feat(works-keyword-search): match keyword highlighting approach

This commit is contained in:
2026-08-24 21:49:05 +02:00
parent 68f1cae4d9
commit 2878667727
9 changed files with 96 additions and 444 deletions
@@ -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<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),
);
}
}
@@ -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(/<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 {
@@ -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<KeywordColor[]>(() =>
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
* <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
@@ -6,30 +6,41 @@
[showTopicFilter]="fuzzySearch()" />
<ng-template #snippetTmp let-work>
<div class="snippet-detail">
@if (snippetSegments().get(work.id); as segments) {
<span class="snippet-label">
Fundstelle im {{ snippetSourceLabel(work) }}
</span>
<app-snippet-text [segments]="segments" />
} @else if (work.matched_via?.length) {
<span class="snippet-label">Kein Treffer im Text</span>
<p class="snippet">
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>
} @else {
<span class="empty-text">
Für diese Publikation liegt keine Fundstelle vor.
</span>
}
</div>
<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
@@ -83,44 +83,6 @@
gap: 0.5rem;
}
/* ============================================================
EXPANDED DETAIL ROW
============================================================ */
:host ::ng-deep {
.detail-row .mat-mdc-cell {
padding: 0;
}
.element-row.is-expanded .mat-mdc-cell {
border-bottom-color: transparent;
}
}
.snippet-detail {
display: flex;
flex-direction: column;
gap: 0.375rem;
padding: 0.875rem 1rem 1rem 4rem;
background: var(--sg-surface-soft);
}
.snippet-label {
color: var(--sg-text-muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.02em;
text-transform: uppercase;
}
.snippet {
margin: 0;
font-size: 12.5px;
line-height: 1.6;
color: var(--sg-text-secondary);
overflow-wrap: anywhere;
}
.matched-topic {
color: var(--sg-text);
font-weight: 600;
@@ -17,12 +17,12 @@ import {
TopicPageV2,
Work,
} from '../../../../api';
import { SearchResultsStateService } from '../search-results-state.service';
import {
SnippetSegment,
splitSnippet,
} from '../../../../resolvers/utils/keyword-highlight';
import { SnippetTextComponent } from '../../../../shared/ui/snippet-text/snippet-text.component';
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',
@@ -33,7 +33,8 @@ import { SnippetTextComponent } from '../../../../shared/ui/snippet-text/snippet
PublicationTableComponent,
PublicationFilterComponent,
QueryParamPaginatorComponent,
SnippetTextComponent,
HighlightedTextComponent,
TableDetailRowComponent,
],
templateUrl: './works-results.component.html',
styleUrl: './works-results.component.scss',
@@ -75,16 +76,13 @@ export class KeywordsToWorksResultsComponent implements OnInit {
fuzzySearch = computed(() => this.queryParamMap().get('fuzzy') === 'true');
readonly snippetSegments = computed(() => {
const byWorkId = new Map<string, SnippetSegment[]>();
const keywordColors = this.state.keywordColors();
readonly snippetHighlights = computed(() => {
const byWorkId = new Map<string, SnippetHighlight>();
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;
@@ -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<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 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 interface SnippetSegment {
text: string;
isSearchMatch: boolean;
match: KeywordColor | null;
groupHasMatch: boolean;
}
export function splitSnippet(
snippet: string,
keywordColors: readonly KeywordColor[] = [],
): SnippetSegment[] {
const searchMatch = /<em>([\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(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#(?:39|x27);/g, "'")
.replace(/&amp;/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())
);
}
@@ -1,16 +0,0 @@
<p class="snippet">
@for (segment of rendered(); track $index) {
@if (segment.isSearchMatch) {
<mark
class="snippet-mark"
[class.has-topic]="!!segment.color"
[style.--t]="segment.color"
[matTooltip]="segment.tooltip"
matTooltipPosition="above"
>{{ segment.text }}</mark
>
} @else {
<span>{{ segment.text }}</span>
}
}
</p>
@@ -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;
}
@@ -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<SnippetSegment[]>();
showTooltips = input<boolean>(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, []);
}
}