Compare commits

..
Author SHA1 Message Date
spsaefan adc9599515 test Jenkins build
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-06-22 10:39:08 +02:00
56 changed files with 2602 additions and 4160 deletions
+5 -14
View File
@@ -6,19 +6,10 @@ build
.vscode .vscode
# Ingore pyhton cache # Ingore pyhton cache
__pycache__ __pycache__
# Ignore macos # Ignore macos
.DS_Store .DS_Store
# Ignore generated python code
# Ignore local environment files src/python/account/
.env
.env.*
**/.env
**/.env.*
!.env.example
!**/.env.example
# Ignore generated python code
src/python/account/
*.pyc *.pyc
@@ -26,4 +17,4 @@ node_modules/
angular-app/.angular angular-app/.angular
# Ignore sentence-transformer local model cache # Ignore sentence-transformer local model cache
service/sentence_transformer/models/ service/sentence_transformer/models/␍
+1 -1
View File
@@ -49,7 +49,7 @@ task exportOpenApiSpec(type: Exec) {
commandLine 'docker', 'run', '--rm', commandLine 'docker', 'run', '--rm',
'--platform', "${targetPlatform}", '--platform', "${targetPlatform}",
'-w', '/home', '-w', '/home',
//'-v', "${projectDir}/src/main:/home", the source code is already baked into the image at build time '-v', "${projectDir}/src/main:/home",
'-v', "${openApiDir}:/mnt/openapi", '-v', "${openApiDir}:/mnt/openapi",
'-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'", '-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'",
'--name', "${imageName}-service-openapi", '--name', "${imageName}-service-openapi",
+41 -101
View File
@@ -1,13 +1,17 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
""" """
Script to fetch all topics from 'openalex-topics', One-time script to fetch all topics from 'openalex-topics',
vectorize display names, full descriptions, and individual keywords using the sentence-transformers model, vectorize display names and chunked descriptions using the sentence-transformers model,
and push them to the 'topicvectors' index with multi-vector mapping. and push them to the 'topicvectors' index with multi-vector hybrid mapping.
""" """
import os
import sys import sys
import json import json
import base64
import re
from pathlib import Path from pathlib import Path
import httpx import httpx
import numpy as np
from dotenv import load_dotenv from dotenv import load_dotenv
# Add service/src/main to python path to load settings # Add service/src/main to python path to load settings
@@ -20,10 +24,8 @@ sys.path.append(str(project_root / "service" / "src" / "main"))
from inse.config import settings from inse.config import settings
ELASTIC_URL = settings.elasticsearch_url ELASTIC_URL = settings.elasticsearch_url
if ELASTIC_URL and not ELASTIC_URL.endswith("/"):
ELASTIC_URL += "/"
API_KEY = settings.elasticsearch_api_key API_KEY = settings.elasticsearch_api_key
MODEL_NAME = settings.sentence_transformers_model_name MODEL_NAME = "paraphrase-multilingual-mpnet-base-v2"
# Import sentence-transformers # Import sentence-transformers
from sentence_transformers import SentenceTransformer from sentence_transformers import SentenceTransformer
@@ -33,6 +35,14 @@ headers = {
"Content-Type": "application/json" "Content-Type": "application/json"
} }
def split_into_sentences(text):
if not text:
return []
# Split on period, exclamation, or question mark followed by whitespace
sentences = re.split(r'(?<=[.!?])\s+', text.strip())
# Filter out empty or extremely short sentences
return [s for s in sentences if len(s.strip()) > 3]
def fetch_all_topics(): def fetch_all_topics():
print("Fetching topics from 'openalex-topics'...") print("Fetching topics from 'openalex-topics'...")
topics = [] topics = []
@@ -65,67 +75,7 @@ def fetch_all_topics():
print(f"Total topics fetched: {len(topics)}") print(f"Total topics fetched: {len(topics)}")
return topics return topics
def update_mappings(): def bulk_index_topics(topics, display_name_vectors, nested_description_vectors):
print("Checking/updating mappings for 'topicvectors'...")
mapping_payload = {
"properties": {
"display_name_vector": {
"type": "dense_vector",
"dims": 768,
"index": True,
"similarity": "cosine",
"index_options": {
"type": "int8_hnsw",
"m": 16,
"ef_construction": 100
}
},
"description_vector": {
"type": "dense_vector",
"dims": 768,
"index": True,
"similarity": "cosine",
"index_options": {
"type": "int8_hnsw",
"m": 16,
"ef_construction": 100
}
},
"keyword_vectors": {
"type": "nested",
"properties": {
"vector": {
"type": "dense_vector",
"dims": 768,
"index": True,
"similarity": "cosine",
"index_options": {
"type": "int8_hnsw",
"m": 16,
"ef_construction": 100
}
}
}
}
}
}
with httpx.Client(timeout=30.0) as client:
# Check if index exists
check_resp = client.get(f"{ELASTIC_URL}topicvectors", headers=headers)
if check_resp.status_code == 404:
print("Index 'topicvectors' does not exist. Creating it...")
create_payload = {
"mappings": mapping_payload
}
resp = client.put(f"{ELASTIC_URL}topicvectors", json=create_payload, headers=headers)
resp.raise_for_status()
else:
print("Index 'topicvectors' exists. Updating mappings...")
resp = client.put(f"{ELASTIC_URL}topicvectors/_mapping", json=mapping_payload, headers=headers)
resp.raise_for_status()
print("Mappings update process completed.")
def bulk_index_topics(topics, display_name_vectors, description_vectors, keyword_vectors_list):
print("Bulk indexing vectorized topics into 'topicvectors'...") print("Bulk indexing vectorized topics into 'topicvectors'...")
batch_size = 500 batch_size = 500
@@ -133,24 +83,22 @@ def bulk_index_topics(topics, display_name_vectors, description_vectors, keyword
for i in range(0, len(topics), batch_size): for i in range(0, len(topics), batch_size):
batch_topics = topics[i:i+batch_size] batch_topics = topics[i:i+batch_size]
batch_name_vecs = display_name_vectors[i:i+batch_size] batch_name_vecs = display_name_vectors[i:i+batch_size]
batch_desc_vecs = description_vectors[i:i+batch_size] batch_desc_vecs_list = nested_description_vectors[i:i+batch_size]
batch_kw_vecs_list = keyword_vectors_list[i:i+batch_size]
bulk_lines = [] bulk_lines = []
for t, name_vec, desc_vec, kw_vecs in zip(batch_topics, batch_name_vecs, batch_desc_vecs, batch_kw_vecs_list): for t, name_vec, desc_vecs in zip(batch_topics, batch_name_vecs, batch_desc_vecs_list):
source = t["_source"] source = t["_source"]
source.pop("siblings", None) # drop siblings field when making the copy # Remove deprecated single vector if present
if "vector" in source:
del source["vector"]
# Assign name vector as a standard float list # Assign name vector as a standard float list
source["display_name_vector"] = name_vec.tolist() source["display_name_vector"] = name_vec.tolist()
# Assign description vector # Assign nested description vectors as standard float lists
source["description_vector"] = desc_vec.tolist() source["description_vectors"] = [
{"vector": vec.tolist()} for vec in desc_vecs
# Assign nested keyword vectors
source["keyword_vectors"] = [
{"vector": vec.tolist()} for vec in kw_vecs
] ]
# Meta line # Meta line
@@ -176,8 +124,6 @@ def bulk_index_topics(topics, display_name_vectors, description_vectors, keyword
print(f"Indexed batch {i} to {i + len(batch_topics)}") print(f"Indexed batch {i} to {i + len(batch_topics)}")
def main(): def main():
update_mappings()
topics = fetch_all_topics() topics = fetch_all_topics()
if not topics: if not topics:
print("No topics found. Exiting.") print("No topics found. Exiting.")
@@ -187,50 +133,44 @@ def main():
model = SentenceTransformer(MODEL_NAME) model = SentenceTransformer(MODEL_NAME)
# 1. Gather all texts to embed # 1. Gather all texts to embed
keywords_by_topic = [] display_names = []
description_sentences_by_topic = []
all_texts_to_embed = [] all_texts_to_embed = []
for t in topics: for t in topics:
source = t["_source"] source = t["_source"]
name = source.get("display_name") or "" name = source.get("display_name") or ""
display_names.append(name)
all_texts_to_embed.append(name) all_texts_to_embed.append(name)
desc = source.get("description") or "" desc = source.get("description") or ""
all_texts_to_embed.append(desc) sentences = split_into_sentences(desc)
description_sentences_by_topic.append(sentences)
all_texts_to_embed.extend(sentences)
kws = source.get("keywords") or [] print(f"Embedding {len(all_texts_to_embed)} texts (display names and description passages)...")
if not isinstance(kws, list):
kws = [kws] if kws else []
keywords_by_topic.append(kws)
all_texts_to_embed.extend(kws)
print(f"Embedding {len(all_texts_to_embed)} texts (display names, descriptions, and keywords)...")
all_vectors = model.encode(all_texts_to_embed, show_progress_bar=True, batch_size=32) all_vectors = model.encode(all_texts_to_embed, show_progress_bar=True, batch_size=32)
# 2. Map embeddings back to topics # 2. Map embeddings back to topics
display_name_vectors = [] display_name_vectors = []
description_vectors = [] nested_description_vectors = []
keyword_vectors_list = []
vector_idx = 0 vector_idx = 0
for idx, t in enumerate(topics): for idx, t in enumerate(topics):
# First vector is the display name
display_name_vectors.append(all_vectors[vector_idx]) display_name_vectors.append(all_vectors[vector_idx])
vector_idx += 1 vector_idx += 1
description_vectors.append(all_vectors[vector_idx]) # Next N vectors are the description chunks
vector_idx += 1 sentences = description_sentences_by_topic[idx]
topic_desc_vecs = []
kws = keywords_by_topic[idx] for _ in range(len(sentences)):
topic_kw_vecs = [] topic_desc_vecs.append(all_vectors[vector_idx])
for _ in range(len(kws)):
topic_kw_vecs.append(all_vectors[vector_idx])
vector_idx += 1 vector_idx += 1
keyword_vectors_list.append(topic_kw_vecs) nested_description_vectors.append(topic_desc_vecs)
# Bulk index # Bulk index
bulk_index_topics(topics, display_name_vectors, description_vectors, keyword_vectors_list) bulk_index_topics(topics, display_name_vectors, nested_description_vectors)
print("Done!") print("Done!")
if __name__ == "__main__": if __name__ == "__main__":
+114
View File
@@ -0,0 +1,114 @@
{
"query": "localization",
"max_score": 23.237041,
"results": [
{
"topic_name": "Indoor and Outdoor Localization Technologies",
"score": 23.237041
},
{
"topic_name": "Robotics and Sensor-Based Localization",
"score": 21.511477
},
{
"topic_name": "Spectral Theory in Mathematical Physics",
"score": 14.039959
},
{
"topic_name": "Socioeconomic Development in MENA",
"score": 11.518878
},
{
"topic_name": "Electrical Fault Detection and Protection",
"score": 10.770052
},
{
"topic_name": "Machine Learning in Bioinformatics",
"score": 10.322677
},
{
"topic_name": "Software System Performance and Reliability",
"score": 10.112644
},
{
"topic_name": "Quantum many-body systems",
"score": 10.112644
},
{
"topic_name": "Random lasers and scattering media",
"score": 10.112644
},
{
"topic_name": "Insect Pheromone Research and Control",
"score": 9.910988
},
{
"topic_name": "Tactile and Sensory Interactions",
"score": 9.910988
},
{
"topic_name": "Handwritten Text Recognition Techniques",
"score": 9.910988
},
{
"topic_name": "Integrated Circuits and Semiconductor Failure Analysis",
"score": 9.910988
},
{
"topic_name": "Medical Imaging and Analysis",
"score": 9.7172165
},
{
"topic_name": "Microwave Imaging and Scattering Analysis",
"score": 9.7172165
},
{
"topic_name": "Neurology and Historical Studies",
"score": 9.7172165
},
{
"topic_name": "High-Velocity Impact and Material Behavior",
"score": 9.7172165
},
{
"topic_name": "Software Engineering Research",
"score": 9.530875
},
{
"topic_name": "Software Testing and Debugging Techniques",
"score": 9.530875
},
{
"topic_name": "Digital Media Forensic Detection",
"score": 9.530875
},
{
"topic_name": "Infrared Thermography in Medicine",
"score": 9.351548
},
{
"topic_name": "Explainable Artificial Intelligence (XAI)",
"score": 9.351548
},
{
"topic_name": "Underwater Vehicles and Communication Systems",
"score": 9.351548
},
{
"topic_name": "Diffusion and Search Dynamics",
"score": 8.8518915
},
{
"topic_name": "Direction-of-Arrival Estimation Techniques",
"score": 5.968384
},
{
"topic_name": "Retinal Imaging and Analysis",
"score": 5.6107
},
{
"topic_name": "Radar Systems and Signal Processing",
"score": 4.721418
}
]
}
+19
View File
@@ -0,0 +1,19 @@
ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic/
ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/
LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212
LLM_MODEL=gemma4-e4b
# Patent search (EPO + USPTO)
PATENT_ELASTICSEARCH_URL=https://inse.nes.uni-due.de/elastic
PATENT_ELASTICSEARCH_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
ELASTICSEARCH_URL=https://project.nes.uni-due.de/elastic
ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic
ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
LLM_API_URL=https://project.nes.uni-due.de/llm2/v1/
LLM_API_KEY=c2d5e7ccf7a4760dd3d19bed2caed9d85ff7437400e0ea82a6d6f912ebc2f212
LLM_MODEL=gemma4-e4b
-39
View File
@@ -1,39 +0,0 @@
# Database config
DATABASE_URL=sqlite:///../data/inse-sqlite.db
DATABASE_DEBUG=false
DATABASE_INIT=true
# Authorization config
AUTH_DISABLED=false
AUTH_STANDALONE=true
AUTH_SECRET=change-me
# OpenAlex config
OPENALEX_WORKS_SEARCH_INDEX=openalex-works*
OPENALEX_WORKS_SEARCH_TIMEOUT_SECONDS=30.0
OPENALEX_API_BASE_URL=https://api.openalex.org
OPENALEX_API_KEY=
OPENALEX_API_TIMEOUT_SECONDS=30.0
# Patent Elasticsearch config
PATENT_ELASTICSEARCH_URL=
PATENT_ELASTICSEARCH_API_KEY=
# LLM config
LLM_API_URL=
LLM_API_KEY=
LLM_MODEL=
# Sentence Transformers config
SENTENCE_TRANSFORMERS_MODEL_NAME=paraphrase-multilingual-mpnet-base-v2
# Elasticsearch config
ELASTICSEARCH_URL=
ELASTICSEARCH_API_KEY=
ELASTICSEARCH_INSE_URL=
ELASTICSEARCH_INSE_API_KEY=
# App config
ALLOWED_ORIGINS=["http://localhost:4200"]
SERVERS=[{"url":"http://localhost:8000","description":"Local development server"}]
LOGGING_LEVEL=DEBUG
-3
View File
@@ -45,9 +45,6 @@ class Settings(BaseSettings):
llm_api_key: Optional[str] = None llm_api_key: Optional[str] = None
llm_model: Optional[str] = None llm_model: Optional[str] = None
# Sentence Transformers config
sentence_transformers_model_name: str = "paraphrase-multilingual-mpnet-base-v2"
# Elasticsearch config # Elasticsearch config
elasticsearch_url: str = "https://project.nes.uni-due.de/elastic" elasticsearch_url: str = "https://project.nes.uni-due.de/elastic"
elasticsearch_api_key: Optional[str] = None elasticsearch_api_key: Optional[str] = None
+47 -66
View File
@@ -256,19 +256,10 @@ def _datetime_str_or_none(value: Any) -> str | None:
return f"{text}T00:00:00Z" return f"{text}T00:00:00Z"
return text return text
# Configuration for vector search similarity thresholds and boosts
SIMILARITY_THRESHOLD = 0.62
BOOST_LEXICAL = 1.0
# higher values for semantic weights, because cosine similarity is between 0 and 1
BOOST_DISPLAY_NAME_VECTOR = 30.0
BOOST_DESCRIPTION_VECTOR = 15.0
BOOST_KEYWORD_VECTORS = 25.0
async def vector_search_topics( async def vector_search_topics(
*, *,
query: str, query: str,
limit: int = 25, limit: int = 25,
search_type: str = "hybrid",
) -> TopicsListResponse: ) -> TopicsListResponse:
""" """
Perform a semantic similarity search on the topicvectors index. Perform a semantic similarity search on the topicvectors index.
@@ -296,70 +287,53 @@ async def vector_search_topics(
) )
# 2. Query Elasticsearch using standard Bool Should hybrid search # 2. Query Elasticsearch using standard Bool Should hybrid search
should_clauses = []
# Lexical multi_match search (only in hybrid mode)
if search_type == "hybrid":
should_clauses.append({
"multi_match": {
"query": query,
"fields": [
"display_name^3",
"keywords^2",
"description^1"
],
"boost": BOOST_LEXICAL
}
})
# Semantic KNN clauses
should_clauses.extend([
{
"knn": {
"field": "display_name_vector",
"query_vector": query_vector,
"similarity": SIMILARITY_THRESHOLD,
"boost": BOOST_DISPLAY_NAME_VECTOR,
"k": 500,
"num_candidates": 500
}
},
{
"knn": {
"field": "description_vector",
"query_vector": query_vector,
"similarity": SIMILARITY_THRESHOLD,
"boost": BOOST_DESCRIPTION_VECTOR,
"k": 500,
"num_candidates": 500
}
},
{
"nested": {
"path": "keyword_vectors",
"query": {
"knn": {
"field": "keyword_vectors.vector",
"query_vector": query_vector,
"similarity": SIMILARITY_THRESHOLD,
"k": 500,
"num_candidates": 500
}
},
"score_mode": "max",
"boost": BOOST_KEYWORD_VECTORS
}
}
])
body = { body = {
"query": { "query": {
"bool": { "bool": {
"should": should_clauses "should": [
{
"multi_match": {
"query": query,
"fields": [
"display_name^3",
"keywords^2",
"description^1"
],
"boost": 1.0
}
},
{
"knn": {
"field": "display_name_vector",
"query_vector": query_vector,
"k": limit,
"num_candidates": 100,
"similarity": 0.62,
"boost": 2.0
}
},
{
"nested": {
"path": "description_vectors",
"query": {
"knn": {
"field": "description_vectors.vector",
"query_vector": query_vector,
"k": limit,
"num_candidates": 100,
"similarity": 0.62
}
},
"score_mode": "max",
"boost": 1.0
}
}
]
} }
}, },
"_source": { "_source": {
"excludes": ["display_name_vector", "description_vector", "keyword_vectors", "description"] # remove unrequired fields "excludes": ["display_name_vector", "description_vectors", "description", "siblings"] # remove unrequired fields (description, sibling currently not needed)
}, },
"size": limit "size": limit
} }
@@ -380,6 +354,13 @@ async def vector_search_topics(
# 3. Format result # 3. Format result
hits = raw_results.get("hits", {}).get("hits", []) hits = raw_results.get("hits", {}).get("hits", [])
# Log scores to JSON for threshold analysis TODO: Remove after finetune
try:
from .score_logger import log_scores_to_json
log_scores_to_json(hits, query)
except Exception as exc:
logger.warning(f"Could not log search scores: {exc}")
total = len(hits) total = len(hits)
results = [hit.get("_source", {}) for hit in hits] results = [hit.get("_source", {}) for hit in hits]
@@ -0,0 +1,36 @@
import json
from pathlib import Path
from typing import Any, Dict, List
def log_scores_to_json(hits: List[Dict[str, Any]], query: str) -> None:
"""
Utility function to log the names and scores of all vector search hits to a JSON file.
This helps in debugging and manually tweaking the similarity score thresholds.
"""
scores_data = []
for hit in hits:
source = hit.get("_source", {})
topic_name = source.get("display_name") or source.get("name") or "Unknown"
score = hit.get("_score", 0.0)
scores_data.append({
"topic_name": topic_name,
"score": score
})
data_dir = Path("/data")
output_file = data_dir / "search_scores.json"
log_payload = {
"query": query,
"max_score": hits[0].get("_score", 0.0) if hits else 0.0,
"results": scores_data
}
try:
with open(output_file, "w", encoding="utf-8") as f:
json.dump(log_payload, f, indent=2, ensure_ascii=False)
print(f"DEBUG: Saved search scores for query '{query}' to {output_file}")
except Exception as exc:
print(f"DEBUG: Failed to save search scores: {exc}")
-5
View File
@@ -129,14 +129,9 @@ async def vector_search_topics(
int, int,
Query(description="Maximum number of topics to return.", ge=1, le=100), Query(description="Maximum number of topics to return.", ge=1, le=100),
] = 25, ] = 25,
search_type: Annotated[
str,
Query(alias="searchType", description="Search approach: 'hybrid' or 'semantic'."),
] = "hybrid",
): ):
return await logic.vector_search_topics( return await logic.vector_search_topics(
query=query, query=query,
limit=limit, limit=limit,
search_type=search_type,
) )
+1 -3
View File
@@ -38,7 +38,6 @@ def get_persons_data(hit:dict):
return author return author
from sentence_transformers import SentenceTransformer from sentence_transformers import SentenceTransformer
from .config import settings
# Sentence Transformer Model # Sentence Transformer Model
_model: SentenceTransformer | None = None _model: SentenceTransformer | None = None
@@ -56,6 +55,5 @@ def get_model():
if os.environ.get("SENTENCE_TRANSFORMERS_HOME") == "/models": if os.environ.get("SENTENCE_TRANSFORMERS_HOME") == "/models":
os.environ["HF_HUB_OFFLINE"] = "1" os.environ["HF_HUB_OFFLINE"] = "1"
model_name = settings.sentence_transformers_model_name _model = SentenceTransformer("paraphrase-multilingual-mpnet-base-v2")
_model = SentenceTransformer(model_name)
return _model return _model
+1 -15
View File
@@ -24,18 +24,4 @@ export * from './topics.service';
import { TopicsService } from './topics.service'; import { TopicsService } from './topics.service';
export * from './works.service'; export * from './works.service';
import { WorksService } from './works.service'; import { WorksService } from './works.service';
export const APIS = [ export const APIS = [CompanyConnectionsService, FundingService, INSEAccountServiceService, INSEServiceService, InstitutionsService, ItemsService, NewsService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, TopicsService, WorksService];
CompanyConnectionsService,
FundingService,
INSEAccountServiceService,
INSEServiceService,
InstitutionsService,
ItemsService,
NewsService,
PatentsService,
PersonNetworkService,
PersonsService,
ProjectsService,
TopicsService,
WorksService,
];
File diff suppressed because it is too large Load Diff
+66 -119
View File
@@ -1,7 +1,7 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
@@ -9,18 +9,12 @@
*/ */
/* tslint:disable:no-unused-variable member-ordering */ /* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core'; import { Inject, Injectable, Optional } from '@angular/core';
import { import { HttpClient, HttpHeaders, HttpParams,
HttpClient, HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
HttpHeaders, } from '@angular/common/http';
HttpParams, import { CustomHttpParameterCodec } from '../encoder';
HttpResponse, import { Observable } from 'rxjs';
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore // @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError'; import { HTTPValidationError } from '../model/hTTPValidationError';
@@ -28,121 +22,74 @@ import { HTTPValidationError } from '../model/hTTPValidationError';
import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse'; import { PatentsByAuthorResponse } from '../model/patentsByAuthorResponse';
// @ts-ignore // @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration'; import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service'; import { BaseService } from '../api.base.service';
@Injectable({ @Injectable({
providedIn: 'root', providedIn: 'root'
}) })
export class PatentsService extends BaseService { export class PatentsService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
/** constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
* Get patents matched to an author by name. super(basePath, configuration);
* @endpoint get /api/inse-service/authors/{author_id}/patents
* @param authorId
* @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 getPatentsByAuthor(
authorId: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<PatentsByAuthorResponse>;
public getPatentsByAuthor(
authorId: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<PatentsByAuthorResponse>>;
public getPatentsByAuthor(
authorId: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<PatentsByAuthorResponse>>;
public getPatentsByAuthor(
authorId: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error(
'Required parameter authorId was null or undefined when calling getPatentsByAuthor.',
);
} }
let localVarHeaders = this.defaultHeaders; /**
* Get patents matched to an author by name.
* @endpoint get /api/inse-service/authors/{author_id}/patents
* @param authorId
* @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 getPatentsByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PatentsByAuthorResponse>;
public getPatentsByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PatentsByAuthorResponse>>;
public getPatentsByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PatentsByAuthorResponse>>;
public getPatentsByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getPatentsByAuthor.');
}
const localVarHttpHeaderAcceptSelected: string | undefined = let localVarHeaders = this.defaultHeaders;
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']); const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
if (localVarHttpHeaderAcceptSelected !== undefined) { 'application/json'
localVarHeaders = localVarHeaders.set( ]);
'Accept', if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHttpHeaderAcceptSelected, 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/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/patents`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PatentsByAuthorResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
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/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/patents`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PatentsByAuthorResponse>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
} }
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,25 +1,27 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
* Do not edit the class manually. * Do not edit the class manually.
*/ */
export interface EuOrganizationProjectSummary {
/** export interface EuOrganizationProjectSummary {
* The unique identifier of the organization. /**
*/ * The unique identifier of the organization.
organization_id: string; */
/** organization_id: string;
* The unique identifier of the project. /**
*/ * The unique identifier of the project.
project_id: string; */
title?: string | null; project_id: string;
start_date?: string | null; title?: string | null;
end_date?: string | null; start_date?: string | null;
acronym?: string | null; end_date?: string | null;
ec_contribution?: number | null; acronym?: string | null;
ec_contribution?: number | null;
} }
@@ -1,7 +1,7 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
@@ -9,21 +9,23 @@
*/ */
import { EuOrganizationProjectSummary } from './euOrganizationProjectSummary'; import { EuOrganizationProjectSummary } from './euOrganizationProjectSummary';
export interface EuOrganizationProjectSummaryPage {
/** export interface EuOrganizationProjectSummaryPage {
* The current page number. /**
*/ * The current page number.
page?: number; */
/** page?: number;
* The requested page size. /**
*/ * The requested page size.
size?: number; */
/** size?: number;
* The total number of items. /**
*/ * The total number of items.
total?: number; */
/** total?: number;
* The organization project summaries on this page. /**
*/ * The organization project summaries on this page.
elements?: Array<EuOrganizationProjectSummary>; */
elements?: Array<EuOrganizationProjectSummary>;
} }
+20 -16
View File
@@ -1,7 +1,7 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
@@ -9,19 +9,23 @@
*/ */
import { ProjectType } from './projectType'; import { ProjectType } from './projectType';
export interface FundingProject {
/** export interface FundingProject {
* The type of the project. /**
*/ * The type of the project.
type: ProjectType; */
/** type: ProjectType;
* The unique identifier of the project. /**
*/ * The unique identifier of the project.
id: string; */
title?: string | null; id: string;
acronym?: string | null; title?: string | null;
start_date?: string | null; acronym?: string | null;
end_date?: string | null; start_date?: string | null;
funding_amount?: number | null; end_date?: string | null;
funding_amount?: number | null;
} }
export namespace FundingProject {} export namespace FundingProject {
}
+7 -5
View File
@@ -1,15 +1,17 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
* Do not edit the class manually. * Do not edit the class manually.
*/ */
export interface MentionedPerson {
name: string; export interface MentionedPerson {
is_ude?: boolean; name: string;
person_id?: string | null; is_ude?: boolean;
person_id?: string | null;
} }
+11 -9
View File
@@ -1,19 +1,21 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
* Do not edit the class manually. * Do not edit the class manually.
*/ */
export interface NewsArticle {
id: string; export interface NewsArticle {
date?: string | null; id: string;
maintitle?: string | null; date?: string | null;
author?: string | null; maintitle?: string | null;
url?: string | null; author?: string | null;
relevant?: boolean | null; url?: string | null;
snippet?: string | null; relevant?: boolean | null;
snippet?: string | null;
} }
+13 -11
View File
@@ -1,7 +1,7 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
@@ -9,14 +9,16 @@
*/ */
import { MentionedPerson } from './mentionedPerson'; import { MentionedPerson } from './mentionedPerson';
export interface NewsArticleDetail {
id: string; export interface NewsArticleDetail {
date?: string | null; id: string;
maintitle?: string | null; date?: string | null;
author?: string | null; maintitle?: string | null;
url?: string | null; author?: string | null;
relevant?: boolean | null; url?: string | null;
snippet?: string | null; relevant?: boolean | null;
full_content?: string | null; snippet?: string | null;
authors?: Array<MentionedPerson>; full_content?: string | null;
authors?: Array<MentionedPerson>;
} }
+8 -6
View File
@@ -1,7 +1,7 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
@@ -9,9 +9,11 @@
*/ */
import { NewsArticle } from './newsArticle'; import { NewsArticle } from './newsArticle';
export interface NewsPage {
total: number; export interface NewsPage {
page: number; total: number;
page_size: number; page: number;
results: Array<NewsArticle>; page_size: number;
results: Array<NewsArticle>;
} }
+14 -12
View File
@@ -1,22 +1,24 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
* Do not edit the class manually. * Do not edit the class manually.
*/ */
export interface PatentEntry {
patent_id: string; export interface PatentEntry {
source: string; patent_id: string;
title?: string | null; source: string;
abstract?: string | null; title?: string | null;
publication_date?: string | null; 'abstract'?: string | null;
publication_year?: string | null; publication_date?: string | null;
inventors?: Array<string>; publication_year?: string | null;
assignees?: Array<string>; inventors?: Array<string>;
ipc?: Array<string>; assignees?: Array<string>;
country?: string | null; ipc?: Array<string>;
country?: string | null;
} }
@@ -1,7 +1,7 @@
/** /**
* Innovation Search Engine API * Innovation Search Engine API
* *
* *
* *
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech * https://openapi-generator.tech
@@ -9,9 +9,11 @@
*/ */
import { PatentEntry } from './patentEntry'; import { PatentEntry } from './patentEntry';
export interface PatentsByAuthorResponse {
author_id: string; export interface PatentsByAuthorResponse {
author_name?: string | null; author_id: string;
patent_count: number; author_name?: string | null;
patents: Array<PatentEntry>; patent_count: number;
patents: Array<PatentEntry>;
} }
@@ -4,10 +4,19 @@
<div class="funding-area"> <div class="funding-area">
<mat-card appearance="outlined"> <mat-card appearance="outlined">
<mat-card-content> <mat-card-content>
<app-query-param-input <mat-form-field style="width: 100%">
label="Suche nach Themen" <mat-label>Suche nach Themen</mat-label>
queryParamKey="search" /> <input
matInput
type="search"
[debounceTime]="300"
[(debouncedValue)]="urlSearchTerm"
(debouncedValueChange)="handleSearchTermChange($event)" />
<mat-icon matPrefix>search</mat-icon>
<button matIconButton matSuffix (click)="clearSearchTerm()">
<mat-icon>clear</mat-icon>
</button>
</mat-form-field>
<mat-tab-group <mat-tab-group
[selectedIndex]="tabIndex()" [selectedIndex]="tabIndex()"
(selectedTabChange)="selectedTabChange($event)"> (selectedTabChange)="selectedTabChange($event)">
@@ -15,20 +24,24 @@
<app-data-table <app-data-table
[data]="euProjectData" [data]="euProjectData"
[columns]="euProjectColumns" [columns]="euProjectColumns"
queryParamSortKey="sort_by" [activeSortKey]="urlSortKey()"
queryParamSortDirectionKey="sort_direction" /> [sortDirection]="urlSortDirection()"
(sortChange)="handleSortChange($event)" />
</mat-tab> </mat-tab>
<mat-tab label="Bund"> <mat-tab label="Bund">
<app-data-table <app-data-table
[data]="bundProjectData" [data]="bundProjectData"
[columns]="bundProjectColumns" [columns]="bundProjectColumns"
queryParamSortKey="sort_by" [activeSortKey]="urlSortKey()"
queryParamSortDirectionKey="sort_direction" /> [sortDirection]="urlSortDirection()"
(sortChange)="handleSortChange($event)" />
</mat-tab> </mat-tab>
</mat-tab-group> </mat-tab-group>
<app-query-param-paginator <mat-paginator
[total]="pageTotal()" [length]="this.pageTotal()"
[pageSizeOptions]="[10, 20, 50]" /> [pageSize]="this.pageSize()"
[pageIndex]="this.pageIndex()"
(page)="handlePageChange($event)" />
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
<div class="funding-info-section"> <div class="funding-info-section">
@@ -62,7 +75,9 @@
undefined undefined
" /> " />
<app-person-network-info-card <app-person-network-info-card
[description]="'Durchschnittliche jährliche Förderung durch die Europäische Union'" [description]="
'Durchschnittliche jährliche Förderung durch die Europäische Union'
"
[value]=" [value]="
(euAverageAnnualFunding() (euAverageAnnualFunding()
| currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined | currency: 'EUR' : 'symbol' : '1.0-0' : 'de') ?? undefined
@@ -4,6 +4,7 @@ import {
effect, effect,
input, input,
OnInit, OnInit,
signal,
TemplateRef, TemplateRef,
viewChild, viewChild,
} from '@angular/core'; } from '@angular/core';
@@ -18,6 +19,7 @@ import {
import { MatCardModule } from '@angular/material/card'; import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
import { MatTabChangeEvent, MatTabsModule } from '@angular/material/tabs'; import { MatTabChangeEvent, MatTabsModule } from '@angular/material/tabs';
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { import {
@@ -25,13 +27,13 @@ import {
DataTableComponent, DataTableComponent,
} from '../../shared/ui/data-table/data-table.component'; } from '../../shared/ui/data-table/data-table.component';
import { CurrencyPipe, DatePipe } from '@angular/common'; import { CurrencyPipe, DatePipe } from '@angular/common';
import { toSignal } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { Sort, SortDirection } from '@angular/material/sort';
import { DebounceDirective } from '../../directives/debounce.directive';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { InstitutionProjectsFundingGraphComponent } from '../institution-projects-funding-graph/institution-projects-funding-graph.component'; import { InstitutionProjectsFundingGraphComponent } from '../institution-projects-funding-graph/institution-projects-funding-graph.component';
import { PersonNetworkInfoCardComponent } from '../person-network-info-card/person-network-info-card.component'; import { PersonNetworkInfoCardComponent } from '../person-network-info-card/person-network-info-card.component';
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component';
type BundProjectRow = { type BundProjectRow = {
id: string; id: string;
@@ -56,18 +58,18 @@ type EuProjectRow = {
MatCardModule, MatCardModule,
MatFormFieldModule, MatFormFieldModule,
MatTabsModule, MatTabsModule,
MatPaginatorModule,
FormsModule, FormsModule,
MatInputModule, MatInputModule,
DataTableComponent, DataTableComponent,
DatePipe, DatePipe,
CurrencyPipe, CurrencyPipe,
DebounceDirective,
MatIconModule, MatIconModule,
MatButtonModule, MatButtonModule,
InstitutionProjectsFundingGraphComponent, InstitutionProjectsFundingGraphComponent,
PersonNetworkInfoCardComponent, PersonNetworkInfoCardComponent,
RouterModule, RouterModule,
QueryParamPaginatorComponent,
QueryParamInputComponent,
], ],
templateUrl: './institution-projects.component.html', templateUrl: './institution-projects.component.html',
styleUrl: './institution-projects.component.scss', styleUrl: './institution-projects.component.scss',
@@ -115,10 +117,24 @@ export class InstitutionProjectsComponent implements OnInit {
return funding.annual_average_over_period ?? 0; return funding.annual_average_over_period ?? 0;
}); });
urlSortKey = signal<string>('');
urlSortDirection = signal<SortDirection>('');
urlSearchTerm = signal<string>('');
constructor( constructor(
private readonly activatedRoute: ActivatedRoute, private readonly activatedRoute: ActivatedRoute,
private readonly router: Router, private readonly router: Router,
) { ) {
this.activatedRoute.queryParams
.pipe(takeUntilDestroyed())
.subscribe((params) => {
this.urlSortKey.set(params['sort_by'] ?? '');
this.urlSortDirection.set(
(params['sort_direction'] as SortDirection) ?? '',
);
this.urlSearchTerm.set(params['search'] ?? '');
});
effect(() => { effect(() => {
const euPage = this.cordisEuProjectPage(); const euPage = this.cordisEuProjectPage();
if (euPage) { if (euPage) {
@@ -135,6 +151,20 @@ export class InstitutionProjectsComponent implements OnInit {
: []; : [];
} }
}); });
effect(() => {
const searchTerm = this.urlSearchTerm();
if (searchTerm) {
this.router.navigate([], {
queryParams: { search: searchTerm, page: 0, size: 10 },
queryParamsHandling: 'merge',
});
}
});
effect(() => {
console.log('Funding over time data:', this.bundProjectsFunding());
});
} }
readonly queryParams = toSignal(this.activatedRoute.queryParamMap, { readonly queryParams = toSignal(this.activatedRoute.queryParamMap, {
@@ -145,6 +175,12 @@ export class InstitutionProjectsComponent implements OnInit {
return this.queryParams()?.get('project_tab') ?? 'eu'; return this.queryParams()?.get('project_tab') ?? 'eu';
}); });
readonly page = computed(() => {
const pageParam = this.queryParams()?.get('page');
const page = pageParam ? Number.parseInt(pageParam, 10) : 0;
return Number.isNaN(page) ? 0 : page;
});
readonly selectedPage = computed(() => { readonly selectedPage = computed(() => {
if (this.displayedProjects() === 'eu') { if (this.displayedProjects() === 'eu') {
return this.cordisEuProjectPage(); return this.cordisEuProjectPage();
@@ -157,6 +193,14 @@ export class InstitutionProjectsComponent implements OnInit {
return this.selectedPage()?.total ?? 0; return this.selectedPage()?.total ?? 0;
}); });
readonly pageSize = computed(() => {
return this.selectedPage()?.size ?? 10;
});
readonly pageIndex = computed(() => {
return this.selectedPage()?.page ?? 0;
});
ngOnInit(): void { ngOnInit(): void {
this.euProjectColumns = [ this.euProjectColumns = [
{ {
@@ -275,4 +319,32 @@ export class InstitutionProjectsComponent implements OnInit {
queryParamsHandling: 'merge', queryParamsHandling: 'merge',
}); });
} }
handlePageChange(event: PageEvent): void {
this.router.navigate([], {
queryParams: { page: event.pageIndex, size: event.pageSize },
queryParamsHandling: 'merge',
});
}
handleSortChange(event: Sort): void {
this.router.navigate([], {
queryParams: { sort_by: event.active, sort_direction: event.direction },
queryParamsHandling: 'merge',
});
}
handleSearchTermChange(newTerm: string): void {
this.router.navigate([], {
queryParams: { search: newTerm, page: 0, size: 10 },
queryParamsHandling: 'merge',
});
}
clearSearchTerm(): void {
this.router.navigate([], {
queryParams: { search: null, page: 0, size: 10 },
queryParamsHandling: 'merge',
});
}
} }
@@ -4,19 +4,34 @@
<mat-divider /> <mat-divider />
<div class="search-and-sorting"> <div class="search-and-sorting">
<app-query-param-input <mat-form-field style="width: 100%">
[label]="'Suche nach Namen'" <mat-label>Suche nach Namen</mat-label>
[debounceTime]="400" <input
[queryParamKey]="'search'" /> matInput
type="search"
[debounceTime]="300"
[(debouncedValue)]="urlSearchTerm"
(debouncedValueChange)="handleSearchTermChange($event)" />
<mat-icon matPrefix>search</mat-icon>
<button matIconButton matSuffix (click)="clearSearchTerm()">
<mat-icon>clear</mat-icon>
</button>
</mat-form-field>
<div class="sorting"> <div class="sorting">
<app-query-param-selector <select (change)="handleSortFieldChange($event)" [value]="urlSortBy()">
[options]="sortingOptions" <option value="relevance">Relevanz</option>
[queryParamKey]="'sort_by'" /> <option value="name">Name</option>
<option value="works_count">Anzahl Publikationen</option>
<option value="citations_count">Anzahl Zitationen</option>
</select>
<app-query-param-selector <select
[options]="sortingDirectionOptions" (change)="handleSortOrderChange($event)"
[queryParamKey]="'sorting_order'" /> [value]="urlSortingOrder()">
<option value="desc">Absteigend</option>
<option value="asc">Aufsteigend</option>
</select>
</div> </div>
</div> </div>
@@ -91,7 +106,11 @@
<mat-divider /> <mat-divider />
<app-query-param-paginator <mat-paginator
[total]="institutionPageValue.total ?? 0" [length]="institutionPageValue.total"
[pageSizeOptions]="[10, 20, 50]" /> [pageSize]="institutionPageValue.size"
[pageSizeOptions]="[10, 20, 50]"
[pageIndex]="institutionPageValue.page"
(page)="handlePageChange($event)">
</mat-paginator>
</div> </div>
@@ -25,10 +25,26 @@
.cards { .cards {
display: grid; display: grid;
gap: 1.5rem; gap: 1.5rem;
grid-template-columns: repeat(auto-fit, minmax(380px, 1fr)); grid-template-columns: repeat(4, 1fr);
padding: 0 1rem; padding: 0 1rem;
} }
@media (max-width: 900px) {
.cards {
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 600px) {
.cards {
grid-template-columns: 1fr;
}
}
mat-paginator {
background-color: var(--sg-background);
}
.card { .card {
padding: 0.5rem; padding: 0.5rem;
background-color: var(--sg-background); background-color: var(--sg-background);
@@ -1,28 +1,26 @@
import { Component, input } from '@angular/core'; import { Component, effect, input, signal } from '@angular/core';
import { Institution, InstitutionPage } from '../../api'; import { Institution, 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';
import { RouterModule } from '@angular/router'; import { MatInputModule } from '@angular/material/input';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { DebounceDirective } from '../../directives/debounce.directive';
import { MatPaginator, PageEvent } from '@angular/material/paginator';
import { MatDividerModule } from '@angular/material/divider'; import { MatDividerModule } from '@angular/material/divider';
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
import {
QueryParamSelectorComponent,
SelectorOption,
} from '../../shared/ui/query-param-selector/query-param-selector.component';
import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component';
@Component({ @Component({
selector: 'app-institutions', selector: 'app-institutions',
imports: [ imports: [
MatButtonModule, MatButtonModule,
MatCardModule, MatCardModule,
MatInputModule,
MatIconModule, MatIconModule,
DebounceDirective,
MatPaginator,
MatDividerModule, MatDividerModule,
RouterModule, RouterModule,
QueryParamPaginatorComponent,
QueryParamSelectorComponent,
QueryParamInputComponent,
], ],
templateUrl: './institutions.component.html', templateUrl: './institutions.component.html',
styleUrl: './institutions.component.scss', styleUrl: './institutions.component.scss',
@@ -30,21 +28,74 @@ import { QueryParamInputComponent } from '../../shared/ui/query-param-input/quer
export class InstitutionsComponent { export class InstitutionsComponent {
institutionPage = input.required<InstitutionPage>(); institutionPage = input.required<InstitutionPage>();
sortingOptions: SelectorOption[] = [ urlSearchTerm = signal<string>('');
{ value: 'relevance', display_name: 'Relevanz' }, urlSortBy = signal<string>('relevance');
{ value: 'name', display_name: 'Name' }, urlSortingOrder = signal<string>('desc');
{ value: 'works_count', display_name: 'Anzahl Publikationen' },
{ value: 'citations_count', display_name: 'Anzahl Zitationen' }, constructor(
]; private readonly activatedRoute: ActivatedRoute,
sortingDirectionOptions: SelectorOption[] = [ private readonly router: Router,
{ value: 'asc', display_name: 'Aufsteigend' }, ) {
{ value: 'desc', display_name: 'Absteigend' }, this.activatedRoute.queryParams
]; .pipe(takeUntilDestroyed())
.subscribe((params) => {
this.urlSearchTerm.set(params['search'] || '');
this.urlSortBy.set(params['sort_by'] || 'relevance');
this.urlSortingOrder.set(params['sorting_order'] || 'desc');
});
effect(() => {
const searchTerm = this.urlSearchTerm();
this.router.navigate([], {
queryParams: { search: searchTerm },
queryParamsHandling: 'merge',
});
});
}
handleSearchTermChange(newTerm: string): void {
this.router.navigate([], {
queryParams: { search: newTerm },
queryParamsHandling: 'merge',
});
}
clearSearchTerm(): void {
this.router.navigate([], {
queryParams: { search: null },
queryParamsHandling: 'merge',
});
}
handlePageChange(event: PageEvent): void {
this.router.navigate([], {
queryParams: { page: event.pageIndex, size: event.pageSize },
queryParamsHandling: 'merge',
});
}
extractInstitutionId(institution: Institution): string { extractInstitutionId(institution: Institution): string {
return institution.id?.split('/').pop() ?? ''; return institution.id?.split('/').pop() ?? '';
} }
handleSortFieldChange(event: Event): void {
const selectElement = event.target as HTMLSelectElement;
const sortField = selectElement.value;
this.router.navigate([], {
queryParams: { sort_by: sortField },
queryParamsHandling: 'merge',
});
}
handleSortOrderChange(event: Event): void {
const selectElement = event.target as HTMLSelectElement;
const sortOrder = selectElement.value;
this.router.navigate([], {
queryParams: { sorting_order: sortOrder },
queryParamsHandling: 'merge',
});
}
getDisplayName(institution: Institution): string { getDisplayName(institution: Institution): string {
const primary = institution.display_name?.trim(); const primary = institution.display_name?.trim();
if (primary && primary.length > 0) return primary; if (primary && primary.length > 0) return primary;
@@ -1,8 +1,8 @@
<article class="person-card"> <article class="person-card">
<a [routerLink]="['/person', person().id, 'overview']" class="card-header"> <a [routerLink]="['/person', person.id, 'overview']" class="card-header">
<!-- Initials Avatar or Profile Image fallback --> <!-- Initials Avatar or Profile Image fallback -->
<div [skText]="loading()" class="avatar"> <div [skText]="loading" class="avatar">
{{ initials() }} {{ getInitials(person.display_name) }}
</div> </div>
<div class="header-main"> <div class="header-main">
<div class="bookmark"> <div class="bookmark">
@@ -11,43 +11,41 @@
(click)=" (click)="
toggleBookmark(); $event.stopPropagation(); $event.preventDefault() toggleBookmark(); $event.stopPropagation(); $event.preventDefault()
" "
[class.bookmarked]="isBookmarked()" [class.bookmarked]="isBookmarked"
aria-label="Bookmark person"> aria-label="Bookmark person">
<mat-icon>{{ <mat-icon>{{
isBookmarked() ? 'bookmark' : 'bookmark_border' isBookmarked ? 'bookmark' : 'bookmark_border'
}}</mat-icon> }}</mat-icon>
</button> </button>
</div> </div>
<h2 <h2
[skText]="loading()" [skText]="loading"
class="person-name" class="person-name"
[title]="person().display_name ?? ''"> [title]="person.display_name ?? ''">
{{ person().display_name ?? '' }} {{ person.display_name ?? '' }}
</h2> </h2>
<p [skText]="loading()" class="person-id"> <p [skText]="loading" class="person-id">
{{ distinguishingId() }} {{ getDistinguishingId(person) }}
</p> </p>
<p [skText]="loading()" class="stats"> <p [skText]="loading" class="stats">
{{ statsString() }} {{ getStatsString() }}
</p> </p>
<p [skText]="loading()" class="stats"> <p [skText]="loading" class="stats">
{{ hIndexString() }} {{ getHIndexString() }}
</p> </p>
</div> </div>
</a> </a>
<div class="card-body"> <div class="card-body">
@if (institution(); as inst) { @if (institution(person); as inst) {
<div class="institution-row" style="margin-bottom: 8px"> <div class="institution-row" style="margin-bottom: 8px">
<button <span
type="button"
class="institution-tag" class="institution-tag"
[matTooltip]="inst.display_name || ''"
matTooltipPosition="above"
(click)=" (click)="
institutionClick.emit(inst.display_name || ''); institutionClick.emit(inst.display_name || '');
$event.stopPropagation() $event.stopPropagation()
"> "
[title]="inst.display_name || ''">
<mat-icon <mat-icon
style=" style="
font-size: 12px; font-size: 12px;
@@ -59,12 +57,12 @@
>apartment</mat-icon >apartment</mat-icon
> >
<span <span
[skText]="loading()" [skText]="loading"
class="institution-name" class="institution-name"
style="vertical-align: middle" style="vertical-align: middle"
>{{ inst.display_name ?? '' }}</span >{{ inst.display_name ?? '' }}</span
> >
@if (inst.country_code && !loading()) { @if (inst.country_code && !loading) {
<img <img
alt="" alt=""
class="flag-img" class="flag-img"
@@ -77,41 +75,38 @@
>{{ inst.country_code.toUpperCase() }}</span >{{ inst.country_code.toUpperCase() }}</span
> >
} }
</button> </span>
</div> </div>
} }
<div class="topic-row"> <div class="topic-row">
@for (topic of topics(); track topic.id) { @for (topic of topics(person); track topic.id) {
<button <span
type="button" [skText]="loading"
[skText]="loading()"
class="topic-tag" class="topic-tag"
[class.active]="selectedTopics().has(topic.display_name || '')"
[matTooltip]="getTopicTooltip(topic)"
matTooltipPosition="above"
(click)=" (click)="
topicClick.emit(topic.display_name || ''); $event.stopPropagation() topicClick.emit(topic.display_name || ''); $event.stopPropagation()
"> "
{{ topic.display_name }} [title]="getTopicTooltip(topic)"
</button> >{{ topic.display_name }}</span
>
} }
</div> </div>
</div> </div>
<div class="card-footer"> <div class="card-footer">
<div class="action-buttons"> <div class="action-buttons">
<a [routerLink]="['/person', person().id, 'overview']" class="action-btn"> <a [routerLink]="['/person', person.id, 'overview']" class="action-btn">
<mat-icon>visibility</mat-icon> <mat-icon>visibility</mat-icon>
<span>Übersicht</span> <span>Übersicht</span>
</a> </a>
<a <a
[routerLink]="['/person', person().id, 'publications']" [routerLink]="['/person', person.id, 'publications']"
class="action-btn"> class="action-btn">
<mat-icon>menu_book</mat-icon> <mat-icon>menu_book</mat-icon>
<span>Publikationen</span> <span>Publikationen</span>
</a> </a>
<a [routerLink]="['/person', person().id, 'network']" class="action-btn"> <a [routerLink]="['/person', person.id, 'network']" class="action-btn">
<mat-icon>share</mat-icon> <mat-icon>share</mat-icon>
<span>Netzwerk</span> <span>Netzwerk</span>
</a> </a>
@@ -140,9 +140,6 @@
transition: all 0.2s ease; transition: all 0.2s ease;
max-width: 100%; max-width: 100%;
box-sizing: border-box; box-sizing: border-box;
margin: 0;
line-height: normal;
font-family: inherit;
.institution-name { .institution-name {
overflow: hidden; overflow: hidden;
@@ -162,15 +159,10 @@
white-space: nowrap; white-space: nowrap;
} }
&:hover, &:hover {
&:focus-visible {
background: var(--sg-primary); background: var(--sg-primary);
color: #fff; color: #fff;
border-color: var(--sg-primary); border-color: var(--sg-primary);
outline: none;
box-shadow:
0 0 0 2px var(--sg-background),
0 0 0 4px var(--sg-primary);
} }
} }
@@ -231,36 +223,11 @@
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
box-sizing: border-box; box-sizing: border-box;
margin: 0;
line-height: normal;
font-family: inherit;
display: inline-flex;
align-items: center;
&:hover, &:hover {
&:focus-visible {
background: var(--sg-primary-soft); background: var(--sg-primary-soft);
border-color: var(--sg-primary); border-color: var(--sg-primary);
color: var(--sg-primary); color: var(--sg-primary);
outline: none;
box-shadow:
0 0 0 2px var(--sg-background),
0 0 0 4px var(--sg-primary);
}
&.active {
background: var(--sg-primary-soft);
border-color: var(--sg-primary);
color: var(--sg-primary);
font-weight: 700;
box-shadow: 0 0 0 1.5px var(--sg-primary);
&:hover,
&:focus-visible {
box-shadow:
0 0 0 2px var(--sg-background),
0 0 0 4px var(--sg-primary);
}
} }
} }
@@ -1,51 +1,46 @@
import { Component, input, computed, output } from '@angular/core'; import { Component, Input, Output, EventEmitter } from '@angular/core';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { RouterLink } from '@angular/router'; import { RouterLink } from '@angular/router';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import { CustomAuthor, DehydratedInstitution, WorkTopic } from '../../api'; import { CustomAuthor, DehydratedInstitution, WorkTopic } from '../../api';
import { SkTextDirective } from '../../custom-directives/sk-text.directive'; import { SkTextDirective } from '../../custom-directives/sk-text.directive';
@Component({ @Component({
selector: 'app-person-card', selector: 'app-person-card',
standalone: true, standalone: true,
imports: [ imports: [CommonModule, RouterLink, MatIconModule, SkTextDirective],
CommonModule,
RouterLink,
MatIconModule,
SkTextDirective,
MatTooltipModule,
],
templateUrl: './person-card.component.html', templateUrl: './person-card.component.html',
styleUrl: './person-card.component.scss', styleUrl: './person-card.component.scss',
}) })
export class PersonCardComponent { export class PersonCardComponent {
person = input.required<CustomAuthor>(); @Input({ required: true }) person!: CustomAuthor;
isBookmarked = input<boolean>(false); @Input() isBookmarked = false;
loading = input<boolean>(false); @Input() loading = false;
selectedTopics = input<Set<string>>(new Set<string>()); @Output() bookmarkToggle = new EventEmitter<CustomAuthor>();
@Output() topicClick = new EventEmitter<string>();
@Output() institutionClick = new EventEmitter<string>();
bookmarkToggle = output<CustomAuthor>(); getInitials(name: string | null | undefined): string {
topicClick = output<string>();
institutionClick = output<string>();
initials = computed<string>(() => {
const name = this.person().display_name;
if (!name) return 'U'; if (!name) return 'U';
const cleanName = name.replace(/Prof\.|Dr\.|M\.Sc\./g, '').trim(); const cleanName = name.replace(/Prof\.|Dr\.|M\.Sc\./g, '').trim();
const parts = cleanName.split(' '); const parts = cleanName.split(' ');
const first = parts[0]?.[0] || ''; const first = parts[0]?.[0] || '';
const last = parts[parts.length - 1]?.[0] || ''; const last = parts[parts.length - 1]?.[0] || '';
return (first + last).toUpperCase(); return (first + last).toUpperCase();
}); }
institution = computed<DehydratedInstitution | undefined>(() => { getRatingClass(rating: string | null | undefined): string {
const p = this.person(); const r = (rating || '').toLowerCase();
if (p.last_known_institutions?.[0]) { if (r === 'sehr geeignet') return 'very-suitable';
return p.last_known_institutions[0]; if (r === 'geeignet') return 'suitable';
return 'possible';
}
institution(person: CustomAuthor): DehydratedInstitution | undefined {
if (person.last_known_institutions?.[0]) {
return person.last_known_institutions[0];
} }
const affiliations = p.affiliations ?? []; const affiliations = person.affiliations ?? [];
let newestInstitution: DehydratedInstitution | undefined = let newestInstitution: DehydratedInstitution | undefined =
affiliations[0]?.institution ?? undefined; affiliations[0]?.institution ?? undefined;
let newestYear = -1; let newestYear = -1;
@@ -60,51 +55,12 @@ export class PersonCardComponent {
} }
return newestInstitution; return newestInstitution;
}); }
topics = computed<WorkTopic[]>(() => { topics(person: CustomAuthor): WorkTopic[] {
return (this.person().topics ?? []) return (person.topics ?? [])
.filter((t): t is WorkTopic => !!t.display_name) .filter((t): t is WorkTopic => !!t.display_name)
.slice(0, 3); .slice(0, 3);
});
distinguishingId = computed<string>(() => {
const p = this.person();
if (p.orcid) {
return p.orcid.replace('https://orcid.org/', '');
}
return '';
});
statsString = computed<string>(() => {
const works = this.person().works_count;
const citations = this.person().cited_by_count;
const hasWorks = works !== undefined && works !== null;
const hasCitations = citations !== undefined && citations !== null;
if (hasWorks && hasCitations) {
return `Publikationen: ${works} · Zitationen: ${citations}`;
} else if (hasWorks) {
return `Publikationen: ${works}`;
} else if (hasCitations) {
return `Zitationen: ${citations}`;
}
return '';
});
hIndexString = computed<string>(() => {
const hIndex = this.person().summary_stats?.h_index;
if (hIndex !== undefined && hIndex !== null) {
return `h_index: ${hIndex}`;
}
return '';
});
getRatingClass(rating: string | null | undefined): string {
const r = (rating || '').toLowerCase();
if (r === 'sehr geeignet') return 'very-suitable';
if (r === 'geeignet') return 'suitable';
return 'possible';
} }
getTopicTooltip(topic: WorkTopic): string { getTopicTooltip(topic: WorkTopic): string {
@@ -120,7 +76,39 @@ export class PersonCardComponent {
return path; return path;
} }
getDistinguishingId(person: CustomAuthor): string {
if (!person) return '';
if (person.orcid) {
return person.orcid.replace('https://orcid.org/', '');
}
return '';
}
getStatsString(): string {
const works = this.person.works_count;
const citations = this.person.cited_by_count;
const hasWorks = works !== undefined && works !== null;
const hasCitations = citations !== undefined && citations !== null;
if (hasWorks && hasCitations) {
return `Publikationen: ${works} · Zitationen: ${citations}`;
} else if (hasWorks) {
return `Publikationen: ${works}`;
} else if (hasCitations) {
return `Zitationen: ${citations}`;
}
return '';
}
getHIndexString(): string {
const hIndex = this.person.summary_stats?.h_index;
if (hIndex !== undefined && hIndex !== null) {
return `h_index: ${hIndex}`;
}
return '';
}
toggleBookmark(): void { toggleBookmark(): void {
this.bookmarkToggle.emit(this.person()); this.bookmarkToggle.emit(this.person);
} }
} }
@@ -19,8 +19,7 @@
<button <button
mat-icon-button mat-icon-button
(click)="clearSearch()" (click)="clearSearch()"
matTooltip="Suche zurücksetzen" matTooltip="Suche zurücksetzen">
aria-label="Suche zurücksetzen">
<mat-icon>close</mat-icon> <mat-icon>close</mat-icon>
</button> </button>
</div> </div>
@@ -43,10 +42,7 @@
</button> </button>
</span> </span>
} }
<button <button class="clear-all-btn" (click)="clearAllFilters()">
class="clear-all-btn"
(click)="clearAllFilters()"
aria-label="Alle Filter zurücksetzen">
Filter zurücksetzen Filter zurücksetzen
</button> </button>
</div> </div>
@@ -60,18 +56,14 @@
<div class="sort-selector"> <div class="sort-selector">
<span class="sort-label">Sortierung:</span> <span class="sort-label">Sortierung:</span>
<div class="select-wrapper"> <div class="select-wrapper">
<select <select [formControl]="sortValueControl">
[formControl]="sortValueControl"
aria-label="Sortierkriterium">
<option [ngValue]="null">Beste Treffer (Relevanz)</option> <option [ngValue]="null">Beste Treffer (Relevanz)</option>
<option value="works_count">Publikationen</option> <option value="works_count">Publikationen</option>
<option value="cited_by_count">Zitierungen</option> <option value="cited_by_count">Zitierungen</option>
<option value="summary_stats.h_index">h_index</option> <option value="summary_stats.h_index">h_index</option>
</select> </select>
<select <select [formControl]="sortOrderControl">
[formControl]="sortOrderControl"
aria-label="Sortierreihenfolge">
<option value="desc">Absteigend</option> <option value="desc">Absteigend</option>
<option value="asc">Aufsteigend</option> <option value="asc">Aufsteigend</option>
</select> </select>
@@ -95,7 +87,6 @@
[loading]="loading" [loading]="loading"
[person]="person" [person]="person"
[isBookmarked]="isBookmarked(person)" [isBookmarked]="isBookmarked(person)"
[selectedTopics]="selectedTopics()"
(bookmarkToggle)="toggleBookmark($event)" (bookmarkToggle)="toggleBookmark($event)"
(topicClick)="onCardTopicClick($event)" (topicClick)="onCardTopicClick($event)"
(institutionClick)="onCardInstitutionClick($event)"> (institutionClick)="onCardInstitutionClick($event)">
@@ -141,23 +132,19 @@
<input <input
type="text" type="text"
[formControl]="topicSearchControl" [formControl]="topicSearchControl"
aria-label="Thema suchen"
placeholder="Thema suchen..." /> placeholder="Thema suchen..." />
@if (topicSearchControl.value) { @if (topicSearchControl.value) {
<button <button
class="clear-topic-search" class="clear-topic-search"
(click)="topicSearchControl.setValue('')" (click)="topicSearchControl.setValue('')">
aria-label="Themensuche zurücksetzen">
<mat-icon>close</mat-icon> <mat-icon>close</mat-icon>
</button> </button>
} }
</div> </div>
<app-topic-hierarchy <app-topic-hierarchy
[selectedTopics]="selectedTopics()" [selectedTopics]="selectedTopics"
[searchQuery]="topicSearchControl.value" [searchQuery]="topicSearchControl.value"
[searchType]="topicSearchType()"
(searchTypeChange)="onTopicSearchTypeChange($event)"
(selectionChange)="onTopicSelectionChange($event)"> (selectionChange)="onTopicSelectionChange($event)">
</app-topic-hierarchy> </app-topic-hierarchy>
</div> </div>
@@ -171,7 +158,6 @@
type="text" type="text"
[formControl]="institutionControl" [formControl]="institutionControl"
[matAutocomplete]="auto" [matAutocomplete]="auto"
aria-label="Institution suchen"
placeholder="Institution suchen..." placeholder="Institution suchen..."
(keyup.enter)="applySidebarFilters()" /> (keyup.enter)="applySidebarFilters()" />
<mat-autocomplete <mat-autocomplete
@@ -197,8 +183,7 @@
@if (institutionControl.value) { @if (institutionControl.value) {
<button <button
class="clear-topic-search" class="clear-topic-search"
(click)="clearInstitutionFilter()" (click)="clearInstitutionFilter()">
aria-label="Institution zurücksetzen">
<mat-icon>close</mat-icon> <mat-icon>close</mat-icon>
</button> </button>
} }
@@ -213,8 +198,7 @@
"> ">
<mat-checkbox <mat-checkbox
[formControl]="yearFilterEnabledControl" [formControl]="yearFilterEnabledControl"
(change)="applySidebarFilters()" (change)="applySidebarFilters()">
aria-label="Zusammenarbeit nach Jahr filtern">
<span <span
style="font-size: 12px; font-weight: 500; color: var(--sg-text)" style="font-size: 12px; font-weight: 500; color: var(--sg-text)"
>Zusammenarbeit nach Jahr filtern</span >Zusammenarbeit nach Jahr filtern</span
@@ -233,8 +217,7 @@
<mat-radio-group <mat-radio-group
[formControl]="filterModeControl" [formControl]="filterModeControl"
(change)="applySidebarFilters()" (change)="applySidebarFilters()"
style="display: flex; gap: 16px" style="display: flex; gap: 16px">
aria-label="Modus für Jahresfilter">
<mat-radio-button value="in" <mat-radio-button value="in"
><span style="font-size: 12px; color: var(--sg-text)" ><span style="font-size: 12px; color: var(--sg-text)"
>Genau in</span >Genau in</span
@@ -257,7 +240,6 @@
[formControl]="filterYearControl" [formControl]="filterYearControl"
(change)="applySidebarFilters()" (change)="applySidebarFilters()"
(keyup.enter)="applySidebarFilters()" (keyup.enter)="applySidebarFilters()"
aria-label="Jahr"
placeholder="Z. B. 2025" /> placeholder="Z. B. 2025" />
@if (filterYearControl.hasError('min')) { @if (filterYearControl.hasError('min')) {
<mat-error>Jahr muss ≥ 1900 sein</mat-error> <mat-error>Jahr muss ≥ 1900 sein</mat-error>
@@ -273,10 +255,7 @@
<!-- Sidebar Footer Action showing matches count --> <!-- Sidebar Footer Action showing matches count -->
<div class="sidebar-footer"> <div class="sidebar-footer">
<button <button class="submit-btn" (click)="applySidebarFilters()">
class="submit-btn"
(click)="applySidebarFilters()"
aria-label="Gefundene Personen anzeigen">
<span [skText]="loading" <span [skText]="loading"
>{{ total | number: '1.0-0' }} Personen anzeigen</span >{{ total | number: '1.0-0' }} Personen anzeigen</span
> >
@@ -13,64 +13,18 @@
margin: 0 auto; margin: 0 auto;
} }
// Shared flex layouts
.page-header,
.sidebar-header,
.toolbar {
display: flex;
align-items: center;
}
.page-header,
.toolbar {
justify-content: space-between;
}
.sidebar-header,
.toolbar {
border-bottom: 1px solid var(--sg-border);
padding-bottom: 12px;
}
.selection-summary,
.active-filters-row,
.chips-container,
.sort-selector,
.topic-search-wrapper {
display: flex;
align-items: center;
}
.filter-chip {
display: inline-flex;
align-items: center;
}
// Shared column & sidebar column layouts
.results-column,
.empty-state,
.filters-sidebar,
.filter-section {
display: flex;
flex-direction: column;
}
// Shared containers styling
.selection-summary,
.active-filters-row,
.filters-sidebar {
background: var(--sg-surface);
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
}
// Individual styles
.results-column { .results-column {
display: flex;
min-width: 0;
flex-direction: column;
gap: 20px; gap: 20px;
min-width: 0; min-width: 0;
} }
.page-header { .page-header {
display: flex;
justify-content: space-between;
align-items: center;
gap: 16px; gap: 16px;
h1 { h1 {
@@ -88,8 +42,13 @@
} }
.selection-summary { .selection-summary {
display: flex;
align-items: center;
gap: 12px; gap: 12px;
padding: 8px 12px; padding: 8px 12px;
background: var(--sg-surface);
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
strong { strong {
display: block; display: block;
@@ -106,8 +65,13 @@
} }
.active-filters-row { .active-filters-row {
display: flex;
align-items: center;
gap: 10px; gap: 10px;
background: var(--sg-surface);
padding: 8px 16px; padding: 8px 16px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
flex-wrap: wrap; flex-wrap: wrap;
font-size: 13px; font-size: 13px;
} }
@@ -118,11 +82,15 @@
} }
.chips-container { .chips-container {
display: flex;
align-items: center;
gap: 6px; gap: 6px;
flex-wrap: wrap; flex-wrap: wrap;
} }
.filter-chip { .filter-chip {
display: inline-flex;
align-items: center;
gap: 4px; gap: 4px;
padding: 2px 8px; padding: 2px 8px;
background: var(--sg-surface-soft); background: var(--sg-surface-soft);
@@ -131,53 +99,53 @@
font-size: 11px; font-size: 11px;
font-weight: 600; font-weight: 600;
color: var(--sg-text); color: var(--sg-text);
button {
border: none;
background: transparent;
cursor: pointer;
padding: 0;
display: flex;
color: var(--sg-text-soft);
&:hover {
color: var(--sg-text);
}
mat-icon {
font-size: 12px;
width: 12px;
height: 12px;
}
}
} }
// Shared button resets
.filter-chip button,
.clear-topic-search,
.clear-all-btn { .clear-all-btn {
border: none; border: none;
background: transparent; background: transparent;
cursor: pointer; cursor: pointer;
}
.filter-chip button,
.clear-topic-search {
padding: 0;
display: flex;
color: var(--sg-text-soft);
&:hover {
color: var(--sg-text);
}
}
.filter-chip button mat-icon {
font-size: 12px;
width: 12px;
height: 12px;
}
.clear-topic-search mat-icon {
font-size: 14px;
width: 14px;
height: 14px;
}
.clear-all-btn {
font-size: 11px; font-size: 11px;
font-weight: 600; font-weight: 600;
color: var(--sg-warning); color: var(--sg-warning);
text-decoration: underline; text-decoration: underline;
} }
.toolbar {
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid var(--sg-border);
padding-bottom: 12px;
}
.result-count { .result-count {
font-size: 13px; font-size: 13px;
color: var(--sg-text-muted); color: var(--sg-text-muted);
} }
.sort-selector { .sort-selector {
display: flex;
align-items: center;
gap: 8px; gap: 8px;
font-size: 13px; font-size: 13px;
color: var(--sg-text-muted); color: var(--sg-text-muted);
@@ -191,14 +159,6 @@
color: var(--sg-text); color: var(--sg-text);
outline: none; outline: none;
cursor: pointer; cursor: pointer;
transition:
border-color 0.15s,
box-shadow 0.15s;
&:focus-visible {
border-color: var(--sg-primary);
box-shadow: 0 0 0 2px var(--sg-primary-soft);
}
} }
} }
@@ -209,6 +169,8 @@
} }
.empty-state { .empty-state {
display: flex;
flex-direction: column;
align-items: center; align-items: center;
padding: 48px 16px; padding: 48px 16px;
background: var(--sg-surface); background: var(--sg-surface);
@@ -242,14 +204,24 @@ mat-paginator {
} }
.filters-sidebar { .filters-sidebar {
background: var(--sg-surface);
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
padding: 16px; padding: 16px;
box-shadow: var(--sg-shadow-sm); box-shadow: var(--sg-shadow-sm);
display: flex;
flex-direction: column;
gap: 16px;
position: sticky; position: sticky;
top: 16px; top: 16px;
} }
.sidebar-header { .sidebar-header {
display: flex;
align-items: center;
gap: 8px; gap: 8px;
padding-bottom: 12px;
border-bottom: 1px solid var(--sg-border);
mat-icon { mat-icon {
color: var(--sg-primary); color: var(--sg-primary);
@@ -266,6 +238,8 @@ mat-paginator {
} }
.filter-section { .filter-section {
display: flex;
flex-direction: column;
gap: 8px; gap: 8px;
} }
@@ -278,18 +252,13 @@ mat-paginator {
} }
.topic-search-wrapper { .topic-search-wrapper {
position: relative;
display: flex;
align-items: center;
background: var(--sg-surface-soft); background: var(--sg-surface-soft);
border: 1px solid var(--sg-border); border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm); border-radius: var(--sg-radius-sm);
padding: 4px 8px; padding: 4px 8px;
transition:
border-color 0.15s,
box-shadow 0.15s;
&:focus-within {
border-color: var(--sg-primary);
box-shadow: 0 0 0 2px var(--sg-primary-soft);
}
mat-icon { mat-icon {
font-size: 16px; font-size: 16px;
@@ -307,6 +276,20 @@ mat-paginator {
flex-grow: 1; flex-grow: 1;
margin-left: 6px; margin-left: 6px;
} }
.clear-topic-search {
border: none;
background: transparent;
cursor: pointer;
display: flex;
color: var(--sg-text-soft);
mat-icon {
font-size: 14px;
width: 14px;
height: 14px;
}
}
} }
.sidebar-footer { .sidebar-footer {
@@ -324,21 +307,12 @@ mat-paginator {
font-size: 13px; font-size: 13px;
font-weight: 700; font-weight: 700;
cursor: pointer; cursor: pointer;
transition: transition: background 0.15s;
background 0.15s,
box-shadow 0.15s;
&:hover:not(:disabled) { &:hover:not(:disabled) {
background: var(--sg-primary-strong); background: var(--sg-primary-strong);
} }
&:focus-visible {
outline: none;
box-shadow:
0 0 0 2px var(--sg-background),
0 0 0 4px var(--sg-primary);
}
&:disabled { &:disabled {
opacity: 0.5; opacity: 0.5;
cursor: not-allowed; cursor: not-allowed;
@@ -78,9 +78,8 @@ export class PersonListComponent {
defaultOrderValue = 'desc'; defaultOrderValue = 'desc';
// Selected filter states // Selected filter states
readonly selectedTopics = signal<Set<string>>(new Set<string>()); selectedTopics = new Set<string>();
readonly searchValue = signal<string | null>(null); searchValue = signal<string | null>(null);
readonly topicSearchType = signal<'hybrid' | 'semantic'>('hybrid');
// Applied filter states (reflecting actual URL query params) // Applied filter states (reflecting actual URL query params)
appliedInstitutionName = ''; appliedInstitutionName = '';
@@ -145,14 +144,11 @@ export class PersonListComponent {
const filterYear = params['filterYear'] const filterYear = params['filterYear']
? Number.parseInt(params['filterYear'], 10) ? Number.parseInt(params['filterYear'], 10)
: new Date().getFullYear() - 1; : new Date().getFullYear() - 1;
const topicSearch = params['topicSearch'] || '';
const topicSearchType =
params['topicSearchType'] === 'semantic' ? 'semantic' : 'hybrid';
const topics = this.parseQueryParamArray(params['topic']); const topics = this.parseQueryParamArray(params['topic']);
// restore values from query params // restore values from query params
this.selectedTopics.set(new Set(topics)); this.selectedTopics = new Set(topics);
this.currentPage = page; this.currentPage = page;
this.paginationService.selection = pageSize; this.paginationService.selection = pageSize;
@@ -181,10 +177,6 @@ export class PersonListComponent {
if (this.filterYearControl.value !== filterYear) { if (this.filterYearControl.value !== filterYear) {
this.filterYearControl.setValue(filterYear); this.filterYearControl.setValue(filterYear);
} }
if (this.topicSearchControl.value !== topicSearch) {
this.topicSearchControl.setValue(topicSearch, { emitEvent: false });
}
this.topicSearchType.set(topicSearchType);
// Update applied filter states // Update applied filter states
this.appliedInstitutionName = institutionName; this.appliedInstitutionName = institutionName;
@@ -222,22 +214,6 @@ export class PersonListComponent {
.subscribe(() => { .subscribe(() => {
this.applySidebarFilters(); this.applySidebarFilters();
}); });
this.topicSearchControl.valueChanges
.pipe(
debounceTime(300),
distinctUntilChanged(),
takeUntilDestroyed(this.destroyRef),
)
.subscribe((val) => {
this.router.navigate([], {
queryParams: {
topicSearch: val || null,
},
queryParamsHandling: 'merge',
replaceUrl: true,
});
});
} }
private updateSortOrderState(value: any) { private updateSortOrderState(value: any) {
@@ -261,7 +237,7 @@ export class PersonListComponent {
// Filter selection checks // Filter selection checks
isTopicSelected(topic: string): boolean { isTopicSelected(topic: string): boolean {
return this.selectedTopics().has(topic); return this.selectedTopics.has(topic);
} }
isRelevanceSelected(): boolean { isRelevanceSelected(): boolean {
@@ -269,15 +245,11 @@ export class PersonListComponent {
} }
toggleTopic(topic: string): void { toggleTopic(topic: string): void {
this.selectedTopics.update((set) => { if (this.selectedTopics.has(topic)) {
const next = new Set(set); this.selectedTopics.delete(topic);
if (next.has(topic)) { } else {
next.delete(topic); this.selectedTopics.add(topic);
} else { }
next.add(topic);
}
return next;
});
this.applySidebarFilters(); this.applySidebarFilters();
} }
@@ -288,7 +260,7 @@ export class PersonListComponent {
label: string; label: string;
}> { }> {
const list: Array<{ category: string; value: string; label: string }> = []; const list: Array<{ category: string; value: string; label: string }> = [];
this.selectedTopics().forEach((t) => { this.selectedTopics.forEach((t) => {
list.push({ category: 'topic', value: t, label: `Thema: ${t}` }); list.push({ category: 'topic', value: t, label: `Thema: ${t}` });
}); });
if (this.appliedInstitutionName) { if (this.appliedInstitutionName) {
@@ -308,11 +280,7 @@ export class PersonListComponent {
removeFilter(filter: { category: string; value: string }): void { removeFilter(filter: { category: string; value: string }): void {
if (filter.category === 'topic') { if (filter.category === 'topic') {
this.selectedTopics.update((set) => { this.selectedTopics.delete(filter.value);
const next = new Set(set);
next.delete(filter.value);
return next;
});
} else if (filter.category === 'institutionName') { } else if (filter.category === 'institutionName') {
this.institutionControl.setValue('', { emitEvent: false }); this.institutionControl.setValue('', { emitEvent: false });
this.updateYearFilterState(''); this.updateYearFilterState('');
@@ -325,7 +293,7 @@ export class PersonListComponent {
} }
clearAllFilters(): void { clearAllFilters(): void {
this.selectedTopics.set(new Set<string>()); this.selectedTopics.clear();
this.institutionControl.setValue('', { emitEvent: false }); this.institutionControl.setValue('', { emitEvent: false });
this.updateYearFilterState(''); this.updateYearFilterState('');
this.institutionOptions.set([]); this.institutionOptions.set([]);
@@ -341,12 +309,9 @@ export class PersonListComponent {
} }
this.router.navigate([], { this.router.navigate([], {
queryParams: { queryParams: {
topic: this.selectedTopics().size topic: this.selectedTopics.size
? Array.from(this.selectedTopics()) ? Array.from(this.selectedTopics)
: null, : null,
topicSearch: this.topicSearchControl.value || null,
topicSearchType:
this.topicSearchType() === 'semantic' ? 'semantic' : null,
institutionName: this.institutionControl.value || null, institutionName: this.institutionControl.value || null,
sortBy: this.sortValueControl.value || null, sortBy: this.sortValueControl.value || null,
sortOrder: this.sortOrderControl.value || null, sortOrder: this.sortOrderControl.value || null,
@@ -398,17 +363,12 @@ export class PersonListComponent {
} }
onTopicSelectionChange(newSelection: Set<string>): void { onTopicSelectionChange(newSelection: Set<string>): void {
this.selectedTopics.set(newSelection); this.selectedTopics = newSelection;
this.applySidebarFilters();
}
onTopicSearchTypeChange(type: 'hybrid' | 'semantic'): void {
this.topicSearchType.set(type);
this.applySidebarFilters(); this.applySidebarFilters();
} }
onCardTopicClick(topic: string): void { onCardTopicClick(topic: string): void {
this.toggleTopic(topic); this.topicSearchControl.setValue(topic);
} }
onCardInstitutionClick(institutionName: string): void { onCardInstitutionClick(institutionName: string): void {
@@ -5,27 +5,40 @@
</div> </div>
<mat-card appearance="outlined"> <mat-card appearance="outlined">
<mat-card-content> <mat-card-content>
<app-query-param-input label="Suche nach Titel" queryParamKey="search" /> <mat-form-field style="width: 100%">
<mat-label>Suche nach Titel</mat-label>
<input
matInput
type="search"
[debounceTime]="300"
[(debouncedValue)]="urlSearchTerm"
(debouncedValueChange)="handleSearchTermChange($event)" />
<mat-icon matPrefix>search</mat-icon>
<button matIconButton matSuffix (click)="clearSearchTerm()">
<mat-icon>clear</mat-icon>
</button>
</mat-form-field>
<mat-tab-group> <mat-tab-group>
<mat-tab label="DFG"> <mat-tab label="DFG">
<app-data-table <app-data-table
[columns]="dfgProjectColumns" [columns]="dfgProjectColumns"
[data]="dfgProjectData" [data]="dfgProjectData"
[detailTemplate]="dfgProjectDetailRowTmp" [detailTemplate]="dfgProjectDetailRowTmp"
queryParamSortKey="sort_by" [activeSortKey]="urlSortKey()"
queryParamSortDirectionKey="sort_direction" /> [sortDirection]="urlSortDirection()"
(sortChange)="handleSortChange($event)" />
</mat-tab> </mat-tab>
<mat-tab label="EU"> <mat-tab label="EU">
<app-data-table <app-data-table
[columns]="personCordisEuProjectColumns" [columns]="personCordisEuProjectColumns"
[data]="personCordisEuProjectData" [data]="personCordisEuProjectData" />
queryParamSortKey="sort_by"
queryParamSortDirectionKey="sort_direction" />
</mat-tab> </mat-tab>
</mat-tab-group> </mat-tab-group>
<app-query-param-paginator <mat-paginator
[total]="this.pageTotal()" [length]="this.pageTotal()"
[pageSizeOptions]="[10]" /> [pageSize]="this.pageSize()"
[pageIndex]="this.pageIndex()"
(page)="handlePageChange($event)" />
</mat-card-content> </mat-card-content>
</mat-card> </mat-card>
</div> </div>
@@ -4,6 +4,7 @@ import {
effect, effect,
input, input,
OnInit, OnInit,
signal,
TemplateRef, TemplateRef,
viewChild, viewChild,
} from '@angular/core'; } from '@angular/core';
@@ -23,10 +24,12 @@ import { MatCardModule } from '@angular/material/card';
import { MatTabsModule } from '@angular/material/tabs'; import { MatTabsModule } from '@angular/material/tabs';
import { MatFormFieldModule } from '@angular/material/form-field'; import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input'; import { MatInputModule } from '@angular/material/input';
import { Router, RouterModule } from '@angular/router'; import { DebounceDirective } from '../../directives/debounce.directive';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
import { Sort, SortDirection } from '@angular/material/sort';
import { CurrencyPipe, DatePipe } from '@angular/common'; import { CurrencyPipe, DatePipe } from '@angular/common';
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component';
@Component({ @Component({
selector: 'app-person-projects', selector: 'app-person-projects',
@@ -38,11 +41,11 @@ import { QueryParamInputComponent } from '../../shared/ui/query-param-input/quer
MatTabsModule, MatTabsModule,
MatFormFieldModule, MatFormFieldModule,
MatInputModule, MatInputModule,
DebounceDirective,
MatPaginatorModule,
RouterModule, RouterModule,
DatePipe, DatePipe,
CurrencyPipe, CurrencyPipe,
QueryParamPaginatorComponent,
QueryParamInputComponent,
], ],
templateUrl: './person-projects.component.html', templateUrl: './person-projects.component.html',
styleUrl: './person-projects.component.scss', styleUrl: './person-projects.component.scss',
@@ -79,19 +82,55 @@ export class PersonProjectsComponent implements OnInit {
'euProjectsActionsTmp', 'euProjectsActionsTmp',
); );
urlSearchTerm = signal<string>('');
urlSortKey = signal<string>('');
urlSortDirection = signal<SortDirection>('');
readonly pageTotal = computed(() => { readonly pageTotal = computed(() => {
return this.dfgProjectPage()?.total ?? 0; return this.dfgProjectPage()?.total ?? 0;
}); });
constructor(private readonly router: Router) { readonly pageSize = computed(() => {
return this.dfgProjectPage()?.size ?? 10;
});
readonly pageIndex = computed(() => {
return this.dfgProjectPage()?.page ?? 0;
});
constructor(
private readonly router: Router,
private readonly activatedRoute: ActivatedRoute,
) {
this.activatedRoute.queryParamMap
.pipe(takeUntilDestroyed())
.subscribe((params) => {
this.urlSearchTerm.set(params.get('search') || '');
});
effect(() => { effect(() => {
this.dfgProjectData = this.dfgProjectPage().elements || []; this.dfgProjectData = this.dfgProjectPage().elements || [];
}); });
effect(() => { effect(() => {
console.log(
'Updating personCordisEuProjectData with',
this.personCordisEuProjectPage(),
);
this.personCordisEuProjectData = this.personCordisEuProjectData =
this.personCordisEuProjectPage().elements || []; this.personCordisEuProjectPage().elements || [];
}); });
effect(() => {
const searchTerm = this.urlSearchTerm();
if (searchTerm) {
this.router.navigate([], {
queryParams: { search: searchTerm, page: 0, size: this.pageSize() },
queryParamsHandling: 'merge',
});
}
});
} }
ngOnInit(): void { ngOnInit(): void {
@@ -157,4 +196,32 @@ export class PersonProjectsComponent implements OnInit {
}, },
]; ];
} }
handleSearchTermChange(newTerm: string): void {
this.router.navigate([], {
queryParams: { search: newTerm },
queryParamsHandling: 'merge',
});
}
clearSearchTerm(): void {
this.router.navigate([], {
queryParams: { search: null },
queryParamsHandling: 'merge',
});
}
handlePageChange(event: PageEvent): void {
this.router.navigate([], {
queryParams: { page: event.pageIndex, size: event.pageSize },
queryParamsHandling: 'merge',
});
}
handleSortChange(event: Sort): void {
this.router.navigate([], {
queryParams: { sort_by: event.active, sort_direction: event.direction },
queryParamsHandling: 'merge',
});
}
} }
@@ -4,11 +4,19 @@
<mat-divider /> <mat-divider />
<div style="padding: 0 1rem"> <div style="padding: 0 1rem">
<app-query-param-input <mat-form-field style="width: 100%">
label="Suche nach Namen" <mat-label>Suche nach Namen</mat-label>
[debounceTime]="400" <input
queryParamKey="search"> matInput
</app-query-param-input> type="search"
[debounceTime]="300"
[(debouncedValue)]="urlSearchTerm"
(debouncedValueChange)="handleSearchTermChange($event)" />
<mat-icon matPrefix>search</mat-icon>
<button matIconButton matSuffix (click)="clearSearchTerm()">
<mat-icon>clear</mat-icon>
</button>
</mat-form-field>
<div <div
style=" style="
@@ -26,13 +34,16 @@
</mat-chip-listbox> </mat-chip-listbox>
<div class="sorting"> <div class="sorting">
<app-query-param-selector <select (change)="handleSortFieldChange($event)" [value]="urlSortBy()">
[options]="sortingOptions" <option value="title">Name</option>
queryParamKey="sort_by" /> </select>
<app-query-param-selector <select
[options]="sortingDirectionOptions" (change)="handleSortOrderChange($event)"
queryParamKey="sorting_order" /> [value]="urlSortingOrder()">
<option value="desc">Absteigend</option>
<option value="asc">Aufsteigend</option>
</select>
</div> </div>
</div> </div>
</div> </div>
@@ -91,7 +102,11 @@
<mat-divider /> <mat-divider />
<app-query-param-paginator <mat-paginator
[total]="fundingProjectPageValue.total || 0" [length]="fundingProjectPageValue.total"
[pageSizeOptions]="[10, 25, 50]" /> [pageSize]="fundingProjectPageValue.size"
[pageSizeOptions]="[10, 20, 50]"
[pageIndex]="fundingProjectPageValue.page"
(page)="handlePageChange($event)">
</mat-paginator>
</div> </div>
@@ -25,10 +25,22 @@
.cards { .cards {
display: grid; display: grid;
gap: 1.5rem; gap: 1.5rem;
grid-template-columns: repeat(auto-fit, minmax(380px, 1fr)); grid-template-columns: repeat(4, 1fr);
padding: 0 1rem; padding: 0 1rem;
} }
@media (max-width: 900px) {
.cards {
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 600px) {
.cards {
grid-template-columns: 1fr;
}
}
mat-paginator { mat-paginator {
background-color: var(--sg-background); background-color: var(--sg-background);
} }
@@ -1,34 +1,33 @@
import { Component, input, signal } from '@angular/core'; import { Component, effect, input, signal } from '@angular/core';
import { FundingProject, FundingProjectPage, ProjectType } from '../../api'; import { FundingProject, FundingProjectPage, ProjectType } from '../../api';
import { MatDividerModule } from '@angular/material/divider'; import { MatDividerModule } from '@angular/material/divider';
import { MatFormFieldModule } from '@angular/material/form-field';
import { DebounceDirective } from '../../directives/debounce.directive';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatCardModule } from '@angular/material/card'; import { MatCardModule } from '@angular/material/card';
import { ActivatedRoute, Router, RouterModule } from '@angular/router'; import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { MatPaginator, PageEvent } from '@angular/material/paginator';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button'; import { MatButtonModule } from '@angular/material/button';
import { DatePipe, UpperCasePipe } from '@angular/common'; import { DatePipe, UpperCasePipe } from '@angular/common';
import { MatChipListboxChange, MatChipsModule } from '@angular/material/chips'; import { MatChipListboxChange, MatChipsModule } from '@angular/material/chips';
import { QueryParamInputComponent } from '../../shared/ui/query-param-input/query-param-input.component';
import { QueryParamPaginatorComponent } from '../../shared/ui/query-param-paginator/query-param-paginator.component';
import {
QueryParamSelectorComponent,
SelectorOption,
} from '../../shared/ui/query-param-selector/query-param-selector.component';
@Component({ @Component({
selector: 'app-projects', selector: 'app-projects',
imports: [ imports: [
MatDividerModule, MatDividerModule,
MatFormFieldModule,
DebounceDirective,
MatIconModule, MatIconModule,
MatCardModule, MatCardModule,
RouterModule, RouterModule,
MatPaginator,
MatInputModule,
MatButtonModule, MatButtonModule,
UpperCasePipe, UpperCasePipe,
DatePipe, DatePipe,
MatChipsModule, MatChipsModule,
QueryParamInputComponent,
QueryParamPaginatorComponent,
QueryParamSelectorComponent,
], ],
templateUrl: './projects.component.html', templateUrl: './projects.component.html',
styleUrl: './projects.component.scss', styleUrl: './projects.component.scss',
@@ -36,14 +35,11 @@ import {
export class ProjectsComponent { export class ProjectsComponent {
fundingProjectPage = input.required<FundingProjectPage>(); fundingProjectPage = input.required<FundingProjectPage>();
urlSearchTerm = signal<string>('');
urlSortBy = signal<string>('relevance');
urlSortingOrder = signal<string>('desc');
urlChips = signal<ProjectType[]>(['eu', 'bund', 'dfg']); urlChips = signal<ProjectType[]>(['eu', 'bund', 'dfg']);
sortingOptions: SelectorOption[] = [{ value: 'title', display_name: 'Name' }];
sortingDirectionOptions: SelectorOption[] = [
{ value: 'asc', display_name: 'Aufsteigend' },
{ value: 'desc', display_name: 'Absteigend' },
];
constructor( constructor(
private readonly activatedRoute: ActivatedRoute, private readonly activatedRoute: ActivatedRoute,
private readonly router: Router, private readonly router: Router,
@@ -51,10 +47,60 @@ export class ProjectsComponent {
this.activatedRoute.queryParams this.activatedRoute.queryParams
.pipe(takeUntilDestroyed()) .pipe(takeUntilDestroyed())
.subscribe((params) => { .subscribe((params) => {
this.urlSearchTerm.set(params['search'] || '');
this.urlSortBy.set(params['sort_by'] || 'relevance');
this.urlSortingOrder.set(params['sorting_order'] || 'desc');
this.urlChips.set( this.urlChips.set(
(params['selected_project_types'] || 'eu,bund,dfg').split(','), (params['selected_project_types'] || 'eu,bund,dfg').split(','),
); );
}); });
effect(() => {
const searchTerm = this.urlSearchTerm();
this.router.navigate([], {
queryParams: { search: searchTerm },
queryParamsHandling: 'merge',
});
});
}
handleSearchTermChange(newTerm: string): void {
this.router.navigate([], {
queryParams: { search: newTerm, page: 0, size: 10 },
queryParamsHandling: 'merge',
});
}
clearSearchTerm(): void {
this.router.navigate([], {
queryParams: { search: null },
queryParamsHandling: 'merge',
});
}
handlePageChange(event: PageEvent): void {
this.router.navigate([], {
queryParams: { page: event.pageIndex, size: event.pageSize },
queryParamsHandling: 'merge',
});
}
handleSortFieldChange(event: Event): void {
const selectElement = event.target as HTMLSelectElement;
const sortField = selectElement.value;
this.router.navigate([], {
queryParams: { sort_by: sortField },
queryParamsHandling: 'merge',
});
}
handleSortOrderChange(event: Event): void {
const selectElement = event.target as HTMLSelectElement;
const sortOrder = selectElement.value;
this.router.navigate([], {
queryParams: { sorting_order: sortOrder },
queryParamsHandling: 'merge',
});
} }
handleChipBoxChange(change: MatChipListboxChange): void { handleChipBoxChange(change: MatChipListboxChange): void {
@@ -1,44 +1,11 @@
<div class="hierarchy-container"> <div class="hierarchy-container">
@if (searchQuery()) {
<div
class="search-mode-selector"
style="
margin-bottom: 12px;
display: flex;
align-items: center;
gap: 12px;
border-bottom: 1px solid rgba(0, 0, 0, 0.08);
padding-bottom: 8px;
">
<span
style="
font-size: 12px;
font-weight: 500;
color: var(--sg-text);
opacity: 0.8;
"
>Modus:</span
>
<mat-radio-group
[value]="searchType()"
(change)="onSearchTypeChange($event.value)"
style="display: flex; gap: 16px">
<mat-radio-button value="hybrid">
<span style="font-size: 12px; color: var(--sg-text)">Hybrid</span>
</mat-radio-button>
<mat-radio-button value="semantic">
<span style="font-size: 12px; color: var(--sg-text)">Semantisch</span>
</mat-radio-button>
</mat-radio-group>
</div>
}
@if (loading()) { @if (loading()) {
<div class="loading-state"> <div class="loading-state">
<mat-spinner diameter="24"></mat-spinner> <mat-spinner diameter="24"></mat-spinner>
<span>Lade Themen...</span> <span>Lade Themen...</span>
</div> </div>
} @else { } @else {
@if (searchQuery()) { @if (searchQuery) {
<!-- Flat Search Results Mode --> <!-- Flat Search Results Mode -->
<div class="search-results"> <div class="search-results">
<span class="results-meta" <span class="results-meta"
@@ -48,13 +15,8 @@
@for (topic of filteredFlatTopics; track topic.id) { @for (topic of filteredFlatTopics; track topic.id) {
<div class="flat-row"> <div class="flat-row">
<mat-checkbox <mat-checkbox
#tooltip="matTooltip" [checked]="selectedTopics.has(topic.name)"
[checked]="selectedTopics().has(topic.name)" (change)="toggleTopic(topic.name)">
(change)="toggleTopic(topic.name)"
[matTooltip]="topic.name"
matTooltipPosition="above"
(focusin)="tooltip.show()"
(focusout)="tooltip.hide()">
<span class="topic-name">{{ topic.name }}</span> <span class="topic-name">{{ topic.name }}</span>
</mat-checkbox> </mat-checkbox>
<span class="topic-path" [title]="topic.path">{{ <span class="topic-path" [title]="topic.path">{{
@@ -141,18 +103,13 @@
<!-- LEVEL 4: Topic Checkbox --> <!-- LEVEL 4: Topic Checkbox -->
<div class="tree-leaf topic-node"> <div class="tree-leaf topic-node">
<mat-checkbox <mat-checkbox
#tooltip="matTooltip" [checked]="selectedTopics.has(topic.name)"
[checked]=" (change)="toggleTopic(topic.name)">
selectedTopics().has(topic.name) <span
" class="topic-label"
(change)="toggleTopic(topic.name)" [title]="topic.name"
[matTooltip]="topic.name" >{{ topic.name }}</span
matTooltipPosition="above" >
(focusin)="tooltip.show()"
(focusout)="tooltip.hide()">
<span class="topic-label">{{
topic.name
}}</span>
</mat-checkbox> </mat-checkbox>
</div> </div>
} }
@@ -2,13 +2,11 @@
width: 100%; width: 100%;
max-height: 400px; max-height: 400px;
overflow-y: auto; overflow-y: auto;
overflow-x: hidden;
border: 1px solid var(--sg-border); border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm); border-radius: var(--sg-radius-sm);
background: var(--sg-background); background: var(--sg-background);
padding: 4px 8px 4px 4px; padding: 4px;
margin-top: 4px; margin-top: 4px;
box-sizing: border-box;
} }
.loading-state { .loading-state {
@@ -57,11 +55,6 @@
font-size: 12px; font-size: 12px;
color: var(--sg-text); color: var(--sg-text);
font-weight: 500; font-weight: 500;
display: block;
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
} }
.topic-path { .topic-path {
@@ -99,7 +92,7 @@
width: 100%; width: 100%;
background: transparent; background: transparent;
border: none; border: none;
padding: 4px; padding: 4px 6px;
text-align: left; text-align: left;
cursor: pointer; cursor: pointer;
border-radius: 4px; border-radius: 4px;
@@ -129,7 +122,6 @@
white-space: nowrap; white-space: nowrap;
text-overflow: ellipsis; text-overflow: ellipsis;
overflow: hidden; overflow: hidden;
min-width: 0;
} }
} }
@@ -166,62 +158,37 @@
} }
.domain-children { .domain-children {
padding-left: 10px; padding-left: 12px;
border-left: 1px solid var(--sg-border-soft); border-left: 1px solid var(--sg-border-soft);
margin-left: 12px; margin-left: 12px;
margin-bottom: 4px; margin-bottom: 4px;
} }
.field-children { .field-children {
padding-left: 10px; padding-left: 14px;
border-left: 1px solid var(--sg-border-soft); border-left: 1px solid var(--sg-border-soft);
margin-left: 12px; margin-left: 14px;
} }
.subfield-children { .subfield-children {
padding-left: 10px; padding-left: 14px;
border-left: 1px dashed var(--sg-border-soft); border-left: 1px dashed var(--sg-border-soft);
margin-left: 12px; margin-left: 14px;
margin-bottom: 2px; margin-bottom: 2px;
} }
.tree-leaf { .tree-leaf {
padding: 2px 4px; padding: 2px 4px;
width: 100%;
box-sizing: border-box;
} }
.topic-node { .topic-node {
width: 100%;
box-sizing: border-box;
.topic-label { .topic-label {
font-size: 11px; font-size: 11px;
color: var(--sg-text); color: var(--sg-text);
display: block;
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
} text-overflow: ellipsis;
} overflow: hidden;
display: block;
mat-checkbox { max-width: 190px;
display: block !important;
width: 100% !important;
::ng-deep {
.mdc-form-field {
width: 100% !important;
display: flex !important;
align-items: center;
}
.mdc-label {
flex: 1 !important;
min-width: 0 !important;
overflow: hidden;
padding-left: 8px !important;
}
} }
} }
@@ -1,13 +1,17 @@
import { Component, input, model, output, OnInit, signal } from '@angular/core'; import {
Component,
Input,
Output,
EventEmitter,
OnInit,
signal,
} from '@angular/core';
import { CommonModule } from '@angular/common'; import { CommonModule } from '@angular/common';
import { MatCheckboxModule } from '@angular/material/checkbox'; import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatIconModule } from '@angular/material/icon'; import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'; import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatRadioModule } from '@angular/material/radio';
import { MatTooltipModule } from '@angular/material/tooltip';
import { TopicsService } from '../../api/api/topics.service'; import { TopicsService } from '../../api/api/topics.service';
import { combineLatest, of } from 'rxjs'; import { Subject, of } from 'rxjs';
import { toObservable } from '@angular/core/rxjs-interop';
import { import {
debounceTime, debounceTime,
distinctUntilChanged, distinctUntilChanged,
@@ -49,18 +53,28 @@ interface FlatTopic {
MatCheckboxModule, MatCheckboxModule,
MatIconModule, MatIconModule,
MatProgressSpinnerModule, MatProgressSpinnerModule,
MatRadioModule,
MatTooltipModule,
], ],
templateUrl: './topic-hierarchy.component.html', templateUrl: './topic-hierarchy.component.html',
styleUrl: './topic-hierarchy.component.scss', styleUrl: './topic-hierarchy.component.scss',
}) })
export class TopicHierarchyComponent implements OnInit { export class TopicHierarchyComponent implements OnInit {
selectedTopics = input<Set<string>>(new Set<string>()); @Input() selectedTopics: Set<string> = new Set<string>();
searchQuery = input<string>('');
searchType = model<'hybrid' | 'semantic'>('hybrid');
selectionChange = output<Set<string>>(); private _searchQuery = '';
@Input()
set searchQuery(value: string) {
if (value.length < 2) {
this._searchQuery = '';
} else {
this._searchQuery = value;
}
this.filterFlatTopics();
}
get searchQuery(): string {
return this._searchQuery;
}
@Output() selectionChange = new EventEmitter<Set<string>>();
domains: DomainNode[] = []; domains: DomainNode[] = [];
flatTopics: FlatTopic[] = []; flatTopics: FlatTopic[] = [];
@@ -72,37 +86,32 @@ export class TopicHierarchyComponent implements OnInit {
expandedFields = new Set<string>(); expandedFields = new Set<string>();
expandedSubfields = new Set<string>(); expandedSubfields = new Set<string>();
private readonly searchSubject = new Subject<string>();
constructor(private topicsService: TopicsService) { constructor(private topicsService: TopicsService) {
combineLatest([ this.searchSubject
toObservable(this.searchQuery),
toObservable(this.searchType),
])
.pipe( .pipe(
debounceTime(300), debounceTime(300),
distinctUntilChanged( distinctUntilChanged(),
(prev, curr) => prev[0] === curr[0] && prev[1] === curr[1], switchMap((query) => {
), if (!query) {
switchMap(([query, searchType]) => {
if (!query || query.length < 2) {
this.filteredFlatTopics = []; this.filteredFlatTopics = [];
return of({ results: [] }); return of({ results: [] });
} }
this.loading.set(true); this.loading.set(true);
return this.topicsService return this.topicsService.vectorSearchTopics(query, 50).pipe(
.vectorSearchTopics(query, 50, searchType) catchError((err) => {
.pipe( console.error('Error in semantic topic search:', err);
catchError((err) => { // Fallback to local filtering
console.error('Error in semantic topic search:', err); const q = query.toLowerCase();
// Fallback to local filtering this.filteredFlatTopics = this.flatTopics.filter(
const q = query.toLowerCase(); (t) =>
this.filteredFlatTopics = this.flatTopics.filter( t.name.toLowerCase().includes(q) ||
(t) => t.path.toLowerCase().includes(q),
t.name.toLowerCase().includes(q) || );
t.path.toLowerCase().includes(q), return of({ results: [] });
); }),
return of({ results: [] }); );
}),
);
}), }),
) )
.subscribe((response) => { .subscribe((response) => {
@@ -158,14 +167,19 @@ export class TopicHierarchyComponent implements OnInit {
}); });
}); });
this.flatTopics = flat; this.flatTopics = flat;
this.filterFlatTopics();
} }
onSearchTypeChange(type: 'hybrid' | 'semantic'): void { filterFlatTopics(): void {
this.searchType.set(type); if (!this.searchQuery) {
this.filteredFlatTopics = [];
return;
}
this.searchSubject.next(this.searchQuery);
} }
toggleTopic(name: string): void { toggleTopic(name: string): void {
const nextSelection = new Set(this.selectedTopics()); const nextSelection = new Set(this.selectedTopics);
if (nextSelection.has(name)) { if (nextSelection.has(name)) {
nextSelection.delete(name); nextSelection.delete(name);
} else { } else {
@@ -7,9 +7,10 @@ import {
} from '../api'; } from '../api';
import { inject } from '@angular/core'; import { inject } from '@angular/core';
export const cordisEuProjectPageResolver: ResolveFn< export const cordisEuProjectPageResolver: ResolveFn<EuOrganizationProjectSummaryPage> = (
EuOrganizationProjectSummaryPage route,
> = (route, state) => { state,
) => {
const page = route.queryParamMap.get('page') ?? '1'; const page = route.queryParamMap.get('page') ?? '1';
const size = route.queryParamMap.get('size') ?? '10'; const size = route.queryParamMap.get('size') ?? '10';
let institutionId = route.paramMap.get('institutionId'); let institutionId = route.paramMap.get('institutionId');
@@ -3,7 +3,7 @@
mat-table mat-table
[dataSource]="dataSource" [dataSource]="dataSource"
matSort matSort
(matSortChange)="_handleSortChange($event)" (matSortChange)="onSortChange($event)"
multiTemplateDataRows> multiTemplateDataRows>
@for (col of columns(); track col.id) { @for (col of columns(); track col.id) {
<ng-container [matColumnDef]="col.id"> <ng-container [matColumnDef]="col.id">
@@ -4,14 +4,12 @@ import {
Component, Component,
computed, computed,
effect, effect,
inject,
input, input,
output, output,
signal, signal,
TemplateRef, TemplateRef,
viewChild, viewChild,
} from '@angular/core'; } from '@angular/core';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { import {
MatSort, MatSort,
MatSortModule, MatSortModule,
@@ -19,7 +17,6 @@ import {
SortDirection, SortDirection,
} from '@angular/material/sort'; } from '@angular/material/sort';
import { MatTableDataSource, MatTableModule } from '@angular/material/table'; import { MatTableDataSource, MatTableModule } from '@angular/material/table';
import { ActivatedRoute, Router } from '@angular/router';
export interface BaseColumn<T> { export interface BaseColumn<T> {
id: string; id: string;
@@ -58,37 +55,15 @@ export class DataTableComponent<T> implements AfterViewInit {
containerOverflow = computed(() => (this.maxHeight() ? 'auto' : 'visible')); containerOverflow = computed(() => (this.maxHeight() ? 'auto' : 'visible'));
stickyHeader = input<boolean>(true); stickyHeader = input<boolean>(true);
queryParamSortKey = input<string | null>(null); activeSortKey = input<string>('');
queryParamSortDirectionKey = input<string | null>(null); sortDirection = input<SortDirection>('');
sortChange = output<Sort>();
_urlSortValue = computed<string | null>(() => {
const params = this.queryParams();
const key = this.queryParamSortKey();
return params && key ? params[key] || null : null;
});
_urlSortDirectionValue = computed<string | null>(() => {
const params = this.queryParams();
const key = this.queryParamSortDirectionKey();
return params && key ? params[key] || null : null;
});
handleSortChange = output<Sort>();
displayedColumns = computed(() => this.columns().map((col) => col.id)); displayedColumns = computed(() => this.columns().map((col) => col.id));
dataSource = new MatTableDataSource<T>([]); dataSource = new MatTableDataSource<T>([]);
sort = viewChild.required(MatSort); sort = viewChild.required(MatSort);
private readonly activatedRouter = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly queryParams = toSignal(
this.activatedRouter.queryParams.pipe(takeUntilDestroyed()),
);
constructor() { constructor() {
effect(() => { effect(() => {
const currentData = this.data(); const currentData = this.data();
@@ -111,23 +86,15 @@ export class DataTableComponent<T> implements AfterViewInit {
effect(() => { effect(() => {
const matSortInstance = this.sort(); const matSortInstance = this.sort();
const activeKey = this._urlSortValue(); const activeKey = this.activeSortKey();
const direction = this._urlSortDirectionValue(); const direction = this.sortDirection();
if ( if (
matSortInstance.active !== activeKey || matSortInstance.active !== activeKey ||
matSortInstance.direction !== direction matSortInstance.direction !== direction
) { ) {
if (activeKey == null) { matSortInstance.active = activeKey;
matSortInstance.active = ''; matSortInstance.direction = direction;
} else {
matSortInstance.active = activeKey;
}
if (direction == null) {
matSortInstance.direction = '';
} else {
matSortInstance.direction = direction as SortDirection;
}
this.dataSource.sort = matSortInstance; this.dataSource.sort = matSortInstance;
} }
@@ -138,25 +105,8 @@ export class DataTableComponent<T> implements AfterViewInit {
this.dataSource.sort = this.sort(); this.dataSource.sort = this.sort();
} }
_handleSortChange(sort: Sort): void { onSortChange(sort: Sort) {
this.handleSortChange.emit(sort); this.sortChange.emit(sort);
const sortKey = this.queryParamSortKey();
const sortDirectionKey = this.queryParamSortDirectionKey();
if (sortKey != null) {
const queryParams: any = {
[sortKey]: sort.active || null,
};
if (sortDirectionKey != null) {
queryParams[sortDirectionKey] = sort.direction || null;
}
this.router.navigate([], {
queryParams,
queryParamsHandling: 'merge',
});
}
} }
toggleRow(row: T): void { toggleRow(row: T): void {
@@ -1,13 +0,0 @@
<mat-form-field style="width: 100%">
<mat-label>{{ this.label() }}</mat-label>
<input
matInput
type="search"
[debounceTime]="this.debounceTime()"
(debouncedValueChange)="this._handleValueChange($event)"
[ngModel]="this._urlValue()" />
<mat-icon matPrefix>search</mat-icon>
<button matIconButton matSuffix type="button" (click)="clearInput()">
<mat-icon>clear</mat-icon>
</button>
</mat-form-field>
@@ -1,63 +0,0 @@
import { Component, computed, inject, input, output } from '@angular/core';
import { MatFormFieldModule } from '@angular/material/form-field';
import { DebounceDirective } from '../../../directives/debounce.directive';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { ActivatedRoute, Router } from '@angular/router';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-query-param-input',
imports: [
FormsModule,
MatInputModule,
MatButtonModule,
MatIconModule,
MatFormFieldModule,
DebounceDirective,
],
templateUrl: './query-param-input.component.html',
styleUrl: './query-param-input.component.scss',
})
export class QueryParamInputComponent {
queryParamKey = input.required<string>();
queryParamPageKey = input<string>('page');
label = input<string>('Suchen');
debounceTime = input<number>(300);
handleValueChange = output<string>();
private readonly activatedRoute = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly queryParams = toSignal(
this.activatedRoute.queryParams.pipe(takeUntilDestroyed()),
);
_urlValue = computed<string>(() => {
const params = this.queryParams();
const key = this.queryParamKey();
return params && key ? params[key] || '' : '';
});
clearInput(): void {
this.router.navigate([], {
queryParams: { [this.queryParamKey()]: null },
queryParamsHandling: 'merge',
});
}
_handleValueChange(newValue: string): void {
this.handleValueChange?.emit(newValue);
this.router.navigate([], {
queryParams: {
[this.queryParamKey()]: newValue || null,
[this.queryParamPageKey()]: 0,
},
queryParamsHandling: 'merge',
});
}
}
@@ -1,6 +0,0 @@
<mat-paginator
[length]="total()"
[pageSize]="_urlSize()"
[pageIndex]="_urlPage()"
[pageSizeOptions]="pageSizeOptions()"
(page)="_handlePageChange($event)" />
@@ -1,3 +0,0 @@
mat-paginator {
background-color: var(--sg-background);
}
@@ -1,52 +0,0 @@
import { Component, computed, inject, input, output } from '@angular/core';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { MatPaginatorModule, PageEvent } from '@angular/material/paginator';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'app-query-param-paginator',
imports: [MatPaginatorModule],
templateUrl: './query-param-paginator.component.html',
styleUrl: './query-param-paginator.component.scss',
})
export class QueryParamPaginatorComponent {
queryParamPageKey = input<string>('page');
queryParamSizeKey = input<string>('size');
pageSizeOptions = input<number[]>([10, 25, 50]);
total = input.required<number>();
handlePageChange = output<PageEvent>();
private readonly activatedRoute = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly queryParams = toSignal(
this.activatedRoute.queryParams.pipe(takeUntilDestroyed()),
);
_urlPage = computed<number>(() => {
const params = this.queryParams();
const key = this.queryParamPageKey();
return params && key ? +params[key] || 0 : 0;
});
_urlSize = computed<number>(() => {
const params = this.queryParams();
const key = this.queryParamSizeKey();
return params && key ? +params[key] || 10 : 10;
});
_handlePageChange(event: PageEvent): void {
this.handlePageChange?.emit(event);
this.router.navigate([], {
queryParams: {
[this.queryParamPageKey()]: event.pageIndex || 0,
[this.queryParamSizeKey()]: event.pageSize || 10,
},
queryParamsHandling: 'merge',
});
}
}
@@ -1,5 +0,0 @@
<select (change)="_handleSelectionChange($event)" [ngModel]="_urlValue()">
@for (option of options(); track $index) {
<option [value]="option.value">{{ option.display_name }}</option>
}
</select>
@@ -1,10 +0,0 @@
select {
padding: 0.75rem;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
font-size: 1rem;
}
select:hover {
cursor: pointer;
}
@@ -1,46 +0,0 @@
import { Component, computed, inject, input, output } from '@angular/core';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
export type SelectorOption = {
value: string;
display_name: string;
};
@Component({
selector: 'app-query-param-selector',
imports: [FormsModule],
templateUrl: './query-param-selector.component.html',
styleUrl: './query-param-selector.component.scss',
})
export class QueryParamSelectorComponent {
options = input.required<SelectorOption[]>();
queryParamKey = input.required<string>();
handleSelectionChange = output<Event>();
private readonly activatedRoute = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly queryParams = toSignal(
this.activatedRoute.queryParams.pipe(takeUntilDestroyed()),
);
_urlValue = computed<string>(() => {
const params = this.queryParams();
const key = this.queryParamKey();
return params && key ? params[key] || '' : '';
});
_handleSelectionChange(event: Event): void {
const newValue = (event.target as HTMLSelectElement).value;
this.router.navigate([], {
queryParams: { [this.queryParamKey()]: newValue },
queryParamsHandling: 'merge',
});
this.handleSelectionChange.emit(event);
}
}