feature/news-in-keywords #268

Merged
kallweit merged 6 commits from feature/news-in-keywords into dev 2026-08-10 16:44:07 +02:00
35 changed files with 2713 additions and 969 deletions
+207 -39
View File
@@ -27,7 +27,6 @@ TOPIC_NUM_CANDIDATES = 100
TOPIC_SIMILARITY = 0.5
TOPICS_INDEX = "aktuell_openalex_topics"
TOPICS_INDEX_MAX_PAIRS = 100
_SESSION_TOPIC_CACHE: dict[str, list] = {}
@@ -48,6 +47,11 @@ RELATED_BLOCK_SIZE = 5
RELATED_TOPIC_K = 1
EXACT_ID_CAP = 1000
KEYWORD_SEARCH_FIELDS = ["maintitle^3", "intro_content^2", "tags^2", "full_content"]
KEYWORD_SEARCH_SCAN_CAP = 50000
KEYWORD_SEARCH_ID_CAP = 2000
TOPIC_DOCS_PER_ARTICLE = 25
async def get_news_page(
page: int,
@@ -127,6 +131,206 @@ async def search_news(
return news_page
async def search_news_by_keywords(
keywords: list | None = None,
topic_ids: list | None = None,
filter_topic_ids: list | None = None,
fuzzy: bool = False,
page: int = 1,
page_size: int = 10,
year_from: int | None = None,
year_to: int | None = None,
relevance_values: list | None = None,
sort_order: str | None = None,
) -> NewsPage:
"""Searches the news for the keywords of a keywords-search run.
`fuzzy` resolves the keywords to OpenAlex topics (via the aktuell_openalex_topics index),
otherwise the raw keywords are matched as phrases against the article
text. The individual keywords are OR-ed rather than AND-ed.
An article carries at most KEYWORD_LIMIT keywords, so requiring all of them
would leave every multi-keyword search empty.
Articles matching more of them simply rank higher.
A fuzzy search without any resolved topic ids falls back to the raw
keywords. Once there are topic ids the fallback is off: a topic search that matches no article
stays empty instead of silently returning keyword hits.
By default results stay ranked by match strength (Elasticsearch's
`_score`). Passing `sort_order` ('asc'/'desc') overrides that with a
plain date sort, same as the plain news list.
"""
wanted_topic_ids: set = set()
if fuzzy:
wanted_topic_ids = {
topic_id
for topic_id in (topic_ids or []) + (filter_topic_ids or [])
if topic_id
}
if wanted_topic_ids:
should = await _topic_id_should_clauses(wanted_topic_ids)
else:
should = _keyword_should_clauses(keywords)
if not should:
return _empty_page(page, page_size)
clauses = await _filter_clauses(year_from, year_to, relevance_values)
query = {
"bool": {
"should": should,
"minimum_should_match": 1,
"filter": clauses,
}
}
highlight = {
"fields": {"full_content": {"fragment_size": 200, "number_of_fragments": 1}},
"pre_tags": ["<em>"],
"post_tags": ["</em>"],
"encoder": "html",
}
sort = [{"date_full": sort_order}] if sort_order in ("asc", "desc") else None
response = await _run_search(
query=query,
source=["date", "maintitle", "author", "url", "intro_content", "full_content"],
size=page_size,
offset=(page - 1) * page_size,
sort=sort,
highlight=None if wanted_topic_ids else highlight,
)
news_page = await _build_page(response, page, page_size)
await _attach_topics(news_page.results)
return news_page
def _keyword_should_clauses(keywords: list | None) -> list:
return [
{
"multi_match": {
"query": keyword.strip(),
"fields": KEYWORD_SEARCH_FIELDS,
"type": "phrase",
}
}
for keyword in (keywords or [])
if keyword and keyword.strip()
]
async def _topic_id_should_clauses(topic_ids: set) -> list:
"""Turns matched OpenAlex topics into id clauses, boosted by hit count.
Articles that match several of the searched topics get a higher boost, so
Elasticsearch ranks them above articles that only match one.
"""
topics_per_article = await _news_ids_by_topic_ids(topic_ids)
if not topics_per_article:
return []
ranked = sorted(topics_per_article.items(), key=lambda item: -len(item[1]))
ids_by_hit_count: dict[int, list] = {}
for news_id, matched_topics in ranked[:KEYWORD_SEARCH_ID_CAP]:
ids_by_hit_count.setdefault(len(matched_topics), []).append(news_id)
return [
{"ids": {"values": news_ids, "boost": float(hit_count)}}
for hit_count, news_ids in ids_by_hit_count.items()
]
async def _news_ids_by_topic_ids(topic_ids: set) -> dict:
"""Returns news_id -> set of searched topic ids the article was mapped to."""
query = {"terms": {"topic_matches.topic_id.keyword": sorted(topic_ids)}}
topics_per_article: dict[str, set] = {}
scanned = 0
try:
async for hit in elasticsearch.scan(
index=TOPICS_INDEX,
query=query,
source=["news_id", "topic_matches.topic_id"],
cluster="inse",
):
scanned += 1
source = hit.get("_source", {})
news_id = source.get("news_id")
if news_id:
matched = topics_per_article.setdefault(news_id, set())
for match in source.get("topic_matches") or []:
topic_id = match.get("topic_id")
if topic_id in topic_ids:
matched.add(topic_id)
if scanned >= KEYWORD_SEARCH_SCAN_CAP:
logger.warning(
f"Topic lookup hit the scan cap of {KEYWORD_SEARCH_SCAN_CAP} documents."
)
break
except Exception:
logger.exception("Topic lookup for the keyword news search failed.")
return {}
return {news_id: matched for news_id, matched in topics_per_article.items() if matched}
async def _attach_topics(articles: list) -> None:
news_ids = [article.id for article in articles if article.id]
if not news_ids:
return
topics_per_article = await _topics_for_news_ids(news_ids)
for article in articles:
article.topics = topics_per_article.get(article.id, [])
async def _topics_for_news_ids(news_ids: list) -> dict[str, list[MatchedTopic]]:
"""Reads the indexed OpenAlex topic matches for the given articles."""
try:
response = await elasticsearch.search(
index=TOPICS_INDEX,
query={"terms": {"news_id.keyword": news_ids}},
source=["news_id", "keyword", "topic_matches"],
size=min(len(news_ids) * TOPIC_DOCS_PER_ARTICLE, 10000),
cluster="inse",
)
except Exception:
logger.exception("Batched topic lookup for the news result page failed.")
return {}
topics_per_article: dict[str, list[MatchedTopic]] = {}
seen_per_article: dict[str, set] = {}
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
news_id = source.get("news_id")
if not news_id:
continue
keyword = source.get("keyword")
matched = topics_per_article.setdefault(news_id, [])
seen_ids = seen_per_article.setdefault(news_id, set())
for match in source.get("topic_matches") or []:
topic_id = match.get("topic_id")
if not topic_id or topic_id in seen_ids:
continue
seen_ids.add(topic_id)
matched.append(
MatchedTopic(
id=topic_id,
display_name=match.get("topic_display_name"),
subfield_name=match.get("subfield"),
field_name=match.get("field"),
domain_name=match.get("domain"),
source_keyword=keyword,
)
)
return topics_per_article
async def get_news_by_author(
author_id: str,
page: int = 1,
@@ -321,7 +525,7 @@ async def _get_article_keywords(
async def _get_article_topics(news_id: str, keywords: list) -> list:
indexed = await get_article_topics_from_index(news_id)
indexed = (await _topics_for_news_ids([news_id])).get(news_id, [])
if indexed:
return indexed
@@ -336,42 +540,6 @@ async def _get_article_topics(news_id: str, keywords: list) -> list:
return topics
async def get_article_topics_from_index(news_id: str) -> list:
try:
response = await elasticsearch.search(
index=TOPICS_INDEX,
query={"term": {"news_id.keyword": news_id}},
source=["keyword", "topic_matches"],
size=TOPICS_INDEX_MAX_PAIRS,
cluster="inse",
)
except Exception:
logger.exception(f"Topic-index lookup for {news_id} failed.")
return []
matched = []
seen_ids = set()
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
keyword = source.get("keyword")
for match in source.get("topic_matches") or []:
topic_id = match.get("topic_id")
if not topic_id or topic_id in seen_ids:
continue
seen_ids.add(topic_id)
matched.append(
MatchedTopic(
id=topic_id,
display_name=match.get("topic_display_name"),
subfield_name=match.get("subfield"),
field_name=match.get("field"),
domain_name=match.get("domain"),
source_keyword=keyword,
)
)
return matched
def _normalize_keywords(candidates: list) -> list:
"""Trims, dedups (case-insensitive) and caps the keywords from the LLM."""
seen = set()
@@ -516,7 +684,7 @@ async def _get_postproc_labels(news_id: str) -> tuple[bool | None, list, list, s
return relevant, authors, keywords, hit.get("_id")
async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict = None) -> dict:
async def _run_search(query: dict, source: list, size: int, offset: int, sort, highlight: dict | None = None) -> dict:
try:
return await elasticsearch.search(
index="aktuell",
+12 -11
View File
@@ -8,17 +8,6 @@ class NewsKeywords(BaseModel):
keywords: list[str] = Field(description="The extracted keywords from the article.")
class NewsArticle(BaseModel):
id: str
date: str | None = None
maintitle: str | None = None
author: str | None = None
url: str | None = None
relevant: bool | None = None
snippet: str | None = None
related: bool | None = None
class MentionedPerson(BaseModel):
name: str
is_ude: bool = False
@@ -34,6 +23,18 @@ class MatchedTopic(BaseModel):
source_keyword: str | None = None
class NewsArticle(BaseModel):
id: str
date: str | None = None
maintitle: str | None = None
author: str | None = None
url: str | None = None
relevant: bool | None = None
snippet: str | None = None
related: bool | None = None
topics: list[MatchedTopic] | None = None
class NewsArticleDetail(NewsArticle):
full_content: str | None = None
relevant: bool | None = None
+62
View File
@@ -100,6 +100,68 @@ async def search_news(
)
@router.get(
"/keyword/search",
operation_id="getNewsByKeywords",
response_model=NewsPage,
response_model_exclude_none=True,
summary="Searches news articles by the keywords or matched topics of a keywords search.",
tags=[Tags.NEWS],
)
async def search_news_by_keywords(
keywords: Annotated[
list[str] | None, Query(description="Raw keywords to match against title/content.")
] = None,
topic_ids: Annotated[
list[str] | None,
Query(alias="topicIds", description="OpenAlex topic ids the keywords resolved to."),
] = None,
filter_topic_ids: Annotated[
list[str] | None,
Query(alias="filterTopicIds", description="Additional topic ids to narrow the results by."),
] = None,
fuzzy: Annotated[
bool,
Query(description="Search by resolved topics if True, otherwise by raw keywords."),
] = False,
page: Annotated[
int, Query(description="Page number (1-based).", ge=1)
] = 1,
page_size: Annotated[
int, Query(alias="pageSize", description="Articles per page.", ge=1, le=100)
] = 10,
relevance: Annotated[
str | None, Query(description="Comma-separated relevance filter: 'relevant', 'not_relevant'.")
] = None,
year_from: Annotated[
int | None, Query(alias="yearFrom", description="Earliest publication year (inclusive).", ge=0)
] = None,
year_to: Annotated[
int | None, Query(alias="yearTo", description="Latest publication year (inclusive).", ge=0)
] = None,
sort_order: Annotated[
str | None,
Query(
alias="sortOrder",
description="Overrides relevance ranking with a date sort: 'desc' (newest first) or 'asc' (oldest first).",
pattern="^(asc|desc)$",
),
] = None,
):
return await logic.search_news_by_keywords(
keywords=keywords or [],
topic_ids=topic_ids or [],
filter_topic_ids=filter_topic_ids or [],
fuzzy=fuzzy,
page=page,
page_size=page_size,
sort_order=sort_order,
year_from=year_from,
year_to=year_to,
relevance_values=_parse_relevance(relevance),
)
@router.get(
"/by-author",
operation_id="getNewsByAuthor",
File diff suppressed because it is too large Load Diff
+1 -2
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -19,4 +19,3 @@ export interface DfgProjectTopic {
project_count: number;
keywords: Array<DfgProjectKeyword>;
}
+12 -12
View File
@@ -1,22 +1,22 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { MatchedTopic } from './matchedTopic';
export interface NewsArticle {
id: string;
date?: string | null;
maintitle?: string | null;
author?: string | null;
url?: string | null;
relevant?: boolean | null;
snippet?: string | null;
related?: boolean | null;
export interface NewsArticle {
id: string;
date?: string | null;
maintitle?: string | null;
author?: string | null;
url?: string | null;
relevant?: boolean | null;
snippet?: string | null;
related?: boolean | null;
topics?: Array<MatchedTopic> | null;
}
+14 -16
View File
@@ -1,7 +1,7 @@
/**
* Innovation Search Engine API
*
*
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
@@ -10,19 +10,17 @@
import { MatchedTopic } from './matchedTopic';
import { MentionedPerson } from './mentionedPerson';
export interface NewsArticleDetail {
id: string;
date?: string | null;
maintitle?: string | null;
author?: string | null;
url?: string | null;
relevant?: boolean | null;
snippet?: string | null;
related?: boolean | null;
full_content?: string | null;
authors?: Array<MentionedPerson>;
keywords?: Array<string>;
topics?: Array<MatchedTopic>;
export interface NewsArticleDetail {
id: string;
date?: string | null;
maintitle?: string | null;
author?: string | null;
url?: string | null;
relevant?: boolean | null;
snippet?: string | null;
related?: boolean | null;
topics?: Array<MatchedTopic>;
full_content?: string | null;
authors?: Array<MentionedPerson>;
keywords?: Array<string>;
}
+9 -1
View File
@@ -36,6 +36,7 @@ import {
workPageResolver,
workQueryParamKeys,
} from './resolvers/work-page.resolver';
import { keywordsNewsPageResolver } from './resolvers/keywords-news-page.resolver';
import { selectedTopicsResolver } from './resolvers/selected-topics.resolver';
import { selectedInstitutionsResolver } from './resolvers/selected-institutions.resolver';
import { selectedBundInstitutionsResolver } from './resolvers/selected-bund-institutions.resolver';
@@ -273,7 +274,14 @@ export const routes: Routes = [
resolvingFor: RESOLVING_WORK_PAGE_FOR.KEYWORDS_SEARCH,
},
},
{ path: 'news', component: KeywordsToNewsResultsComponent },
{
path: 'news',
component: KeywordsToNewsResultsComponent,
runGuardsAndResolvers: 'always',
resolve: {
newsPage: keywordsNewsPageResolver,
},
},
{
path: 'trends',
component: UniTrendParentComponent,
@@ -1,31 +1,152 @@
<div class="result-layout">
<mat-card class="results-card">
<mat-card-content class="results-placeholder">
<mat-icon>groups</mat-icon>
<h2>Newsliste</h2>
<p>
Die aktuelle Gewichtung ist unter <code>normalized</code> verfügbar.
</p>
</mat-card-content>
</mat-card>
<div class="content">
<div class="filters">
<app-filter-card>
<app-query-param-selector
class="relevance-field"
[options]="relevanceOptions"
[queryParamKey]="keywordsNewsQueryParamKeys.relevance"
label="Relevanz"
icon="check_circle"
[multiple]="true" />
<mat-card class="weights-card">
<mat-card-content>
<app-weights-sliders
[options]="weightOptions"
[initialWeights]="defaultWeights"
title="News-Gewichtung"
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
resetLabel="Ausgewogen"
applyLabel="Neu gewichten"
normalizedTitle="Normalisiert"
queryParamPrefix="newsW_"
[persistInQueryParams]="true"
[showApplyButton]="true"
[showResetButton]="true"
[showNormalizedPreview]="true"
(weightsChange)="onWeightsChange($event)"
(applyWeights)="onApplyWeights($event)" />
</mat-card-content>
</mat-card>
<app-query-param-selector
class="sort-order-field"
[options]="sortOrderOptions"
[queryParamKey]="keywordsNewsQueryParamKeys.sortOrder"
label="Sortierung"
icon="sort" />
</app-filter-card>
<app-year-range-slider
[minYear]="minYear"
[maxYear]="maxYear"
[(startYear)]="yearFrom"
[(endYear)]="yearTo"
(startYearChange)="applyYearFilter()"
(endYearChange)="applyYearFilter()">
</app-year-range-slider>
@if (hasActiveFilters()) {
<button
class="reset-filter-btn"
mat-stroked-button
type="button"
(click)="resetFilters()"
aria-label="Filter zurücksetzen">
<mat-icon>filter_alt_off</mat-icon>
<span>Zurücksetzen</span>
</button>
}
</div>
<ng-template #titleTmp let-article>
<div class="title-cell">
<a class="title" [routerLink]="['/news', article.id]">
{{ article.maintitle || 'Kein Titel' }}
</a>
@if (article.snippet) {
<span class="snippet" [innerHTML]="article.snippet"></span>
}
</div>
</ng-template>
<ng-template #dateTmp let-article>
@if (article.date) {
<span class="date-text">{{ article.date }}</span>
} @else {
<span class="empty-text">-</span>
}
</ng-template>
<ng-template #relevanceTmp let-article>
@if (article.relevant === true) {
<span class="relevance-badge is-relevant">
<mat-icon>check_circle</mat-icon>
Relevant
</span>
} @else if (article.relevant === false) {
<span class="relevance-badge not-relevant">
<mat-icon>cancel</mat-icon>
Nicht relevant
</span>
} @else {
<span
class="relevance-badge undetermined"
[matTooltip]="relevanceHelp"
matTooltipPosition="above">
<mat-icon>help</mat-icon>
Nicht bestimmt
</span>
}
</ng-template>
<ng-template #topicsTmp let-article>
@let topics = article.topics ?? [];
@let topicsExpanded = isTopicsExpanded(article);
@let visibleTopics =
topicsExpanded ? topics : topics.slice(0, topicPreviewCount);
<div class="topic-chips" aria-label="Themen">
@for (topic of visibleTopics; track topic.id ?? topic.display_name) {
<app-topic-chip-2
size="mini"
[topic]="toTopic(topic)"
[showIcon]="false"
[isSelected]="isTopicActive(topic)"
[isClickable]="fuzzySearch()"
(handleChipClick)="toggleTopicFilter($event)" />
} @empty {
<span class="empty-text">-</span>
}
@if (topics.length > topicPreviewCount) {
<app-chip-overflow-toggle
[expanded]="topicsExpanded"
[hiddenCount]="topics.length - topicPreviewCount"
(toggle)="toggleTopicsExpansion(article)" />
}
</div>
</ng-template>
<ng-template #actionsTmp let-article>
<a
mat-icon-button
color="primary"
[routerLink]="['/news', article.id]"
matTooltip="Details anzeigen">
<mat-icon>open_in_new</mat-icon>
</a>
</ng-template>
@if (!hasSearchInput()) {
<div class="no-results">
<span>Keine Keywords ausgewählt.</span>
</div>
} @else if (total() === 0) {
<div class="no-results">
@if (hasNarrowingFilters()) {
<span>Keine Nachrichten für die aktuellen Filter.</span>
<span class="no-results__hint">
Setzen Sie die Filter zurück, um mehr Ergebnisse zu sehen.
</span>
} @else if (searchedByTopics()) {
<span>Zu diesen Themen gibt es keine Nachrichten.</span>
<span class="no-results__hint">
Campus Aktuell deckt nicht jedes Forschungsthema ab. Schalten Sie die
Fuzzy Search aus, um direkt nach den Keywords zu suchen.
</span>
} @else {
<span>Keine Nachrichten zu diesen Keywords gefunden.</span>
}
</div>
} @else {
<div class="table-wrap">
<app-data-table [columns]="columns()" [data]="elements()" />
</div>
<app-query-param-paginator
[total]="total()"
queryParamPageKey="page"
queryParamSizeKey="size" />
}
</div>
@@ -1,29 +1,199 @@
.content {
display: flex;
flex-direction: column;
gap: 1rem;
}
/* ============================================================
RESULT LAYOUT
FILTERS
============================================================ */
.result-layout {
display: grid;
grid-template-columns: minmax(300px, 420px) 1fr;
grid-template-areas: 'summary results';
.filters {
display: flex;
flex-wrap: wrap;
align-items: stretch;
gap: 0.75rem;
align-items: start;
}
.search-summary-card {
grid-area: summary;
}
.relevance-field,
.sort-order-field {
min-width: 200px;
}
.results-card {
grid-area: results;
}
app-year-range-slider {
display: flex;
}
.search-summary-card,
.results-card {
background: var(--sg-surface);
border: 1px solid var(--sg-border);
box-shadow: none;
::ng-deep app-year-range-slider .year-filter {
height: 100%;
}
.mat-mdc-card-content {
padding: 0.75rem;
::ng-deep .mat-mdc-form-field-subscript-wrapper {
display: none;
}
::ng-deep .mat-mdc-form-field-icon-prefix {
padding: 0 4px 0 10px;
}
}
.reset-filter-btn {
display: flex;
align-self: center;
align-items: center;
gap: 0.25rem;
height: 40px;
}
/* ============================================================
TABLE
============================================================ */
.table-wrap {
position: relative;
overflow-x: auto;
}
::ng-deep .table-wrap table {
width: 100%;
min-width: 960px;
border-collapse: separate;
border-spacing: 0 10px;
box-shadow: none;
background: transparent;
}
::ng-deep .table-wrap .mat-mdc-header-cell {
color: var(--sg-text-muted);
font-size: 12px;
font-weight: 700;
}
::ng-deep .table-wrap .mat-mdc-row {
height: 86px;
}
::ng-deep .table-wrap .mat-mdc-cell {
color: var(--sg-text);
border-bottom-color: var(--sg-border);
font-size: 13px;
}
::ng-deep .table-wrap {
.mat-column-date,
.mat-column-relevant,
.mat-mdc-header-cell {
text-align: center;
}
.mat-column-topics {
overflow: visible;
}
}
/* ============================================================
TABLE CELLS
============================================================ */
.title-cell {
display: flex;
flex-direction: column;
gap: 0.25rem;
padding: 0.5rem 0;
max-width: 32rem;
}
.title {
display: inline-block;
max-width: 520px;
line-height: 1.35;
color: var(--sg-text);
font-size: 14px;
font-weight: 700;
text-decoration: none;
&:hover {
color: var(--sg-text);
text-decoration: underline;
}
}
.snippet {
font-size: 12.5px;
line-height: 1.5;
color: var(--sg-text-secondary);
overflow-wrap: anywhere;
::ng-deep em {
font-style: normal;
font-weight: 700;
color: var(--sg-blue-highlight);
}
}
.date-text {
white-space: nowrap;
}
.empty-text {
color: var(--sg-text-muted);
}
.relevance-badge {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 5px 12px;
border-radius: 999px;
font-size: 13px;
font-weight: 600;
line-height: 1;
white-space: nowrap;
mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
}
&.is-relevant {
background: var(--sg-success-soft);
border: 1px solid var(--sg-success);
color: var(--sg-success);
}
&.not-relevant {
background: var(--sg-surface-muted);
border: 1px solid var(--sg-border);
color: var(--sg-text-muted);
}
&.undetermined {
background: var(--sg-warning-soft);
border: 1px solid var(--sg-warning);
color: var(--sg-warning);
cursor: help;
}
}
.topic-chips {
display: flex;
flex-wrap: wrap;
gap: 0.25rem;
align-items: flex-start;
padding: 0.5rem 0;
max-width: 350px;
}
.no-results {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.5rem;
padding: 2rem;
color: var(--sg-text-muted);
text-align: center;
&__hint {
max-width: 34rem;
color: var(--sg-text-soft);
font-size: 0.8125rem;
line-height: 1.5;
}
}
@@ -1,115 +1,284 @@
import { Component, inject, signal } from '@angular/core';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import {
WeightMap,
WeightSliderOption,
WeightsSlidersComponent,
WeightsSlidersValue,
} from '../../../../shared/ui/weights-sliders/weights-sliders.component';
Component,
DestroyRef,
computed,
inject,
input,
signal,
TemplateRef,
viewChild,
} from '@angular/core';
import { ActivatedRoute, Router, RouterModule } from '@angular/router';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatchedTopic, NewsPage, Topic } from '../../../../api';
import {
DataTableComponent,
GenericColumn,
} from '../../../../shared/ui/data-table/data-table.component';
import { QueryParamPaginatorComponent } from '../../../../shared/ui/query-param-paginator/query-param-paginator.component';
import { AppTopicChipComponent } from '../../../../shared/ui/app-topic-chip/app-topic-chip.component';
import { ChipOverflowToggleComponent } from '../../../../shared/ui/chip-overflow-toggle/chip-overflow-toggle.component';
import { FilterCardComponent } from '../../../../shared/ui/filter-card/filter-card.component';
import {
QueryParamSelectorComponent,
SelectorOption,
} from '../../../../shared/ui/query-param-selector/query-param-selector.component';
import { NEWS_MIN_YEAR } from '../../../../shared/ui/news-card/news-card.component';
import { keywordsNewsQueryParamKeys } from '../../../../resolvers/keywords-news-page.resolver';
import { SearchResultsStateService } from '../search-results-state.service';
import { YearRangeSliderComponent } from '../../../../shared/ui/year-range-slider/year-range-slider.component';
type NewsResult = NewsPage['results'][number];
@Component({
selector: 'app-news-results',
imports: [MatCardModule, MatIconModule, WeightsSlidersComponent],
imports: [
RouterModule,
MatButtonModule,
MatIconModule,
MatTooltipModule,
DataTableComponent,
AppTopicChipComponent,
ChipOverflowToggleComponent,
FilterCardComponent,
QueryParamPaginatorComponent,
QueryParamSelectorComponent,
YearRangeSliderComponent,
],
templateUrl: './news-results.component.html',
styleUrl: './news-results.component.scss',
})
export class KeywordsToNewsResultsComponent {
// injects the state set by the parent route — no duplicate parsing here
protected readonly keywordsNewsQueryParamKeys = keywordsNewsQueryParamKeys;
private readonly state = inject(SearchResultsStateService);
private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly destroyRef = inject(DestroyRef);
readonly defaultWeights: WeightMap = {
param1: 0.33,
param2: 0.33,
param3: 0.34,
};
newsPage = input.required<NewsPage>();
readonly weightOptions: WeightSliderOption[] = [
{
key: 'param1',
label: 'Parameter 1',
icon: 'workspace_premium',
description: 'Gewichtet Parameter 1.',
defaultValue: 0.5,
queryParamName: 'wParam1',
},
{
key: 'param2',
label: 'Parameter 2',
icon: 'workspace_premium',
description: 'Gewichtet Parameter 2.',
defaultValue: 0.5,
queryParamName: 'wParam2',
},
{
key: 'param3',
label: 'Parameter 3',
icon: 'workspace_premium',
description: 'Gewichtet Parameter 3.',
defaultValue: 0.5,
queryParamName: 'wParam3',
},
readonly minYear = NEWS_MIN_YEAR;
readonly maxYear = new Date().getFullYear();
readonly relevanceHelp =
'Ein Artikel gilt als relevant, wenn er für Gründungsforschende interessante Inhalte enthält.';
readonly sortOrderOptions: SelectorOption[] = [
{ value: 'desc', display_name: 'Neueste zuerst' },
{ value: 'asc', display_name: 'Älteste zuerst' },
];
readonly currentWeights = signal<WeightsSlidersValue>({
raw: this.defaultWeights,
normalized: {
param1: 0.33,
param2: 0.33,
param3: 0.34,
},
rawSum: 2.5,
normalizedSum: 1,
valid: true,
readonly relevanceOptions: SelectorOption[] = [
{ value: 'relevant', display_name: 'Relevant' },
{ value: 'not_relevant', display_name: 'Nicht relevant' },
];
readonly yearFrom = signal<number>(this.minYear);
readonly yearTo = signal<number>(this.maxYear);
protected readonly topicPreviewCount = 3;
private readonly expandedTopicsIds = signal<ReadonlySet<string>>(new Set());
private readonly queryParamMap = toSignal(this.route.queryParamMap, {
initialValue: this.route.snapshot.queryParamMap,
});
readonly projects = signal<unknown[]>([]); // placeholder until the results service lands
readonly total = computed(() => this.newsPage().total ?? 0);
readonly elements = computed(() => this.newsPage().results ?? []);
readonly fuzzySearch = computed(
() => this.queryParamMap().get('fuzzy') === 'true',
);
private hasLoadedInitial = false;
constructor() {
console.log('check', this.state.payload());
}
onWeightsChange(value: WeightsSlidersValue): void {
this.currentWeights.set(value);
readonly hasSearchInput = computed(() =>
this.fuzzySearch()
? this.state.topicIds().length > 0 || this.state.keywords().length > 0
: this.state.keywords().length > 0,
);
// fires once with the query-param-aware initial state — use it to load
if (!this.hasLoadedInitial) {
this.hasLoadedInitial = true;
this.loadprojects();
readonly selectedTopicIds = computed(() =>
this.queryParamMap().getAll(keywordsNewsQueryParamKeys.topicId),
);
readonly hasActiveFilters = computed(() => {
const params = this.queryParamMap();
return (
!!params.get(keywordsNewsQueryParamKeys.relevance) ||
!!params.get(keywordsNewsQueryParamKeys.yearFrom) ||
!!params.get(keywordsNewsQueryParamKeys.yearTo) ||
!!params.get(keywordsNewsQueryParamKeys.sortOrder) ||
this.selectedTopicIds().length > 0
);
});
readonly hasNarrowingFilters = computed(() => {
const params = this.queryParamMap();
return (
!!params.get(keywordsNewsQueryParamKeys.relevance) ||
!!params.get(keywordsNewsQueryParamKeys.yearFrom) ||
!!params.get(keywordsNewsQueryParamKeys.yearTo) ||
this.selectedTopicIds().length > 0
);
});
readonly searchedByTopics = computed(() => {
if (!this.fuzzySearch()) {
return false;
}
const baseTopicIds = (this.queryParamMap().get('topics') ?? '')
.split(',')
.filter((value) => value.trim());
return baseTopicIds.length > 0 || this.selectedTopicIds().length > 0;
});
titleTmp = viewChild.required<TemplateRef<any>>('titleTmp');
dateTmp = viewChild.required<TemplateRef<any>>('dateTmp');
relevanceTmp = viewChild.required<TemplateRef<any>>('relevanceTmp');
topicsTmp = viewChild.required<TemplateRef<any>>('topicsTmp');
actionsTmp = viewChild.required<TemplateRef<any>>('actionsTmp');
readonly columns = computed<GenericColumn<NewsResult>[]>(() => [
{
id: 'maintitle',
header: 'Titel',
type: 'display',
cellTemplate: this.titleTmp(),
},
{
id: 'date',
header: 'Datum',
type: 'display',
cellTemplate: this.dateTmp(),
},
{
id: 'relevant',
header: 'Relevanz',
type: 'display',
cellTemplate: this.relevanceTmp(),
},
{
id: 'topics',
header: 'Themen',
type: 'display',
cellTemplate: this.topicsTmp(),
},
{
id: 'actions',
header: 'Aktionen',
type: 'display',
cellTemplate: this.actionsTmp(),
},
]);
constructor() {
this.route.queryParamMap
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((params) => {
this.yearFrom.set(
this.parseYear(params.get(keywordsNewsQueryParamKeys.yearFrom)) ??
this.minYear,
);
this.yearTo.set(
this.parseYear(params.get(keywordsNewsQueryParamKeys.yearTo)) ??
this.maxYear,
);
});
}
onApplyWeights(value: WeightsSlidersValue): void {
this.currentWeights.set(value);
this.loadprojects();
}
private loadprojects(): void {
const weights = this.currentWeights();
const requestPayload = {
manualKeywords: this.state.manualKeywords(),
extractedKeywords: this.state.extractedKeywords(),
keywords: this.state.keywords(),
fuzzy: this.state.fuzzySearch(),
weights: {
raw: weights.raw,
normalized: weights.normalized,
applyYearFilter(): void {
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
[keywordsNewsQueryParamKeys.yearFrom]:
this.yearFrom() > this.minYear ? this.yearFrom() : null,
[keywordsNewsQueryParamKeys.yearTo]:
this.yearTo() < this.maxYear ? this.yearTo() : null,
[keywordsNewsQueryParamKeys.page]: 0,
},
queryParamsHandling: 'merge',
});
}
toTopic(matched: MatchedTopic): Topic {
return {
id: matched.id,
display_name: matched.display_name,
subfield: matched.subfield_name
? { display_name: matched.subfield_name }
: null,
field: matched.field_name ? { display_name: matched.field_name } : null,
domain: matched.domain_name
? { display_name: matched.domain_name }
: null,
};
}
console.log(requestPayload);
isTopicActive(topic: MatchedTopic): boolean {
return !!topic.id && this.selectedTopicIds().includes(topic.id);
}
/**
* TODO:
* this.projectsService.searchprojects(requestPayload).subscribe({
* next: results => this.projects.set(results),
* error: error => console.error(error),
* });
*/
isTopicsExpanded(article: NewsResult): boolean {
return this.expandedTopicsIds().has(article.id);
}
toggleTopicsExpansion(article: NewsResult): void {
if (!article.id) {
return;
}
this.expandedTopicsIds.update((ids) => {
const next = new Set(ids);
if (next.has(article.id)) {
next.delete(article.id);
} else {
next.add(article.id);
}
return next;
});
}
toggleTopicFilter(topic: Topic): void {
if (!topic.id || !this.fuzzySearch()) {
return;
}
const selected = this.selectedTopicIds();
const next = selected.includes(topic.id)
? selected.filter((id) => id !== topic.id)
: [...selected, topic.id];
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
[keywordsNewsQueryParamKeys.topicId]: next.length ? next : null,
[keywordsNewsQueryParamKeys.page]: 0,
},
queryParamsHandling: 'merge',
});
}
resetFilters(): void {
this.router.navigate([], {
relativeTo: this.route,
queryParams: {
[keywordsNewsQueryParamKeys.relevance]: null,
[keywordsNewsQueryParamKeys.yearFrom]: null,
[keywordsNewsQueryParamKeys.yearTo]: null,
[keywordsNewsQueryParamKeys.topicId]: null,
[keywordsNewsQueryParamKeys.sortOrder]: null,
[keywordsNewsQueryParamKeys.page]: 0,
},
queryParamsHandling: 'merge',
});
}
private parseYear(raw: string | null): number | null {
const year = Number.parseInt(raw ?? '', 10);
return Number.isNaN(year) ? null : year;
}
}
@@ -40,13 +40,10 @@
}
@if (authorList.length > 3) {
<button
type="button"
class="publication-institution-more"
[attr.aria-expanded]="isExpanded"
(click)="togglePublicationAuthorsExpansion(pub)">
{{ isExpanded ? 'weniger' : '+' + (authorList.length - 3) }}
</button>
<app-chip-overflow-toggle
[expanded]="isExpanded"
[hiddenCount]="authorList.length - 3"
(toggle)="togglePublicationAuthorsExpansion(pub)" />
}
</div>
} @else {
@@ -6,29 +6,6 @@
background: var(--sg-card-bg);
border: 1px solid var(--sg-border);
}
.publication-institution-more {
display: inline-flex;
align-items: center;
min-height: 24px;
padding: 3px 8px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
background: var(--sg-surface);
color: var(--sg-text-muted);
font-family: inherit;
font-size: 11px;
line-height: 1.2;
cursor: pointer;
transition: all 0.2s ease;
&:hover,
&:focus-visible {
border-color: var(--sg-primary);
color: var(--sg-primary);
background: var(--sg-surface-soft);
outline: none;
}
}
.section-header {
display: flex;
align-items: center;
@@ -20,10 +20,12 @@ import {
DataTableComponent,
GenericColumn,
} from '../../../../shared/ui/data-table/data-table.component';
import { ChipOverflowToggleComponent } from '../../../../shared/ui/chip-overflow-toggle/chip-overflow-toggle.component';
@Component({
selector: 'app-publications-table',
imports: [
ChipOverflowToggleComponent,
CommonModule,
MatIcon,
MatCard,
@@ -0,0 +1,80 @@
import { ResolveFn } from '@angular/router';
import { inject } from '@angular/core';
import { of } from 'rxjs';
import { NewsPage, NewsService } from '../api';
export const keywordsNewsQueryParamKeys = {
page: 'page',
size: 'size',
relevance: 'relevance',
yearFrom: 'yearFrom',
yearTo: 'yearTo',
topicId: 'topicId',
sortOrder: 'sorting_order',
} as const;
const emptyPage = (page: number, pageSize: number): NewsPage => ({
total: 0,
page,
page_size: pageSize,
results: [],
});
export const keywordsNewsPageResolver: ResolveFn<NewsPage> = (route) => {
const params = route.queryParamMap;
const page = Number(params.get(keywordsNewsQueryParamKeys.page)) || 0;
const size = Number(params.get(keywordsNewsQueryParamKeys.size)) || 10;
const keywords = splitList(params.get('keywords'));
const topicIds = splitList(params.get('topics'));
const filterTopicIds = params.getAll(keywordsNewsQueryParamKeys.topicId);
const fuzzy = params.get('fuzzy') === 'true';
const canSearch = fuzzy
? topicIds.length > 0 || keywords.length > 0
: keywords.length > 0;
if (!canSearch) {
return of(emptyPage(page + 1, size));
}
const relevance =
params.get(keywordsNewsQueryParamKeys.relevance) || undefined;
const yearFrom = parseYear(params.get(keywordsNewsQueryParamKeys.yearFrom));
const yearTo = parseYear(params.get(keywordsNewsQueryParamKeys.yearTo));
const sortOrder = parseSortOrder(
params.get(keywordsNewsQueryParamKeys.sortOrder),
);
return inject(NewsService).getNewsByKeywords(
keywords,
topicIds,
filterTopicIds,
fuzzy,
page + 1,
size,
relevance,
yearFrom,
yearTo,
sortOrder,
);
};
function splitList(raw: string | null): string[] {
if (!raw) return [];
return raw
.split(',')
.map((value) => value.trim())
.filter(Boolean);
}
function parseYear(raw: string | null): number | undefined {
const year = Number.parseInt(raw ?? '', 10);
return Number.isNaN(year) ? undefined : year;
}
function parseSortOrder(raw: string | null): string | undefined {
return raw === 'asc' || raw === 'desc' ? raw : undefined;
}
@@ -105,13 +105,10 @@
<span class="empty-text">-</span>
}
@if (projectTopics.length > 3) {
<button
type="button"
class="publication-institution-more"
[attr.aria-expanded]="isTopicsExpanded"
(click)="toggleProjectTopicsExpansion(project)">
{{ isTopicsExpanded ? 'weniger' : '+' + (projectTopics.length - 3) }}
</button>
<app-chip-overflow-toggle
[expanded]="isTopicsExpanded"
[hiddenCount]="projectTopics.length - 3"
(toggle)="toggleProjectTopicsExpansion(project)" />
}
</div>
</ng-template>
@@ -121,30 +121,6 @@
}
}
.publication-institution-more {
display: inline-flex;
align-items: center;
min-height: 24px;
padding: 3px 8px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
background: var(--sg-surface);
color: var(--sg-text-muted);
font-family: inherit;
font-size: 11px;
line-height: 1.2;
cursor: pointer;
transition: all 0.2s ease;
&:hover,
&:focus-visible {
border-color: var(--sg-primary);
color: var(--sg-primary);
background: var(--sg-surface-soft);
outline: none;
}
}
// ------------------------
// Containers for chips
// ------------------------
@@ -25,9 +25,11 @@ import { ChipComponent } from '../chip/chip.component';
import { MatTooltip } from '@angular/material/tooltip';
import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors';
import { bundProjectQueryParamKeys } from '../../../resolvers/bund-projects.resolver';
import { ChipOverflowToggleComponent } from '../chip-overflow-toggle/chip-overflow-toggle.component';
@Component({
selector: 'app-bund-project-table',
imports: [
ChipOverflowToggleComponent,
DataTableComponent,
RouterModule,
MatIconModule,
@@ -0,0 +1,7 @@
<button
type="button"
class="chip-overflow-toggle"
[attr.aria-expanded]="expanded()"
(click)="toggle.emit()">
{{ expanded() ? 'weniger' : '+' + hiddenCount() }}
</button>
@@ -0,0 +1,27 @@
:host {
display: inline-flex;
}
.chip-overflow-toggle {
display: inline-flex;
align-items: center;
min-height: 24px;
padding: 3px 8px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
background: var(--sg-surface);
color: var(--sg-text-muted);
font-family: inherit;
font-size: 11px;
line-height: 1.2;
cursor: pointer;
transition: all 0.2s ease;
&:hover,
&:focus-visible {
border-color: var(--sg-primary);
color: var(--sg-primary);
background: var(--sg-surface-soft);
outline: none;
}
}
@@ -0,0 +1,14 @@
import { Component, input, output } from '@angular/core';
@Component({
selector: 'app-chip-overflow-toggle',
standalone: true,
templateUrl: './chip-overflow-toggle.component.html',
styleUrl: './chip-overflow-toggle.component.scss',
})
export class ChipOverflowToggleComponent {
expanded = input<boolean>(false);
hiddenCount = input<number>(0);
toggle = output<void>();
}
@@ -51,17 +51,10 @@
<span class="empty-text">-</span>
}
@if (classifications.length > 3) {
<button
type="button"
class="publication-institution-more"
[attr.aria-expanded]="isClassificationsExpanded"
(click)="toggleProjectClassificationsExpansion(project)">
{{
isClassificationsExpanded
? 'weniger'
: '+' + (classifications.length - 3)
}}
</button>
<app-chip-overflow-toggle
[expanded]="isClassificationsExpanded"
[hiddenCount]="classifications.length - 3"
(toggle)="toggleProjectClassificationsExpansion(project)" />
}
</div>
</ng-template>
@@ -88,17 +81,10 @@
<span class="empty-text">-</span>
}
@if (projectAuthors.length > 3) {
<button
type="button"
class="publication-institution-more"
[attr.aria-expanded]="isProjectAuthorsExpanded"
(click)="toggleProjectAuthorsExpansion(project)">
{{
isProjectAuthorsExpanded
? 'weniger'
: '+' + (projectAuthors.length - 3)
}}
</button>
<app-chip-overflow-toggle
[expanded]="isProjectAuthorsExpanded"
[hiddenCount]="projectAuthors.length - 3"
(toggle)="toggleProjectAuthorsExpansion(project)" />
}
</div>
</ng-template>
@@ -133,16 +119,10 @@
<span class="empty-text">-</span>
}
@if (institutions.length > 3) {
<button
type="button"
class="publication-institution-more"
(click)="toggleProjectInstitutionsExpansion(project)">
@if (isProjectInstitutionsExpanded(project)) {
Weniger anzeigen
} @else {
+{{ institutions.length - 3 }} weitere
}
</button>
<app-chip-overflow-toggle
[expanded]="isProjectInstitutionsExpanded(project)"
[hiddenCount]="institutions.length - 3"
(toggle)="toggleProjectInstitutionsExpansion(project)" />
}
</div>
</ng-template>
@@ -165,13 +145,10 @@
<span class="empty-text">-</span>
}
@if (projectTopics.length > 3) {
<button
type="button"
class="publication-institution-more"
[attr.aria-expanded]="isTopicsExpanded"
(click)="toggleProjectTopicsExpansion(project)">
{{ isTopicsExpanded ? 'weniger' : '+' + (projectTopics.length - 3) }}
</button>
<app-chip-overflow-toggle
[expanded]="isTopicsExpanded"
[hiddenCount]="projectTopics.length - 3"
(toggle)="toggleProjectTopicsExpansion(project)" />
}
</div>
</ng-template>
@@ -100,30 +100,6 @@
}
}
.publication-institution-more {
display: inline-flex;
align-items: center;
min-height: 24px;
padding: 3px 8px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
background: var(--sg-surface);
color: var(--sg-text-muted);
font-family: inherit;
font-size: 11px;
line-height: 1.2;
cursor: pointer;
transition: all 0.2s ease;
&:hover,
&:focus-visible {
border-color: var(--sg-primary);
color: var(--sg-primary);
background: var(--sg-surface-soft);
outline: none;
}
}
// ------------------------
// Containers for chips
// ------------------------
@@ -23,9 +23,11 @@ import { ActivatedRoute, Router } from '@angular/router';
import { DfgPersonSummary } from '../../../api/model/dfgPersonSummary';
import { MatTooltip } from '@angular/material/tooltip';
import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors';
import { ChipOverflowToggleComponent } from '../chip-overflow-toggle/chip-overflow-toggle.component';
@Component({
selector: 'app-dfg-project-table',
imports: [
ChipOverflowToggleComponent,
DataTableComponent,
RouterModule,
MatIconModule,
@@ -60,13 +60,10 @@
}
@if (projectAuthors.length > 3) {
<button
type="button"
class="publication-institution-more"
[attr.aria-expanded]="isExpanded"
(click)="toggleProjectAuthorsExpansion(project)">
{{ isExpanded ? 'weniger' : '+' + (projectAuthors.length - 3) }}
</button>
<app-chip-overflow-toggle
[expanded]="isExpanded"
[hiddenCount]="projectAuthors.length - 3"
(toggle)="toggleProjectAuthorsExpansion(project)" />
}
</div>
</ng-template>
@@ -103,13 +100,10 @@
}
@if (organizations.length > 3) {
<button
type="button"
class="publication-institution-more"
[attr.aria-expanded]="isExpanded"
(click)="toggleProjectOrganizationsExpansion(project)">
{{ isExpanded ? 'weniger' : '+' + (organizations.length - 3) }}
</button>
<app-chip-overflow-toggle
[expanded]="isExpanded"
[hiddenCount]="organizations.length - 3"
(toggle)="toggleProjectOrganizationsExpansion(project)" />
}
</div>
</ng-template>
@@ -133,13 +127,10 @@
}
@if (projectTopics.length > 3) {
<button
type="button"
class="publication-institution-more"
[attr.aria-expanded]="isExpanded"
(click)="toggleProjectTopicsExpansion(project)">
{{ isExpanded ? 'weniger' : '+' + (projectTopics.length - 3) }}
</button>
<app-chip-overflow-toggle
[expanded]="isExpanded"
[hiddenCount]="projectTopics.length - 3"
(toggle)="toggleProjectTopicsExpansion(project)" />
}
</div>
</ng-template>
@@ -100,30 +100,6 @@
}
}
.publication-institution-more {
display: inline-flex;
align-items: center;
min-height: 24px;
padding: 3px 8px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
background: var(--sg-surface);
color: var(--sg-text-muted);
font-family: inherit;
font-size: 11px;
line-height: 1.2;
cursor: pointer;
transition: all 0.2s ease;
&:hover,
&:focus-visible {
border-color: var(--sg-primary);
color: var(--sg-primary);
background: var(--sg-surface-soft);
outline: none;
}
}
// ------------------------
// Containers for chips
// ------------------------
@@ -32,9 +32,11 @@ import { euProjectQueryParamKeys } from '../../../resolvers/eu-cordis-projects.r
import { topicHierarchyColor } from '../../../resolvers/utils/topic-colors';
import { ChipComponent } from '../chip/chip.component';
import { AppAuthorChipComponent } from '../app-author-chip/app-author-chip.component';
import { ChipOverflowToggleComponent } from '../chip-overflow-toggle/chip-overflow-toggle.component';
@Component({
selector: 'app-eu-project-table',
imports: [
ChipOverflowToggleComponent,
DataTableComponent,
RouterModule,
MatIconModule,
@@ -0,0 +1 @@
<ng-content />
@@ -0,0 +1,10 @@
:host {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 8px 12px;
border: 1px solid var(--sg-border);
border-radius: 10px;
background: var(--sg-surface);
box-sizing: border-box;
}
@@ -0,0 +1,9 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-filter-card',
standalone: true,
templateUrl: './filter-card.component.html',
styleUrl: './filter-card.component.scss',
})
export class FilterCardComponent {}
@@ -94,17 +94,10 @@
<span class="empty-text">-</span>
}
@if (publicationInstitutions.length > 3) {
<button
type="button"
class="publication-institution-more"
[attr.aria-expanded]="institutionsExpanded"
(click)="toggleWorkInstitutionsExpansion(work)">
{{
institutionsExpanded
? 'weniger'
: '+' + (publicationInstitutions.length - 3)
}}
</button>
<app-chip-overflow-toggle
[expanded]="institutionsExpanded"
[hiddenCount]="publicationInstitutions.length - 3"
(toggle)="toggleWorkInstitutionsExpansion(work)" />
}
</div>
</ng-template>
@@ -130,13 +123,10 @@
<span class="empty-text">-</span>
}
@if (workAuthors.length > 3) {
<button
type="button"
class="publication-institution-more"
[attr.aria-expanded]="workAuthorsExpanded"
(click)="toggleWorkAuthorsExpansion(work)">
{{ workAuthorsExpanded ? 'weniger' : '+' + (workAuthors.length - 3) }}
</button>
<app-chip-overflow-toggle
[expanded]="workAuthorsExpanded"
[hiddenCount]="workAuthors.length - 3"
(toggle)="toggleWorkAuthorsExpansion(work)" />
}
</div>
</ng-template>
@@ -444,35 +444,6 @@ table.is-hidden {
max-width: 280px;
}
.publication-institution-more,
.publication-topic-more {
display: inline-flex;
align-items: center;
min-height: 24px;
padding: 3px 8px;
border: 1px solid var(--sg-border);
border-radius: var(--sg-radius-sm);
background: var(--sg-surface);
color: var(--sg-text-muted);
font-family: inherit;
font-size: 11px;
line-height: 1.2;
cursor: pointer;
transition: all 0.2s ease;
&:hover,
&:focus-visible {
border-color: var(--sg-primary);
color: var(--sg-primary);
background: var(--sg-surface-soft);
outline: none;
}
}
.publication-topic-more {
max-width: 180px;
}
::ng-deep .mat-mdc-header-cell {
color: var(--sg-text-muted);
font-size: 12px;
@@ -36,10 +36,12 @@ import { TopicTooltipComponent } from '../topic-tooltip/topic-tooltip.component'
import { AppTopicChipComponent } from '../app-topic-chip/app-topic-chip.component';
import { AppAuthorChipComponent } from '../app-author-chip/app-author-chip.component';
import { AppInstitutionChipComponent } from '../app-institution-chip/app-institution-chip.component';
import { ChipOverflowToggleComponent } from '../chip-overflow-toggle/chip-overflow-toggle.component';
@Component({
selector: 'app-publication-table',
imports: [
ChipOverflowToggleComponent,
MatIconModule,
MatTooltipModule,
MatButtonModule,
@@ -2,9 +2,14 @@
@if (label()) {
<mat-label>{{ label() }}</mat-label>
}
@if (icon()) {
<mat-icon matPrefix [fontIcon]="icon()"></mat-icon>
}
<mat-select
(selectionChange)="_handleSelectionChange($event)"
[value]="_urlValue()">
(openedChange)="_handleOpenedChange($event)"
[multiple]="multiple()"
[value]="_value()">
@for (option of _options(); track $index) {
<mat-option [value]="option.value">{{ option.display_name }}</mat-option>
}
@@ -1,6 +1,14 @@
import { Component, computed, inject, input, output } from '@angular/core';
import {
Component,
computed,
inject,
input,
output,
signal,
} from '@angular/core';
import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop';
import { FormsModule } from '@angular/forms';
import { MatIconModule } from '@angular/material/icon';
import { MatSelectChange, MatSelectModule } from '@angular/material/select';
import { ActivatedRoute, Router } from '@angular/router';
@@ -11,7 +19,7 @@ export type SelectorOption = {
@Component({
selector: 'app-query-param-selector',
imports: [FormsModule, MatSelectModule],
imports: [FormsModule, MatIconModule, MatSelectModule],
templateUrl: './query-param-selector.component.html',
styleUrl: './query-param-selector.component.scss',
})
@@ -21,6 +29,13 @@ export class QueryParamSelectorComponent {
handleSelectionChange = output<MatSelectChange>();
allowEmptyValue = input<boolean>(false);
label = input<string>('');
icon = input<string>('');
multiple = input<boolean>(false);
pageQueryParamKey = input<string | null>('page');
private readonly pendingValues = signal<string[] | null>(null);
_options = computed<SelectorOption[]>(() => {
const options = this.options();
@@ -50,14 +65,54 @@ export class QueryParamSelectorComponent {
return params && key ? params[key] || '' : '';
});
_urlValues = computed<string[]>(() => {
const raw = this._urlValue();
return raw
? raw
.split(',')
.map((value) => value.trim())
.filter(Boolean)
: [];
});
_value = computed<string | string[]>(() =>
this.multiple()
? (this.pendingValues() ?? this._urlValues())
: this._urlValue(),
);
_handleSelectionChange(event: MatSelectChange): void {
const newValue = event.value;
this.router.navigate([], {
queryParams: { [this.queryParamKey()]: newValue },
queryParamsHandling: 'merge',
});
if (this.multiple()) {
this.pendingValues.set(event.value ?? []);
return;
}
this.commit(event.value || null);
this.handleSelectionChange.emit(event);
}
_handleOpenedChange(opened: boolean): void {
if (opened || !this.multiple()) {
return;
}
const pending = this.pendingValues();
this.pendingValues.set(null);
if (pending !== null) {
this.commit(pending.length > 0 ? pending.join(',') : null);
}
}
private commit(value: string | null): void {
const pageKey = this.pageQueryParamKey();
this.router.navigate([], {
queryParams: {
[this.queryParamKey()]: value,
...(pageKey ? { [pageKey]: 0 } : {}),
},
queryParamsHandling: 'merge',
});
}
}