feature/keyword-search-works-table #304

Merged
kallweit merged 12 commits from feature/keyword-search-works-table into dev 2026-08-24 21:55:34 +02:00
26 changed files with 639 additions and 742 deletions
@@ -94,7 +94,10 @@ class Work(BaseModel):
content_url: StrictStr | None = Field(default=None, description="URL for downloading full-text content. Only present when `has_content.pdf` or `has_content.grobid_xml` is true.")
created_date: date | None = Field(default=None, description="When this work was added to OpenAlex (ISO 8601 date).")
updated_date: datetime | None = Field(default=None, description="When this work was last updated (ISO 8601 datetime).")
__properties: ClassVar[list[str]] = ["id", "doi", "title", "display_name", "publication_year", "publication_date", "type", "language", "cited_by_count", "is_retracted", "is_paratext", "primary_location", "locations", "best_oa_location", "open_access", "authorships", "ids", "biblio", "abstract_inverted_index", "referenced_works", "referenced_works_count", "related_works", "topics", "primary_topic", "keywords", "funders", "awards", "fwci", "citation_normalized_percentile", "cited_by_percentile_year", "counts_by_year", "sustainable_development_goals", "mesh", "indexed_in", "has_content", "content_url", "created_date", "updated_date"]
snippet: StrictStr | None = Field(default=None, description="Passage of the title or abstract containing the searched keyword, with the matches wrapped in `<em>`. Only set by the keyword search, and only when the keyword actually occurs in the text.")
snippet_field: StrictStr | None = Field(default=None, description="Which field `snippet` was taken from: `title` or `abstract`.")
matched_via: list[StrictStr] | None = Field(default=None, description="Names of the topics and OpenAlex keywords that matched the searched keywords. Set by the keyword search so a work matched purely on metadata can explain itself when there is no `snippet`.")
__properties: ClassVar[list[str]] = ["id", "doi", "title", "display_name", "publication_year", "publication_date", "type", "language", "cited_by_count", "is_retracted", "is_paratext", "primary_location", "locations", "best_oa_location", "open_access", "authorships", "ids", "biblio", "abstract_inverted_index", "referenced_works", "referenced_works_count", "related_works", "topics", "primary_topic", "keywords", "funders", "awards", "fwci", "citation_normalized_percentile", "cited_by_percentile_year", "counts_by_year", "sustainable_development_goals", "mesh", "indexed_in", "has_content", "content_url", "created_date", "updated_date", "snippet", "snippet_field", "matched_via"]
model_config = ConfigDict(
validate_by_name=True,
@@ -273,7 +276,10 @@ class Work(BaseModel):
"has_content": WorkHasContent.from_dict(obj["has_content"]) if obj.get("has_content") is not None else None,
"content_url": obj.get("content_url"),
"created_date": obj.get("created_date"),
"updated_date": obj.get("updated_date")
"updated_date": obj.get("updated_date"),
"snippet": obj.get("snippet"),
"snippet_field": obj.get("snippet_field"),
"matched_via": obj.get("matched_via")
})
return _obj
+13 -121
View File
@@ -4,7 +4,6 @@ Business logic for the "aktuell" news index on the INSE cluster.
"""
import logging
import re
from pydantic import ValidationError
@@ -12,6 +11,12 @@ from inse.exceptions import ElasticsearchException
from ..integrations import elasticsearch, llm
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
from ..snippets import (
FRAGMENT_FIELD,
HIGHLIGHT_TAGS,
SNIPPET_FRAGMENT_CHARS,
snippet_with_context,
)
from ..topics.logic import vector_search_topics_batch
from .model import (
MatchedTopic,
@@ -31,29 +36,16 @@ TOPICS_INDEX = "aktuell_openalex_topics"
_SESSION_TOPIC_CACHE: dict[str, list] = {}
SNIPPET_FRAGMENT_CHARS = 500
SNIPPET_FRAGMENT_COUNT = 3
SNIPPET_FRAGMENT_SEPARATOR = " … "
SNIPPET_CONTEXT_BEFORE_CHARS = 400
SNIPPET_CONTEXT_AFTER_CHARS = 1100
SNIPPET_BOUNDARY_CHARS = 150
SNIPPET_ELLIPSIS = "…"
_EM_TAG = re.compile(r"<em>(.*?)</em>", re.DOTALL)
PREVIEW_WORD_COUNT = 80
CONTENT_HIGHLIGHT = {
"fields": {
"full_content": {
"fragment_size": SNIPPET_FRAGMENT_CHARS,
"number_of_fragments": SNIPPET_FRAGMENT_COUNT,
**FRAGMENT_FIELD,
"no_match_size": SNIPPET_FRAGMENT_CHARS,
}
},
"pre_tags": ["<em>"],
"post_tags": ["</em>"],
**HIGHLIGHT_TAGS,
"require_field_match": False,
}
@@ -162,6 +154,7 @@ async def search_news_by_keywords(
year_to: int | None = None,
relevance_values: list | None = None,
sort_order: str | None = None,
title: str | None = None,
) -> NewsPage:
"""Searches the news for the keywords of a keywords-search run.
@@ -197,6 +190,9 @@ async def search_news_by_keywords(
return _empty_page(page, page_size)
clauses = await _filter_clauses(year_from, year_to, relevance_values)
if title and title.strip():
clauses.append({"match_phrase_prefix": {"maintitle": title.strip()}})
query = {
"bool": {
"should": should,
@@ -774,7 +770,7 @@ def _parse_hit(hit: dict) -> NewsArticle:
fragments = hit.get("highlight", {}).get("full_content")
if fragments:
snippet = _snippet_with_context(source, fragments)
snippet = snippet_with_context(source.get("full_content"), fragments)
else:
snippet = _make_preview(source)
@@ -788,110 +784,6 @@ def _parse_hit(hit: dict) -> NewsArticle:
)
def _snippet_with_context(source: dict, fragments: list) -> str:
joined = SNIPPET_FRAGMENT_SEPARATOR.join(fragments)
text = source.get("full_content")
terms = _marked_terms(joined)
if not text or not terms:
return joined
span = _first_term_span(text, terms)
if span is None:
return joined
start, end = _window_bounds(text, *span)
window = _mark_terms(text[start:end], terms)
if start > 0:
window = f"{SNIPPET_ELLIPSIS} {window}"
if end < len(text):
window = f"{window} {SNIPPET_ELLIPSIS}"
return window
def _marked_terms(fragment_text: str) -> list:
by_key: dict[str, str] = {}
for match in _EM_TAG.finditer(fragment_text):
term = match.group(1).strip()
if term:
by_key.setdefault(term.lower(), term)
return list(by_key.values())
def _first_term_span(text: str, terms: list) -> tuple | None:
lowered = text.lower()
spans = [
(index, index + len(term))
for term, index in ((term, lowered.find(term.lower())) for term in terms)
if index >= 0
]
return min(spans) if spans else None
def _window_bounds(text: str, match_start: int, match_end: int) -> tuple:
start = max(0, match_start - SNIPPET_CONTEXT_BEFORE_CHARS)
end = min(len(text), match_end + SNIPPET_CONTEXT_AFTER_CHARS)
if start > 0:
start = _forward_to_boundary(text, start, match_start)
if end < len(text):
end = _back_to_boundary(text, end, match_end)
return start, end
def _forward_to_boundary(text: str, start: int, limit: int) -> int:
ahead = text[start : min(limit, start + SNIPPET_BOUNDARY_CHARS)]
sentence = ahead.find(". ")
if sentence >= 0:
return start + sentence + 2
space = ahead.find(" ")
return start + space + 1 if space >= 0 else start
def _back_to_boundary(text: str, end: int, floor: int) -> int:
ahead = text[end : end + SNIPPET_BOUNDARY_CHARS]
sentence = ahead.find(". ")
if sentence >= 0:
return end + sentence + 1
space = text.rfind(" ", floor, end)
return space if space > floor else end
def _mark_terms(window: str, terms: list) -> str:
lowered = window.lower()
spans = sorted(
(index, index + len(term))
for term, index in ((term, lowered.find(term.lower())) for term in terms)
if index >= 0
)
marked = []
cursor = 0
for start, end in spans:
if start < cursor:
continue
marked.append(window[cursor:start])
marked.append(f"<em>{window[start:end]}</em>")
cursor = end
marked.append(window[cursor:])
return "".join(marked)
def _make_preview(source: dict) -> str | None:
text = source.get("full_content") or source.get("intro_content")
+5
View File
@@ -147,6 +147,10 @@ async def search_news_by_keywords(
pattern="^(asc|desc)$",
),
] = None,
title: Annotated[
str | None,
Query(description="Narrows the results to articles whose title matches this text."),
] = None,
):
return await logic.search_news_by_keywords(
keywords=keywords or [],
@@ -159,6 +163,7 @@ async def search_news_by_keywords(
year_from=year_from,
year_to=year_to,
relevance_values=_parse_relevance(relevance),
title=title,
)
+125
View File
@@ -0,0 +1,125 @@
import re
SNIPPET_FRAGMENT_CHARS = 500
SNIPPET_FRAGMENT_COUNT = 3
SNIPPET_FRAGMENT_SEPARATOR = " … "
SNIPPET_CONTEXT_BEFORE_CHARS = 400
SNIPPET_CONTEXT_AFTER_CHARS = 1100
SNIPPET_BOUNDARY_CHARS = 150
SNIPPET_ELLIPSIS = "…"
_EM_TAG = re.compile(r"<em>(.*?)</em>", re.DOTALL)
_SENTENCE_BREAK = re.compile(r"(?<![0-9]\.)(?<=[.!?])\s+|\n+")
FRAGMENT_FIELD = {
"fragment_size": SNIPPET_FRAGMENT_CHARS,
"number_of_fragments": SNIPPET_FRAGMENT_COUNT,
}
WHOLE_FIELD = {"number_of_fragments": 0}
HIGHLIGHT_TAGS = {"pre_tags": ["<em>"], "post_tags": ["</em>"]}
def snippet_with_context(text: str | None, fragments: list) -> str:
joined = SNIPPET_FRAGMENT_SEPARATOR.join(fragments)
terms = marked_terms(joined)
if not text or not terms:
return joined
span = _first_term_span(text, terms)
if span is None:
return joined
start, end = _window_bounds(text, *span)
window = _mark_terms(text[start:end], terms)
if start > 0:
window = f"{SNIPPET_ELLIPSIS} {window}"
if end < len(text):
window = f"{window} {SNIPPET_ELLIPSIS}"
return window
def marked_terms(fragment_text: str) -> list:
by_key: dict[str, str] = {}
for match in _EM_TAG.finditer(fragment_text):
term = match.group(1).strip()
if term:
by_key.setdefault(term.lower(), term)
return list(by_key.values())
def _first_term_span(text: str, terms: list) -> tuple | None:
lowered = text.lower()
spans = [
(index, index + len(term))
for term, index in ((term, lowered.find(term.lower())) for term in terms)
if index >= 0
]
return min(spans) if spans else None
def _window_bounds(text: str, match_start: int, match_end: int) -> tuple:
start = max(0, match_start - SNIPPET_CONTEXT_BEFORE_CHARS)
end = min(len(text), match_end + SNIPPET_CONTEXT_AFTER_CHARS)
if start > 0:
start = _forward_to_boundary(text, start, match_start)
if end < len(text):
end = _back_to_boundary(text, end, match_end)
return start, end
def _forward_to_boundary(text: str, start: int, limit: int) -> int:
ahead = _SENTENCE_BREAK.search(text, start, min(limit, start + SNIPPET_BOUNDARY_CHARS))
if ahead:
return ahead.end()
behind_from = max(0, start - SNIPPET_BOUNDARY_CHARS)
behind = list(_SENTENCE_BREAK.finditer(text, behind_from, start))
if behind:
return behind[-1].end()
if behind_from == 0:
return 0
space = text.find(" ", start, start + SNIPPET_BOUNDARY_CHARS)
return space + 1 if space >= 0 else start
def _back_to_boundary(text: str, end: int, floor: int) -> int:
sentence = _SENTENCE_BREAK.search(text, end, end + SNIPPET_BOUNDARY_CHARS)
if sentence:
return sentence.start()
space = text.rfind(" ", floor, end)
return space if space > floor else end
def _mark_terms(window: str, terms: list) -> str:
lowered = window.lower()
spans = sorted(
(index, index + len(term))
for term, index in ((term, lowered.find(term.lower())) for term in terms)
if index >= 0
)
marked = []
cursor = 0
for start, end in spans:
if start < cursor:
continue
marked.append(window[cursor:start])
marked.append(f"<em>{window[start:end]}</em>")
cursor = end
marked.append(window[cursor:])
return "".join(marked)
+73
View File
@@ -6,6 +6,12 @@ from inse.exceptions import ElasticsearchNotFoundException, NotFoundException
from inse.integrations import elasticsearch
from inse.model import ESCluster, ESIndex, SortDirection
from inse.models.openalex.work import Work
from inse.snippets import (
FRAGMENT_FIELD,
HIGHLIGHT_TAGS,
WHOLE_FIELD,
snippet_with_context,
)
from inse.works.v2.model import (
PrimaryCategoryYearAggregation,
PrimaryCategoryYearAggregationPage,
@@ -372,6 +378,17 @@ async def get_works_by_keywords(
track_total_hits=True,
offset=page * size,
sort=sort,
# A work matches on its topic and keyword metadata as well as on its
# text, so roughly half the hits contain the searched keyword nowhere in
# title or abstract. Highlighting tells the two apart: a fragment comes
# back only for the works that really do carry the phrase.
highlight={
"fields": {
"title": WHOLE_FIELD,
"abstract": FRAGMENT_FIELD,
},
**HIGHLIGHT_TAGS,
},
cluster=ESCluster.NES,
)
print(f"Elasticsearch response: {response}")
@@ -388,11 +405,67 @@ async def get_works_by_keywords(
work = Work.from_dict(source) # type: ignore
if work is not None:
snippet, snippet_field = _keyword_snippet(hit)
work.snippet = snippet
work.snippet_field = snippet_field
work.matched_via = _matched_via(source, keywords)
elements.append(work)
return WorkPageV2(elements=elements, total=total, page=page, size=size)
def _keyword_snippet(hit: dict) -> tuple[str | None, str | None]:
"""Picks the passage to show for a hit, preferring the title over the abstract."""
highlight = hit.get("highlight") or {}
title_fragments = highlight.get("title")
if title_fragments:
return title_fragments[0], "title"
abstract_fragments = highlight.get("abstract")
if abstract_fragments:
abstract = (hit.get("_source") or {}).get("abstract")
return snippet_with_context(abstract, abstract_fragments), "abstract"
return None, None
def _matched_via(source: dict, keywords: list[str] | None) -> list[str] | None:
"""Names the topics and keywords a work was matched through.
Only needed when there is no snippet: those works carry the searched term in
their metadata rather than in their text, and would otherwise expand into an
empty row. Matching mirrors the `match_phrase` clauses above closely enough
for a label - it is not used for retrieval.
"""
wanted = [kw.strip().lower() for kw in (keywords or []) if kw and kw.strip()]
if not wanted:
return None
candidates: list[str] = []
primary_topic = source.get("primary_topic") or {}
candidates.append(primary_topic.get("display_name"))
for topic in source.get("topics") or []:
candidates.append(topic.get("display_name"))
for level in ("field", "subfield", "domain"):
candidates.append((topic.get(level) or {}).get("display_name"))
for keyword in source.get("keywords") or []:
candidates.append(keyword.get("display_name"))
names: list[str] = []
for name in candidates:
if not name or name in names:
continue
lowered = name.lower()
if any(kw in lowered for kw in wanted):
names.append(name)
return names or None
async def get_author_works(
raw_oa_author_id: str,
page: int,
+20
View File
@@ -563,6 +563,7 @@ export class NewsService extends BaseService {
* @param yearFrom Earliest publication year (inclusive).
* @param yearTo Latest publication year (inclusive).
* @param sortOrder Overrides relevance ranking with a date sort: \&#39;desc\&#39; (newest first) or \&#39;asc\&#39; (oldest first).
* @param title Narrows the results to articles whose title matches this text.
* @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.
*/
@@ -577,6 +578,7 @@ export class NewsService extends BaseService {
yearFrom?: number,
yearTo?: number,
sortOrder?: string,
title?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
@@ -596,6 +598,7 @@ export class NewsService extends BaseService {
yearFrom?: number,
yearTo?: number,
sortOrder?: string,
title?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
@@ -615,6 +618,7 @@ export class NewsService extends BaseService {
yearFrom?: number,
yearTo?: number,
sortOrder?: string,
title?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
@@ -634,6 +638,7 @@ export class NewsService extends BaseService {
yearFrom?: number,
yearTo?: number,
sortOrder?: string,
title?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
@@ -705,6 +710,11 @@ export class NewsService extends BaseService {
<any>sortOrder,
'sortOrder',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>title,
'title',
);
let localVarHeaders = this.defaultHeaders;
@@ -769,6 +779,7 @@ export class NewsService extends BaseService {
* @param yearFrom Earliest publication year (inclusive).
* @param yearTo Latest publication year (inclusive).
* @param sortOrder Overrides relevance ranking with a date sort: \&#39;desc\&#39; (newest first) or \&#39;asc\&#39; (oldest first).
* @param title Narrows the results to articles whose title matches this text.
* @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.
*/
@@ -783,6 +794,7 @@ export class NewsService extends BaseService {
yearFrom?: number,
yearTo?: number,
sortOrder?: string,
title?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
@@ -802,6 +814,7 @@ export class NewsService extends BaseService {
yearFrom?: number,
yearTo?: number,
sortOrder?: string,
title?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
@@ -821,6 +834,7 @@ export class NewsService extends BaseService {
yearFrom?: number,
yearTo?: number,
sortOrder?: string,
title?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
@@ -840,6 +854,7 @@ export class NewsService extends BaseService {
yearFrom?: number,
yearTo?: number,
sortOrder?: string,
title?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
@@ -911,6 +926,11 @@ export class NewsService extends BaseService {
<any>sortOrder,
'sortOrder',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>title,
'title',
);
let localVarHeaders = this.defaultHeaders;
+43 -42
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
@@ -24,48 +24,49 @@ import { WorkHasContent } from './workHasContent';
import { Location } from './location';
import { WorkBiblio } from './workBiblio';
/**
* A scholarly document (article, book, dataset, thesis, etc.)
*/
export interface Work {
id?: string | null;
doi?: string | null;
title?: string | null;
display_name?: string | null;
publication_year?: number | null;
publication_date?: string | null;
type?: string | null;
language?: string | null;
cited_by_count?: number | null;
is_retracted?: boolean | null;
is_paratext?: boolean | null;
primary_location?: Location | null;
locations?: Array<Location> | null;
best_oa_location?: Location | null;
open_access?: OpenAccess | null;
authorships?: Array<Authorship> | null;
ids?: WorkIds | null;
biblio?: WorkBiblio | null;
abstract_inverted_index?: object | null;
referenced_works?: Array<string> | null;
referenced_works_count?: number | null;
related_works?: Array<string> | null;
topics?: Array<WorkTopic> | null;
primary_topic?: WorkTopic | null;
keywords?: Array<WorkKeyword> | null;
funders?: Array<DehydratedFunder> | null;
awards?: Array<Award> | null;
fwci?: Fwci | null;
citation_normalized_percentile?: WorkCitationNormalizedPercentile | null;
cited_by_percentile_year?: WorkCitedByPercentileYear | null;
counts_by_year?: Array<WorkCountsByYearInner> | null;
sustainable_development_goals?: Array<WorkSustainableDevelopmentGoalsInner> | null;
mesh?: Array<WorkMeshInner> | null;
indexed_in?: Array<string> | null;
has_content?: WorkHasContent | null;
content_url?: string | null;
created_date?: string | null;
updated_date?: string | null;
export interface Work {
id?: string | null;
doi?: string | null;
title?: string | null;
display_name?: string | null;
publication_year?: number | null;
publication_date?: string | null;
type?: string | null;
language?: string | null;
cited_by_count?: number | null;
is_retracted?: boolean | null;
is_paratext?: boolean | null;
primary_location?: Location | null;
locations?: Array<Location> | null;
best_oa_location?: Location | null;
open_access?: OpenAccess | null;
authorships?: Array<Authorship> | null;
ids?: WorkIds | null;
biblio?: WorkBiblio | null;
abstract_inverted_index?: object | null;
referenced_works?: Array<string> | null;
referenced_works_count?: number | null;
related_works?: Array<string> | null;
topics?: Array<WorkTopic> | null;
primary_topic?: WorkTopic | null;
keywords?: Array<WorkKeyword> | null;
funders?: Array<DehydratedFunder> | null;
awards?: Array<Award> | null;
fwci?: Fwci | null;
citation_normalized_percentile?: WorkCitationNormalizedPercentile | null;
cited_by_percentile_year?: WorkCitedByPercentileYear | null;
counts_by_year?: Array<WorkCountsByYearInner> | null;
sustainable_development_goals?: Array<WorkSustainableDevelopmentGoalsInner> | null;
mesh?: Array<WorkMeshInner> | null;
indexed_in?: Array<string> | null;
has_content?: WorkHasContent | null;
content_url?: string | null;
created_date?: string | null;
updated_date?: string | null;
snippet?: string | null;
snippet_field?: string | null;
matched_via?: Array<string> | null;
}
@@ -1,74 +1,60 @@
<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_ICON"
[multiple]="true" />
<app-query-param-input
class="title-field"
[queryParamKey]="keywordsNewsQueryParamKeys.title"
[queryParamPageKey]="keywordsNewsQueryParamKeys.page"
label="Suchen nach Titel"
[debounceTime]="300" />
<app-query-param-selector
class="sort-order-field"
[options]="sortOrderOptions"
[queryParamKey]="keywordsNewsQueryParamKeys.sortOrder"
label="Sortierung"
[icon]="SORT_ICON" />
</app-filter-card>
<div class="filter-row">
<app-filter-card>
<app-query-param-selector
class="relevance-field"
[options]="relevanceOptions"
[queryParamKey]="keywordsNewsQueryParamKeys.relevance"
label="Relevanz"
[icon]="CHECK_CIRCLE_ICON"
[multiple]="true" />
<app-year-range-slider
[minYear]="minYear"
[maxYear]="maxYear"
[(startYear)]="yearFrom"
[(endYear)]="yearTo"
(startYearChange)="applyYearFilter()"
(endYearChange)="applyYearFilter()">
</app-year-range-slider>
<app-query-param-selector
class="sort-order-field"
[options]="sortOrderOptions"
[queryParamKey]="keywordsNewsQueryParamKeys.sortOrder"
label="Sortierung"
[icon]="SORT_ICON" />
</app-filter-card>
@if (hasActiveFilters()) {
<button
class="reset-filter-btn"
mat-stroked-button
type="button"
(click)="resetFilters()"
aria-label="Filter zurücksetzen">
<mat-icon>{{ FILTER_OFF_ICON }}</mat-icon>
<span>Zurücksetzen</span>
</button>
}
<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_OFF_ICON }}</mat-icon>
<span>Zurücksetzen</span>
</button>
}
</div>
</div>
<ng-template #expandTmp let-article>
@if (article.snippet) {
@let expanded = isSnippetExpanded(article);
<button
mat-icon-button
class="expand-toggle"
[attr.aria-expanded]="expanded"
[matTooltip]="
expanded ? 'Textstelle ausblenden' : 'Textstelle anzeigen'
"
[attr.aria-label]="
expanded ? 'Textstelle ausblenden' : 'Textstelle anzeigen'
">
<mat-icon class="expand-icon" [class.is-expanded]="expanded">
{{ EXPAND_MORE_ICON }}
</mat-icon>
</button>
}
</ng-template>
<ng-template #titleTmp let-article>
<div class="title-cell">
<a
class="title"
[routerLink]="['/news', article.id]"
(click)="$event.stopPropagation()">
<span class="title">
<app-highlighted-text
[content]="article.maintitle || 'Kein Titel'"
[highlights]="titleHighlights().get(article.id) ?? []" />
</a>
</span>
</div>
</ng-template>
@@ -201,12 +187,11 @@
}
</div>
} @else {
<div class="table-wrap">
<app-data-table
[columns]="columns()"
[data]="elements()"
[detailTemplate]="snippetTmp" />
</div>
<app-data-table
[columns]="columns()"
[data]="elements()"
[detailTemplate]="fuzzySearch() ? null : snippetTmp"
[canExpand]="hasSnippet" />
<app-query-param-paginator
[total]="total()"
@@ -9,10 +9,20 @@
============================================================ */
.filters {
display: flex;
flex-wrap: wrap;
align-items: stretch;
flex-direction: column;
gap: 0.75rem;
.title-field {
width: 100%;
}
.filter-row {
display: flex;
flex-wrap: wrap;
align-items: stretch;
gap: 0.75rem;
}
.relevance-field,
.sort-order-field {
min-width: 200px;
@@ -43,54 +53,6 @@
height: 40px;
}
/* ============================================================
TABLE
============================================================ */
.table-wrap {
position: relative;
overflow-x: auto;
}
::ng-deep .table-wrap table {
width: 100%;
min-width: 960px;
border-collapse: collapse;
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-topics {
overflow: visible;
}
.mat-column-expand {
width: 48px;
padding-right: 0;
}
.detail-row .mat-mdc-cell {
padding: 0;
border-bottom: none;
}
}
/* ============================================================
TABLE CELLS
============================================================ */
@@ -104,32 +66,16 @@
.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;
}
font-size: 12px;
line-height: 1.5;
overflow-wrap: anywhere;
app-highlighted-text {
display: inline;
}
}
.expand-icon {
color: var(--sg-text-muted);
transition: transform 150ms ease-in-out;
&.is-expanded {
transform: rotate(180deg);
}
}
.date-text {
white-space: nowrap;
}
@@ -178,10 +124,10 @@
.topic-chips {
display: flex;
flex-wrap: wrap;
gap: 0.25rem;
gap: 6px;
align-items: flex-start;
padding: 0.5rem 0;
max-width: 350px;
max-width: 320px;
}
.no-results {
@@ -21,6 +21,7 @@ import {
GenericColumn,
} from '../../../../shared/ui/data-table/data-table.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';
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';
@@ -30,12 +31,14 @@ import {
} 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 {
SearchResultsStateService,
SnippetHighlight,
} from '../search-results-state.service';
import { YearRangeSliderComponent } from '../../../../shared/ui/year-range-slider/year-range-slider.component';
import {
CANCEL_ICON,
CHECK_CIRCLE_ICON,
EXPAND_MORE_ICON,
FILTER_OFF_ICON,
HELP_ICON,
OPEN_IN_NEW_ICON,
@@ -50,11 +53,6 @@ import { TableDetailRowComponent } from '../../../../shared/ui/table-detail-row/
type NewsResult = NewsPage['results'][number];
interface SnippetHighlight {
content: string;
terms: HighlightTerm[];
}
@Component({
selector: 'app-news-results',
imports: [
@@ -69,6 +67,7 @@ interface SnippetHighlight {
ChipOverflowToggleComponent,
FilterCardComponent,
QueryParamPaginatorComponent,
QueryParamInputComponent,
QueryParamSelectorComponent,
YearRangeSliderComponent,
],
@@ -79,7 +78,6 @@ export class KeywordsToNewsResultsComponent {
readonly CHECK_CIRCLE_ICON = CHECK_CIRCLE_ICON;
readonly SORT_ICON = SORT_ICON;
readonly FILTER_OFF_ICON = FILTER_OFF_ICON;
readonly EXPAND_MORE_ICON = EXPAND_MORE_ICON;
readonly CANCEL_ICON = CANCEL_ICON;
readonly HELP_ICON = HELP_ICON;
readonly OPEN_IN_NEW_ICON = OPEN_IN_NEW_ICON;
@@ -142,6 +140,7 @@ export class KeywordsToNewsResultsComponent {
!!params.get(keywordsNewsQueryParamKeys.yearFrom) ||
!!params.get(keywordsNewsQueryParamKeys.yearTo) ||
!!params.get(keywordsNewsQueryParamKeys.sortOrder) ||
!!params.get(keywordsNewsQueryParamKeys.title) ||
this.selectedTopicIds().length > 0
);
});
@@ -152,6 +151,7 @@ export class KeywordsToNewsResultsComponent {
!!params.get(keywordsNewsQueryParamKeys.relevance) ||
!!params.get(keywordsNewsQueryParamKeys.yearFrom) ||
!!params.get(keywordsNewsQueryParamKeys.yearTo) ||
!!params.get(keywordsNewsQueryParamKeys.title) ||
this.selectedTopicIds().length > 0
);
});
@@ -166,22 +166,13 @@ export class KeywordsToNewsResultsComponent {
return baseTopicIds.length > 0 || this.selectedTopicIds().length > 0;
});
expandTmp = viewChild.required<TemplateRef<any>>('expandTmp');
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');
private readonly dataTable = viewChild(DataTableComponent);
readonly columns = computed<GenericColumn<NewsResult>[]>(() => [
{
id: 'expand',
header: '',
type: 'display',
cellTemplate: this.expandTmp(),
},
{
id: 'maintitle',
header: 'Titel',
@@ -261,17 +252,15 @@ export class KeywordsToNewsResultsComponent {
return !!topic.id && this.selectedTopicIds().includes(topic.id);
}
isSnippetExpanded(article: NewsResult): boolean {
return this.dataTable()?.expandedElement() === article;
}
readonly snippetHighlights = computed(() => {
const byArticleId = new Map<string, SnippetHighlight>();
for (const article of this.elements()) {
const snippet = this.buildSnippetHighlight(article);
if (snippet) {
byArticleId.set(article.id, snippet);
if (article.snippet) {
byArticleId.set(
article.id,
this.state.snippetHighlight(article.snippet),
);
}
}
@@ -287,50 +276,14 @@ export class KeywordsToNewsResultsComponent {
containsHighlightTerm(article.maintitle, [keyword]),
);
if (found.length) {
byArticleId.set(article.id, this.toHighlightTerms(found));
byArticleId.set(article.id, this.state.highlightTerms(found));
}
}
return byArticleId;
});
private buildSnippetHighlight(article: NewsResult): SnippetHighlight | null {
const snippet = article.snippet;
if (!snippet) {
return null;
}
return {
content: snippet.replace(/<\/?em>/g, ''),
terms: this.toHighlightTerms([
...this.state.keywords(),
...this.markedTerms(snippet),
]),
};
}
private markedTerms(snippet: string): string[] {
return [...snippet.matchAll(/<em>([\s\S]*?)<\/em>/g)].map((match) =>
match[1].trim(),
);
}
private toHighlightTerms(terms: string[]): HighlightTerm[] {
const seen = new Set<string>();
const result: HighlightTerm[] = [];
for (const raw of terms) {
const term = raw.trim();
const key = term.toLowerCase();
if (!term || seen.has(key)) {
continue;
}
seen.add(key);
result.push({ term, topic: this.state.resolveTopicForTerm(term) });
}
return result;
}
readonly hasSnippet = (article: NewsResult): boolean => !!article.snippet;
isTopicsExpanded(article: NewsResult): boolean {
return this.expandedTopicsIds().has(article.id);
@@ -381,6 +334,7 @@ export class KeywordsToNewsResultsComponent {
[keywordsNewsQueryParamKeys.yearTo]: null,
[keywordsNewsQueryParamKeys.topicId]: null,
[keywordsNewsQueryParamKeys.sortOrder]: null,
[keywordsNewsQueryParamKeys.title]: null,
[keywordsNewsQueryParamKeys.page]: 0,
},
queryParamsHandling: 'merge',
@@ -1,9 +1,15 @@
import { Injectable, computed, signal } from '@angular/core';
import { KeywordEntryWithTopic } from '../../../api/model/keywordEntryWithTopic';
import { Topic } from '../../../api';
import { HighlightTerm } from '../../../shared/ui/highlighted-text/highlighted-text.component';
import { TopicHierarchyColorInput } from '../../../resolvers/utils/topic-colors';
export type KeywordPatentLevel = 'broad' | 'coarse' | 'fine' | 'custom';
export interface SnippetHighlight {
content: string;
terms: HighlightTerm[];
}
export interface PatentKeywordEntry {
entry: KeywordEntryWithTopic;
level: KeywordPatentLevel;
@@ -183,6 +189,41 @@ export class SearchResultsStateService {
return null;
}
/**
* Splits an Elasticsearch snippet into the text to show and the terms to
* mark in it: the searched keywords, plus whatever the search marked with
* <em> that catches the inflected forms the analyzer found.
*/
public snippetHighlight(snippet: string): SnippetHighlight {
const marked = [...snippet.matchAll(/<em>([\s\S]*?)<\/em>/g)].map((match) =>
match[1].trim(),
);
return {
content: snippet.replace(/<\/?em>/g, ''),
terms: this.highlightTerms([...this.keywords(), ...marked]),
};
}
/** Pairs each term with the topic it resolved to; the first spelling wins. */
public highlightTerms(terms: readonly string[]): HighlightTerm[] {
const seen = new Set<string>();
const result: HighlightTerm[] = [];
for (const raw of terms) {
const term = raw.trim();
const key = term.toLowerCase();
if (!term || seen.has(key)) {
continue;
}
seen.add(key);
result.push({ term, topic: this.resolveTopicForTerm(term) });
}
return result;
}
// Parallel topic-name list for trend dashboard strategies. Entries
// without a resolvable keyword are skipped when building the lookup map
// so they can never collide on an `undefined` key and shadow a real one.
@@ -5,11 +5,50 @@
[selectedAuthorsPage]="selectedAuthorsPage()"
[showTopicFilter]="fuzzySearch()" />
<ng-template #snippetTmp let-work>
<app-table-detail-row>
<div table-detail-header>
<h4 class="panel-field__label">Fundstelle in der Publikation</h4>
</div>
<ng-container table-detail-body>
@if (snippetHighlights().get(work.id); as snippet) {
<article class="panel-field panel-field--full">
<h4 class="panel-field__label">{{ snippetSourceLabel(work) }}</h4>
<app-highlighted-text
class="panel-field__text"
[content]="snippet.content"
[highlights]="snippet.terms" />
</article>
} @else if (work.matched_via?.length) {
<article class="panel-field panel-field--full">
<h4 class="panel-field__label">Kein Treffer im Text</h4>
<p class="panel-field__text">
Das gesuchte Keyword kommt weder im Titel noch im Abstract vor.
Die Publikation wurde über
{{ work.matched_via!.length === 1 ? 'das Thema' : 'die Themen' }}
@for (name of work.matched_via; track name; let last = $last) {
<span class="matched-topic">{{ name }}</span
>{{ last ? '' : ', ' }}
}
gefunden.
</p>
</article>
} @else {
<span class="empty-text">
Für diese Publikation liegt keine Fundstelle vor.
</span>
}
</ng-container>
</app-table-detail-row>
</ng-template>
<app-publication-table
[page]="workPage()"
[authorFilterEnabled]="true"
[institutionFilterEnabled]="true"
[topicFilterEnabled]="fuzzySearch()" />
[topicFilterEnabled]="fuzzySearch()"
[detailTemplate]="fuzzySearch() ? null : snippetTmp" />
<app-query-param-paginator
[total]="total()"
@@ -82,3 +82,12 @@
align-items: center;
gap: 0.5rem;
}
.matched-topic {
color: var(--sg-text);
font-weight: 600;
}
.empty-text {
color: var(--sg-text-muted);
}
@@ -11,8 +11,18 @@ import { PublicationTableComponent } from '../../../../shared/ui/publication-tab
import { WorkPageV2 } from '../../../../api/model/workPageV2';
import { PaginationService } from '../../../../shared/services/pagination.service';
import { QueryParamPaginatorComponent } from '../../../../shared/ui/query-param-paginator/query-param-paginator.component';
import { AuthorPage, InstitutionPageV2, TopicPageV2 } from '../../../../api';
import { SearchResultsStateService } from '../search-results-state.service';
import {
AuthorPage,
InstitutionPageV2,
TopicPageV2,
Work,
} from '../../../../api';
import {
SearchResultsStateService,
SnippetHighlight,
} from '../search-results-state.service';
import { HighlightedTextComponent } from '../../../../shared/ui/highlighted-text/highlighted-text.component';
import { TableDetailRowComponent } from '../../../../shared/ui/table-detail-row/table-detail-row.component';
@Component({
selector: 'app-works-results',
@@ -23,6 +33,8 @@ import { SearchResultsStateService } from '../search-results-state.service';
PublicationTableComponent,
PublicationFilterComponent,
QueryParamPaginatorComponent,
HighlightedTextComponent,
TableDetailRowComponent,
],
templateUrl: './works-results.component.html',
styleUrl: './works-results.component.scss',
@@ -64,6 +76,22 @@ export class KeywordsToWorksResultsComponent implements OnInit {
fuzzySearch = computed(() => this.queryParamMap().get('fuzzy') === 'true');
readonly snippetHighlights = computed(() => {
const byWorkId = new Map<string, SnippetHighlight>();
for (const work of this.elements()) {
if (work.id && work.snippet) {
byWorkId.set(work.id, this.state.snippetHighlight(work.snippet));
}
}
return byWorkId;
});
snippetSourceLabel(work: Work): string {
return work.snippet_field === 'title' ? 'Titel' : 'Abstract';
}
ngOnInit(): void {}
clearFilters(): void {
@@ -12,6 +12,7 @@ export const keywordsNewsQueryParamKeys = {
yearTo: 'yearTo',
topicId: 'topicId',
sortOrder: 'sorting_order',
title: 'title',
} as const;
const emptyPage = (page: number, pageSize: number): NewsPage => ({
@@ -47,6 +48,7 @@ export const keywordsNewsPageResolver: ResolveFn<NewsPage> = (route) => {
const sortOrder = parseSortOrder(
params.get(keywordsNewsQueryParamKeys.sortOrder),
);
const title = params.get(keywordsNewsQueryParamKeys.title) || undefined;
return inject(NewsService).getNewsByKeywords(
keywords,
@@ -59,6 +61,7 @@ export const keywordsNewsPageResolver: ResolveFn<NewsPage> = (route) => {
yearFrom,
yearTo,
sortOrder,
title,
);
};
@@ -1,186 +0,0 @@
import { MatchedTopic } from '../../api';
import { topicHierarchyColor } from './topic-colors';
/** A keyword together with the colour and names of the topics it resolved to. */
export interface KeywordColor {
keyword: string;
color: string;
topicNames: string[];
}
/** Pairs every keyword that resolved to a topic with that topic's colour. */
export function topicKeywordColors(
topics: readonly MatchedTopic[] | null | undefined,
keywords?: readonly string[] | null,
): KeywordColor[] {
const byKeyword = new Map<string, Omit<KeywordColor, 'keyword'>>();
for (const topic of topics ?? []) {
if (!topic.source_keyword) {
continue;
}
const key = topic.source_keyword.toLowerCase();
const topicName = topic.display_name?.trim();
const existing = byKeyword.get(key);
if (existing) {
if (topicName && !existing.topicNames.includes(topicName)) {
existing.topicNames.push(topicName);
}
continue;
}
byKeyword.set(key, {
color: topicHierarchyColor({
id: topic.id,
name: topic.display_name,
field_name: topic.field_name,
domain_name: topic.domain_name,
}),
topicNames: topicName ? [topicName] : [],
});
}
const source =
keywords ??
(topics ?? [])
.map((topic) => topic.source_keyword)
.filter((keyword): keyword is string => !!keyword);
const seen = new Set<string>();
const result: KeywordColor[] = [];
for (const keyword of source) {
const key = keyword.toLowerCase();
const entry = byKeyword.get(key);
if (!entry || seen.has(key)) {
continue;
}
seen.add(key);
result.push({ keyword, ...entry });
}
return result;
}
/** Explains, for a mark in the text, which topics its keyword is assigned to. */
export function keywordTooltip(
keyword: string,
topicNames: readonly string[],
): string {
if (!topicNames.length) {
return `„${keyword}“ ist keinem der aufgelisteten Themen zugeordnet.`;
}
if (topicNames.length === 1) {
return `„${keyword}“ ist dem Thema „${topicNames[0]}“ zugeordnet.`;
}
const names = topicNames.map((name) => `„${name}“`).join(', ');
return `„${keyword}“ ist den Themen ${names} zugeordnet.`;
}
const WORD_CHAR = '[\\w\\u00C0-\\u024F]';
export const KW_MARK_CLASS = 'kw-mark';
export interface KeywordSegment {
text: string;
match: KeywordColor | null;
}
export function splitByKeywords(
text: string,
keywordColors: readonly KeywordColor[],
): KeywordSegment[] {
const sorted = [...keywordColors]
.filter(({ keyword }) => keyword.trim())
.sort((a, b) => b.keyword.length - a.keyword.length);
if (!sorted.length) {
return text ? [{ text, match: null }] : [];
}
// Acronyms are matched exactly, everything else may carry an inflection
// ("Gründung" also marks "Gründungen").
const alternatives = sorted.map(({ keyword }) =>
isAcronymLike(keyword)
? `${escapeRegex(keyword)}(?!${WORD_CHAR})`
: `${escapeRegex(keyword)}${WORD_CHAR}*`,
);
const pattern = new RegExp(
`(?<!${WORD_CHAR})(?:${alternatives.join('|')})`,
'gi',
);
const segments: KeywordSegment[] = [];
let lastIndex = 0;
let match: RegExpExecArray | null;
const pushPlain = (value: string) => {
if (value) {
segments.push({ text: value, match: null });
}
};
while ((match = pattern.exec(text)) !== null) {
const matched = match[0];
const entry = sorted.find(({ keyword }) =>
matched.toLowerCase().startsWith(keyword.toLowerCase()),
);
if (!entry) {
continue;
}
pushPlain(text.slice(lastIndex, match.index));
segments.push({ text: matched, match: entry });
lastIndex = match.index + matched.length;
}
pushPlain(text.slice(lastIndex));
return segments;
}
export function highlightKeywords(
text: string,
keywordColors: readonly KeywordColor[],
): string {
return splitByKeywords(text, keywordColors)
.map(({ text: value, match }) => {
if (!match) {
return escapeHtml(value);
}
const tooltip = escapeHtml(
keywordTooltip(match.keyword, match.topicNames),
);
return (
`<mark class="${KW_MARK_CLASS}" style="--t:${match.color}"` +
` data-kw="${escapeHtml(match.keyword)}" title="${tooltip}">` +
`${escapeHtml(value)}</mark>`
);
})
.join('');
}
export function escapeHtml(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
function escapeRegex(text: string): string {
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function isAcronymLike(keyword: string): boolean {
return (
keyword.length <= 3 ||
(keyword === keyword.toUpperCase() && keyword !== keyword.toLowerCase())
);
}
@@ -4,6 +4,10 @@
margin: 0 auto;
}
:host ::ng-deep .mat-column-title {
min-width: 280px;
}
// ------------------------
// Shared tags & chips
// ------------------------
@@ -164,48 +168,6 @@
max-width: 200px;
}
// ------------------------
// Data table overrides (applied via ::ng-deep)
// ------------------------
::ng-deep {
.mat-mdc-header-cell {
color: var(--sg-text-muted);
font-size: 12px;
font-weight: 700;
}
.mat-mdc-row {
height: 86px;
}
.mat-mdc-cell {
color: var(--sg-text);
border-bottom-color: var(--sg-border);
font-size: 13px;
}
.table-wrap {
.mat-column-type,
.mat-column-year,
.mat-column-language,
.mat-column-citations,
.mat-mdc-header-cell {
text-align: center;
}
.mat-mdc-cell:not(:last-child),
.mat-mdc-header-cell:not(:last-child) {
border-right: 1px solid var(--sg-border);
}
.mat-column-institutions,
.mat-column-topics {
overflow: visible;
}
}
}
// ------------------------
// Responsive adjustments
// ------------------------
@@ -8,6 +8,31 @@
matSort
(matSortChange)="_handleSortChange($event)"
multiTemplateDataRows>
@if (detailTemplate()) {
<ng-container [matColumnDef]="expandColumnId">
<th mat-header-cell *matHeaderCellDef class="expand-cell"></th>
<td mat-cell *matCellDef="let row" class="expand-cell">
@if (isExpandable(row)) {
@let expanded = row === expandedElement();
<button
mat-icon-button
type="button"
[attr.aria-expanded]="expanded"
[matTooltip]="
expanded ? 'Details ausblenden' : 'Details anzeigen'
"
[attr.aria-label]="
expanded ? 'Details ausblenden' : 'Details anzeigen'
">
<mat-icon class="expand-icon" [class.is-expanded]="expanded">
expand_more
</mat-icon>
</button>
}
</td>
</ng-container>
}
@for (col of columns(); track col.id) {
<ng-container [matColumnDef]="col.id">
@if (col.headerTemplate) {
@@ -61,6 +86,8 @@
mat-row
*matRowDef="let row; columns: displayedColumns()"
class="element-row"
[class.is-expandable]="isExpandable(row)"
[class.is-expanded]="row === expandedElement()"
(click)="toggleRow(row)"></tr>
<tr
@@ -18,12 +18,32 @@ tr.detail-row {
height: 0 !important;
}
.detail-row .mat-mdc-cell {
padding: 0;
border-bottom: none;
}
.detail-row-wrapper {
overflow: hidden;
display: flex;
}
.element-row:hover {
.element-row.is-expandable:hover {
background: var(--sg-surface-soft);
cursor: pointer;
}
.expand-cell {
width: 1%;
white-space: nowrap;
padding-right: 0;
}
.expand-icon {
color: var(--sg-text-muted);
transition: transform 150ms ease-in-out;
&.is-expanded {
transform: rotate(180deg);
}
}
@@ -19,6 +19,9 @@ import {
SortDirection,
} from '@angular/material/sort';
import { MatTableDataSource, MatTableModule } from '@angular/material/table';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatTooltipModule } from '@angular/material/tooltip';
import { ActivatedRoute, Router } from '@angular/router';
import { SkTextDirective } from '../../../custom-directives/sk-text.directive';
export interface BaseColumn<T> {
@@ -43,7 +46,15 @@ export type GenericColumn<T> = AccessorColumn<T> | DisplayColumn<T>;
@Component({
selector: 'app-data-table',
standalone: true,
imports: [MatTableModule, NgTemplateOutlet, MatSortModule, SkTextDirective],
imports: [
MatTableModule,
NgTemplateOutlet,
MatSortModule,
MatButtonModule,
MatIconModule,
MatTooltipModule,
SkTextDirective,
],
templateUrl: './data-table.component.html',
styleUrl: './data-table.component.scss',
})
@@ -54,6 +65,7 @@ export class DataTableComponent<T> implements AfterViewInit {
detailTemplate = input<TemplateRef<any> | null>(null);
expandedElement = signal<T | null>(null);
canExpand = input<((row: T) => boolean) | null>(null);
maxHeight = input<string | null>(null);
containerOverflow = computed(() => (this.maxHeight() ? 'auto' : 'visible'));
@@ -78,7 +90,12 @@ export class DataTableComponent<T> implements AfterViewInit {
handleSortChange = output<Sort>();
displayedColumns = computed(() => this.columns().map((col) => col.id));
readonly expandColumnId = 'expand';
displayedColumns = computed(() => {
const ids = this.columns().map((col) => col.id);
return this.detailTemplate() ? [this.expandColumnId, ...ids] : ids;
});
dataSource = new MatTableDataSource<T>([]);
sort = viewChild.required(MatSort);
@@ -160,8 +177,13 @@ export class DataTableComponent<T> implements AfterViewInit {
}
}
isExpandable(row: T): boolean {
if (!this.detailTemplate()) return false;
return this.canExpand()?.(row) ?? true;
}
toggleRow(row: T): void {
if (!this.detailTemplate()) return;
if (!this.isExpandable(row)) return;
this.expandedElement.update((current) => (current === row ? null : row));
}
}
@@ -4,6 +4,16 @@
margin: 0 auto;
}
:host ::ng-deep {
.mat-column-title {
min-width: 280px;
}
.mat-column-names {
min-width: 200px;
}
}
// ------------------------
// Shared tags & chips
// ------------------------
@@ -154,48 +164,6 @@
}
}
// ------------------------
// Data table overrides (applied via ::ng-deep)
// ------------------------
::ng-deep {
.mat-mdc-header-cell {
color: var(--sg-text-muted);
font-size: 12px;
font-weight: 700;
}
.mat-mdc-row {
height: 86px;
}
.mat-mdc-cell {
color: var(--sg-text);
border-bottom-color: var(--sg-border);
font-size: 13px;
}
.table-wrap {
.mat-column-type,
.mat-column-year,
.mat-column-language,
.mat-column-citations,
.mat-mdc-header-cell {
text-align: center;
}
.mat-mdc-cell:not(:last-child),
.mat-mdc-header-cell:not(:last-child) {
border-right: 1px solid var(--sg-border);
}
.mat-column-institutions,
.mat-column-topics {
overflow: visible;
}
}
}
// ------------------------
// Responsive adjustments
// ------------------------
@@ -4,6 +4,16 @@
margin: 0 auto;
}
:host ::ng-deep {
.mat-column-title {
min-width: 280px;
}
.mat-column-authors {
min-width: 200px;
}
}
// ------------------------
// Shared tags & chips
// ------------------------
@@ -142,47 +152,7 @@
.classification-container {
max-width: 200px;
}
// ------------------------
// Data table overrides (applied via ::ng-deep)
// ------------------------
::ng-deep {
.mat-mdc-header-cell {
color: var(--sg-text-muted);
font-size: 12px;
font-weight: 700;
}
.mat-mdc-row {
height: 86px;
}
.mat-mdc-cell {
color: var(--sg-text);
border-bottom-color: var(--sg-border);
font-size: 13px;
}
.table-wrap {
.mat-column-type,
.mat-column-year,
.mat-column-language,
.mat-column-citations,
.mat-mdc-header-cell {
text-align: center;
}
.mat-mdc-cell:not(:last-child),
.mat-mdc-header-cell:not(:last-child) {
border-right: 1px solid var(--sg-border);
}
.mat-column-institutions,
.mat-column-topics {
overflow: visible;
}
}
}
.type-filter-btn {
display: inline-flex;
margin: 0;
@@ -1,6 +1,7 @@
<app-data-table
[columns]="columns()"
[data]="elements()"
[detailTemplate]="detailTemplate()"
queryParamSortKey="sort_by"
queryParamSortDirectionKey="sort_direction" />
@@ -16,7 +17,7 @@
[class.active]="isTypeActive(work.type)"
matTooltip="Nach Typ filtern"
matTooltipPosition="above"
(click)="toggleTypeFilter(work.type)">
(click)="$event.stopPropagation(); toggleTypeFilter(work.type)">
<app-chip [color]="typeColor(work.type)">
{{ work.type | workType }}
</app-chip>
@@ -34,7 +35,9 @@
[class.active]="isYearActive(work.publication_year)"
matTooltip="Nach Jahr filtern"
matTooltipPosition="above"
(click)="toggleYearFilter(work.publication_year)">
(click)="
$event.stopPropagation(); toggleYearFilter(work.publication_year)
">
{{ work.publication_year }}
</button>
} @else {
@@ -50,7 +53,7 @@
[class.active]="isLanguageActive(work.language)"
matTooltip="Nach Sprache filtern"
matTooltipPosition="above"
(click)="toggleLanguageFilter(work.language)">
(click)="$event.stopPropagation(); toggleLanguageFilter(work.language)">
{{ work.language | languageCode }}
</button>
} @else {
@@ -81,7 +84,8 @@
<div
class="institution-chips"
aria-label="Institutionen"
style="padding: 0.5rem 0">
style="padding: 0.5rem 0"
(click)="$event.stopPropagation()">
@for (institution of visibleInstitutions; track institution.id) {
<app-institution-chip
size="mini"
@@ -107,7 +111,11 @@
@let workAuthorsExpanded = isWorkAuthorsExpanded(work);
@let visibleAuthors =
workAuthorsExpanded ? workAuthors : workAuthors.slice(0, 3);
<div class="author-chips" aria-label="Autoren" style="padding: 0.5rem 0">
<div
class="author-chips"
aria-label="Autoren"
style="padding: 0.5rem 0"
(click)="$event.stopPropagation()">
@for (
author of visibleAuthors;
track author.id ?? 'name-' + author.display_name
@@ -133,7 +141,11 @@
<ng-template #topicsTmp let-work>
@let workTopics = work.topics ?? [];
<div class="topic-chips" aria-label="Themen" style="display: flex">
<div
class="topic-chips"
aria-label="Themen"
style="display: flex"
(click)="$event.stopPropagation()">
@for (topic of workTopics; track topic.id) {
<app-topic-chip-2
size="mini"
@@ -157,7 +169,8 @@
mat-icon-button
color="primary"
[routerLink]="['/publication', extractRawId(work.id)]"
matTooltip="Details anzeigen">
matTooltip="Details anzeigen"
(click)="$event.stopPropagation()">
<mat-icon>{{ OPEN_IN_NEW_ICON }}</mat-icon>
</a>
</ng-template>
@@ -331,20 +331,6 @@
font-size: 12px;
}
.table-wrap {
position: relative;
overflow-x: auto;
}
table {
width: 100%;
min-width: 1120px;
border-collapse: separate;
border-spacing: 0 10px;
box-shadow: none;
background: transparent;
}
.title {
display: inline-block;
max-width: 520px;
@@ -360,10 +346,6 @@ a.title:hover {
text-decoration: underline;
}
table.is-hidden {
display: none;
}
.table-status {
display: flex;
flex-direction: column;
@@ -444,42 +426,6 @@ table.is-hidden {
max-width: 280px;
}
::ng-deep .mat-mdc-header-cell {
color: var(--sg-text-muted);
font-size: 12px;
font-weight: 700;
}
::ng-deep .mat-mdc-row {
height: 86px;
}
::ng-deep .mat-mdc-cell {
color: var(--sg-text);
border-bottom-color: var(--sg-border);
font-size: 13px;
}
.table-wrap ::ng-deep {
.mat-column-type,
.mat-column-year,
.mat-column-language,
.mat-column-citations,
.mat-mdc-header-cell {
text-align: center;
}
.mat-mdc-cell:not(:last-child),
.mat-mdc-header-cell:not(:last-child) {
border-right: 1px solid var(--sg-border);
}
.mat-column-institutions,
.mat-column-topics {
overflow: visible;
}
}
mat-paginator {
background: transparent;
}
@@ -70,6 +70,8 @@ export class PublicationTableComponent {
rawOaAuthorId = input<string | undefined>(undefined);
rawOaInstitutionId = input<string | undefined>(undefined);
detailTemplate = input<TemplateRef<any> | null>(null);
shouldFetchClassifications = computed(() => {
return (
this.rawOaAuthorId() !== undefined ||
+27 -1
View File
@@ -130,6 +130,9 @@ body {
--sg-radius-lg: 18px;
--sg-blue-highlight: #3d7cff;
/* Backdrop for a keyword match that resolved to no topic. Topic-bound matches carry
their topic's colour instead. */
--sg-highlight-mark-bg: rgba(255, 214, 0, 0.35);
--sg-default-bold-weight: 900;
/* Additional Design Tokens for Dark Mode Support */
@@ -415,6 +418,29 @@ input {
font-size: 14px;
}
.data-table-container {
.mat-mdc-header-cell {
color: var(--sg-text-muted);
font-size: 12px;
font-weight: 700;
}
.mat-mdc-row {
height: 86px;
}
.mat-mdc-cell {
color: var(--sg-text);
border-bottom-color: var(--sg-border);
font-size: 13px;
}
.mat-column-institutions,
.mat-column-topics {
overflow: visible;
}
}
h1,
h2,
h3 {
@@ -484,7 +510,7 @@ html.dark-theme {
}
/* highlighted text */
.app-highlight-mark {
background-color: rgba(255, 214, 0, 0.35);
background-color: var(--sg-highlight-mark-bg);
border-radius: 2px;
padding: 0 1px;
}