diff --git a/service/src/main/inse/models/openalex/work.py b/service/src/main/inse/models/openalex/work.py index 31934220..3ad6f785 100644 --- a/service/src/main/inse/models/openalex/work.py +++ b/service/src/main/inse/models/openalex/work.py @@ -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 ``. 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 diff --git a/service/src/main/inse/news/logic.py b/service/src/main/inse/news/logic.py index 2cc1b6fb..453323bb 100644 --- a/service/src/main/inse/news/logic.py +++ b/service/src/main/inse/news/logic.py @@ -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"(.*?)", 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": [""], - "post_tags": [""], + **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"{window[start:end]}") - 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") diff --git a/service/src/main/inse/news/service.py b/service/src/main/inse/news/service.py index eeeeb564..bfc6d105 100644 --- a/service/src/main/inse/news/service.py +++ b/service/src/main/inse/news/service.py @@ -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, ) diff --git a/service/src/main/inse/snippets.py b/service/src/main/inse/snippets.py new file mode 100644 index 00000000..0d8d662a --- /dev/null +++ b/service/src/main/inse/snippets.py @@ -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"(.*?)", re.DOTALL) + +_SENTENCE_BREAK = re.compile(r"(?"], "post_tags": [""]} + + +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"{window[start:end]}") + cursor = end + marked.append(window[cursor:]) + + return "".join(marked) diff --git a/service/src/main/inse/works/v2/service.py b/service/src/main/inse/works/v2/service.py index 20e139a8..8309edf9 100644 --- a/service/src/main/inse/works/v2/service.py +++ b/service/src/main/inse/works/v2/service.py @@ -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, diff --git a/webapp/src/app/api/api/news.service.ts b/webapp/src/app/api/api/news.service.ts index 6d7a4c53..b789f410 100644 --- a/webapp/src/app/api/api/news.service.ts +++ b/webapp/src/app/api/api/news.service.ts @@ -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: \'desc\' (newest first) or \'asc\' (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 { sortOrder, 'sortOrder', ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + 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: \'desc\' (newest first) or \'asc\' (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 { sortOrder, 'sortOrder', ); + localVarQueryParameters = this.addToHttpParams( + localVarQueryParameters, + title, + 'title', + ); let localVarHeaders = this.defaultHeaders; diff --git a/webapp/src/app/api/model/work.ts b/webapp/src/app/api/model/work.ts index 07d94a1c..97c4d648 100644 --- a/webapp/src/app/api/model/work.ts +++ b/webapp/src/app/api/model/work.ts @@ -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 | null; - best_oa_location?: Location | null; - open_access?: OpenAccess | null; - authorships?: Array | null; - ids?: WorkIds | null; - biblio?: WorkBiblio | null; - abstract_inverted_index?: object | null; - referenced_works?: Array | null; - referenced_works_count?: number | null; - related_works?: Array | null; - topics?: Array | null; - primary_topic?: WorkTopic | null; - keywords?: Array | null; - funders?: Array | null; - awards?: Array | null; - fwci?: Fwci | null; - citation_normalized_percentile?: WorkCitationNormalizedPercentile | null; - cited_by_percentile_year?: WorkCitedByPercentileYear | null; - counts_by_year?: Array | null; - sustainable_development_goals?: Array | null; - mesh?: Array | null; - indexed_in?: Array | 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 | null; + best_oa_location?: Location | null; + open_access?: OpenAccess | null; + authorships?: Array | null; + ids?: WorkIds | null; + biblio?: WorkBiblio | null; + abstract_inverted_index?: object | null; + referenced_works?: Array | null; + referenced_works_count?: number | null; + related_works?: Array | null; + topics?: Array | null; + primary_topic?: WorkTopic | null; + keywords?: Array | null; + funders?: Array | null; + awards?: Array | null; + fwci?: Fwci | null; + citation_normalized_percentile?: WorkCitationNormalizedPercentile | null; + cited_by_percentile_year?: WorkCitedByPercentileYear | null; + counts_by_year?: Array | null; + sustainable_development_goals?: Array | null; + mesh?: Array | null; + indexed_in?: Array | 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 | null; } - diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html index 7c21c0a7..d1cb0a6e 100644 --- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.html @@ -1,74 +1,60 @@
- - + - - +
+ + - - + + - @if (hasActiveFilters()) { - - } + + + + @if (hasActiveFilters()) { + + } +
- - @if (article.snippet) { - @let expanded = isSnippetExpanded(article); - - } - -
- + - +
@@ -201,12 +187,11 @@ }
} @else { -
- -
+ 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>('expandTmp'); titleTmp = viewChild.required>('titleTmp'); dateTmp = viewChild.required>('dateTmp'); relevanceTmp = viewChild.required>('relevanceTmp'); topicsTmp = viewChild.required>('topicsTmp'); actionsTmp = viewChild.required>('actionsTmp'); - private readonly dataTable = viewChild(DataTableComponent); - readonly columns = computed[]>(() => [ - { - 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(); 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(/([\s\S]*?)<\/em>/g)].map((match) => - match[1].trim(), - ); - } - - private toHighlightTerms(terms: string[]): HighlightTerm[] { - const seen = new Set(); - 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', diff --git a/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts b/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts index 802abafb..e4ba48c8 100644 --- a/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts +++ b/webapp/src/app/modules/keywords-search/search-results/search-results-state.service.ts @@ -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 + * that catches the inflected forms the analyzer found. + */ + public snippetHighlight(snippet: string): SnippetHighlight { + const marked = [...snippet.matchAll(/([\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(); + 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. diff --git a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html index 7f6d987c..447b0fae 100644 --- a/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html +++ b/webapp/src/app/modules/keywords-search/search-results/works-results/works-results.component.html @@ -5,11 +5,50 @@ [selectedAuthorsPage]="selectedAuthorsPage()" [showTopicFilter]="fuzzySearch()" /> + + +
+

Fundstelle in der Publikation

+
+ + + @if (snippetHighlights().get(work.id); as snippet) { +
+

{{ snippetSourceLabel(work) }}

+ +
+ } @else if (work.matched_via?.length) { +
+

Kein Treffer im 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) { + {{ name }}{{ last ? '' : ', ' }} + } + gefunden. +

+
+ } @else { + + Für diese Publikation liegt keine Fundstelle vor. + + } +
+
+
+ + [topicFilterEnabled]="fuzzySearch()" + [detailTemplate]="fuzzySearch() ? null : snippetTmp" /> this.queryParamMap().get('fuzzy') === 'true'); + readonly snippetHighlights = computed(() => { + const byWorkId = new Map(); + + 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 { diff --git a/webapp/src/app/resolvers/keywords-news-page.resolver.ts b/webapp/src/app/resolvers/keywords-news-page.resolver.ts index a347122c..c8515505 100644 --- a/webapp/src/app/resolvers/keywords-news-page.resolver.ts +++ b/webapp/src/app/resolvers/keywords-news-page.resolver.ts @@ -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 = (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 = (route) => { yearFrom, yearTo, sortOrder, + title, ); }; diff --git a/webapp/src/app/resolvers/utils/keyword-highlight.ts b/webapp/src/app/resolvers/utils/keyword-highlight.ts deleted file mode 100644 index b22ec493..00000000 --- a/webapp/src/app/resolvers/utils/keyword-highlight.ts +++ /dev/null @@ -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>(); - - 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(); - 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( - `(? { - 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 ( - `` + - `${escapeHtml(value)}` - ); - }) - .join(''); -} - -export function escapeHtml(text: string): string { - return text - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -} - -function escapeRegex(text: string): string { - return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); -} - -function isAcronymLike(keyword: string): boolean { - return ( - keyword.length <= 3 || - (keyword === keyword.toUpperCase() && keyword !== keyword.toLowerCase()) - ); -} diff --git a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.scss b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.scss index 57b73879..3da75c51 100644 --- a/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.scss +++ b/webapp/src/app/shared/ui/bund-project-table/bund-project-table.component.scss @@ -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 // ------------------------ diff --git a/webapp/src/app/shared/ui/data-table/data-table.component.html b/webapp/src/app/shared/ui/data-table/data-table.component.html index 85b8df3f..498fb20b 100644 --- a/webapp/src/app/shared/ui/data-table/data-table.component.html +++ b/webapp/src/app/shared/ui/data-table/data-table.component.html @@ -8,6 +8,31 @@ matSort (matSortChange)="_handleSortChange($event)" multiTemplateDataRows> + @if (detailTemplate()) { + + + + @if (isExpandable(row)) { + @let expanded = row === expandedElement(); + + } + + + } + @for (col of columns(); track 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)"> { @@ -43,7 +46,15 @@ export type GenericColumn = AccessorColumn | DisplayColumn; @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 implements AfterViewInit { detailTemplate = input | null>(null); expandedElement = signal(null); + canExpand = input<((row: T) => boolean) | null>(null); maxHeight = input(null); containerOverflow = computed(() => (this.maxHeight() ? 'auto' : 'visible')); @@ -78,7 +90,12 @@ export class DataTableComponent implements AfterViewInit { handleSortChange = output(); - 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([]); sort = viewChild.required(MatSort); @@ -160,8 +177,13 @@ export class DataTableComponent 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)); } } diff --git a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.scss b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.scss index d4642344..c56c94f4 100644 --- a/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.scss +++ b/webapp/src/app/shared/ui/dfg-project-table/dfg-project-table.component.scss @@ -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 // ------------------------ diff --git a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.scss b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.scss index 7b182c1d..a79e6da8 100644 --- a/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.scss +++ b/webapp/src/app/shared/ui/eu-project-table/eu-project-table.component.scss @@ -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; diff --git a/webapp/src/app/shared/ui/publication-table/publication-table.component.html b/webapp/src/app/shared/ui/publication-table/publication-table.component.html index b79b690e..c9014f46 100644 --- a/webapp/src/app/shared/ui/publication-table/publication-table.component.html +++ b/webapp/src/app/shared/ui/publication-table/publication-table.component.html @@ -1,6 +1,7 @@ @@ -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)"> {{ work.type | workType }} @@ -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 }} } @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 }} } @else { @@ -81,7 +84,8 @@
+ style="padding: 0.5rem 0" + (click)="$event.stopPropagation()"> @for (institution of visibleInstitutions; track institution.id) { +
@for ( author of visibleAuthors; track author.id ?? 'name-' + author.display_name @@ -133,7 +141,11 @@ @let workTopics = work.topics ?? []; -
+
@for (topic of workTopics; track topic.id) { + matTooltip="Details anzeigen" + (click)="$event.stopPropagation()"> {{ OPEN_IN_NEW_ICON }} diff --git a/webapp/src/app/shared/ui/publication-table/publication-table.component.scss b/webapp/src/app/shared/ui/publication-table/publication-table.component.scss index 6df1e4e9..6fda9380 100644 --- a/webapp/src/app/shared/ui/publication-table/publication-table.component.scss +++ b/webapp/src/app/shared/ui/publication-table/publication-table.component.scss @@ -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; } diff --git a/webapp/src/app/shared/ui/publication-table/publication-table.component.ts b/webapp/src/app/shared/ui/publication-table/publication-table.component.ts index 4977dea8..98300190 100644 --- a/webapp/src/app/shared/ui/publication-table/publication-table.component.ts +++ b/webapp/src/app/shared/ui/publication-table/publication-table.component.ts @@ -70,6 +70,8 @@ export class PublicationTableComponent { rawOaAuthorId = input(undefined); rawOaInstitutionId = input(undefined); + detailTemplate = input | null>(null); + shouldFetchClassifications = computed(() => { return ( this.rawOaAuthorId() !== undefined || diff --git a/webapp/src/styles.scss b/webapp/src/styles.scss index 86fde541..1885b80f 100644 --- a/webapp/src/styles.scss +++ b/webapp/src/styles.scss @@ -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; }