diff --git a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts index 7a304133..8efe6b23 100644 --- a/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts +++ b/webapp/src/app/modules/keywords-search/search-results/news-results/news-results.component.ts @@ -30,7 +30,10 @@ 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, @@ -49,11 +52,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: [ @@ -254,9 +252,11 @@ export class KeywordsToNewsResultsComponent { 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), + ); } } @@ -272,51 +272,13 @@ 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 { 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 08aa1bd1..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,13 +1,15 @@ import { Injectable, computed, signal } from '@angular/core'; import { KeywordEntryWithTopic } from '../../../api/model/keywordEntryWithTopic'; import { Topic } from '../../../api'; -import { KeywordColor } from '../../../resolvers/utils/keyword-highlight'; -import { - topicHierarchyColor, - TopicHierarchyColorInput, -} from '../../../resolvers/utils/topic-colors'; +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; @@ -188,21 +190,39 @@ export class SearchResultsStateService { return null; } - /** The searched keywords with their topic colour, for the snippet marks. */ - readonly keywordColors = computed(() => - Array.from(this.keywordTopicMap(), ([keyword, topic]) => ({ - keyword, - color: topicHierarchyColor({ - id: topic.id, - name: topic.display_name, - field_id: topic.field?.id, - field_name: topic.field?.display_name, - domain_id: topic.domain?.id, - domain_name: topic.domain?.display_name, - }), - topicNames: topic.display_name ? [topic.display_name] : [], - })), - ); + /** + * 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 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 d9711a68..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 @@ -6,30 +6,41 @@ [showTopicFilter]="fuzzySearch()" /> -
- @if (snippetSegments().get(work.id); as segments) { - - Fundstelle im {{ 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. - - } -
+ +
+

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. + + } +
+
this.queryParamMap().get('fuzzy') === 'true'); - readonly snippetSegments = computed(() => { - const byWorkId = new Map(); - - const keywordColors = this.state.keywordColors(); + readonly snippetHighlights = computed(() => { + const byWorkId = new Map(); for (const work of this.elements()) { - if (!work.id || !work.snippet) { - continue; + if (work.id && work.snippet) { + byWorkId.set(work.id, this.state.snippetHighlight(work.snippet)); } - byWorkId.set(work.id, splitSnippet(work.snippet, keywordColors)); } return byWorkId; 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 d0879a84..00000000 --- a/webapp/src/app/resolvers/utils/keyword-highlight.ts +++ /dev/null @@ -1,214 +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 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 interface SnippetSegment { - text: string; - isSearchMatch: boolean; - match: KeywordColor | null; - groupHasMatch: boolean; -} - -export function splitSnippet( - snippet: string, - keywordColors: readonly KeywordColor[] = [], -): SnippetSegment[] { - const searchMatch = /([\s\S]*?)<\/em>/g; - const segments: SnippetSegment[] = []; - - let lastIndex = 0; - let match: RegExpExecArray | null; - - const pushPlain = (raw: string) => { - const text = decodeHtml(raw); - if (text) { - segments.push({ - text, - isSearchMatch: false, - match: null, - groupHasMatch: false, - }); - } - }; - - while ((match = searchMatch.exec(snippet)) !== null) { - pushPlain(snippet.slice(lastIndex, match.index)); - - const parts = splitByKeywords(decodeHtml(match[1]), keywordColors); - const groupHasMatch = parts.some((part) => part.match); - - for (const part of parts) { - segments.push({ - text: part.text, - isSearchMatch: true, - match: part.match, - groupHasMatch, - }); - } - - lastIndex = searchMatch.lastIndex; - } - - pushPlain(snippet.slice(lastIndex)); - - return segments; -} - -export function decodeHtml(text: string): string { - return text - .replace(/</g, '<') - .replace(/>/g, '>') - .replace(/"/g, '"') - .replace(/&#(?:39|x27);/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/snippet-text/snippet-text.component.html b/webapp/src/app/shared/ui/snippet-text/snippet-text.component.html deleted file mode 100644 index 6f39bd6d..00000000 --- a/webapp/src/app/shared/ui/snippet-text/snippet-text.component.html +++ /dev/null @@ -1,16 +0,0 @@ -

- @for (segment of rendered(); track $index) { - @if (segment.isSearchMatch) { - {{ segment.text }} - } @else { - {{ segment.text }} - } - } -

diff --git a/webapp/src/app/shared/ui/snippet-text/snippet-text.component.scss b/webapp/src/app/shared/ui/snippet-text/snippet-text.component.scss deleted file mode 100644 index 5a25d88c..00000000 --- a/webapp/src/app/shared/ui/snippet-text/snippet-text.component.scss +++ /dev/null @@ -1,28 +0,0 @@ -.snippet { - margin: 0; - font-size: 12.5px; - line-height: 1.6; - color: var(--sg-text-secondary); - overflow-wrap: anywhere; -} - -.snippet-mark { - background: var(--sg-highlight-mark-bg); - border-radius: 2px; - padding: 0 1px; - - &.has-topic { - background: transparent; - padding: 0; - color: var(--t); - font-weight: 700; - text-decoration: underline; - text-decoration-color: var(--t); - text-decoration-thickness: 2px; - text-underline-offset: 2px; - } -} - -:host(.has-tooltips) .snippet-mark { - cursor: help; -} diff --git a/webapp/src/app/shared/ui/snippet-text/snippet-text.component.ts b/webapp/src/app/shared/ui/snippet-text/snippet-text.component.ts deleted file mode 100644 index a9e1e3a3..00000000 --- a/webapp/src/app/shared/ui/snippet-text/snippet-text.component.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { Component, computed, input } from '@angular/core'; -import { MatTooltipModule } from '@angular/material/tooltip'; - -import { - keywordTooltip, - SnippetSegment, -} from '../../../resolvers/utils/keyword-highlight'; - -@Component({ - host: { - '[class.has-tooltips]': 'showTooltips()', - }, - selector: 'app-snippet-text', - imports: [MatTooltipModule], - templateUrl: './snippet-text.component.html', - styleUrl: './snippet-text.component.scss', -}) -export class SnippetTextComponent { - segments = input.required(); - - showTooltips = input(false); - - protected readonly rendered = computed(() => - this.segments().map((segment) => ({ - text: segment.text, - isSearchMatch: segment.isSearchMatch, - color: segment.match?.color ?? null, - tooltip: this.tooltipFor(segment), - })), - ); - - private tooltipFor(segment: SnippetSegment): string { - if (!this.showTooltips() || !segment.isSearchMatch) { - return ''; - } - - if (segment.match) { - return keywordTooltip(segment.match.keyword, segment.match.topicNames); - } - - return segment.groupHasMatch ? '' : keywordTooltip(segment.text, []); - } -}