Files
smartguide/webapp/src/app/modules/keywords-search/keywords-search.component.ts
T
taguesokoudjou 75c0638df5
LocationBasedServices/smartguide/pipeline/pr-dev There was a failure building this commit
resolve keywords-search patent UI conflicts
2026-07-15 14:20:27 +02:00

1229 lines
40 KiB
TypeScript

import { Component, computed, signal, inject, effect } from '@angular/core';
import { BreakpointObserver } from '@angular/cdk/layout';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatDividerModule } from '@angular/material/divider';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatTabsModule } from '@angular/material/tabs';
import { ActivatedRoute, Router } from '@angular/router';
import { debounceTime, distinctUntilChanged } from 'rxjs';
import { KeywordsRequest } from '../../api/model/keywordsRequest';
import { MatExpansionModule } from '@angular/material/expansion';
import { ExtractedKeywords } from '../../api/model/extractedKeywords';
import { ExtractedKeywordsResponse } from '../../api/model/extractedKeywordsResponse';
import { DestroyRef } from '@angular/core';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { KeywordWebSocketService, WsEvent } from './keywords-websocket.service';
import { TopicsService } from '../../api/api/topics.service';
import { KeywordsTopicsRequest } from '../../api/model/keywordsTopicsRequest';
import { KeywordEntryWithTopic } from '../../api/model/keywordEntryWithTopic';
import { TopicAutocompleteComponent } from '../../shared/ui/topic-autocomplete/topic-autocomplete.component';
import { LoadingComponent } from '../../shared/ui/loading/loading.component';
import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.component';
import { TopicLegendComponent } from '../../shared/ui/topic-legend/topic-legend.component';
import { Topic } from '../../api/model/topic';
import { NgTemplateOutlet } from '@angular/common';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { map } from 'rxjs/operators';
import { toSignal } from '@angular/core/rxjs-interop';
import { MatSliderModule } from '@angular/material/slider';
import { FileUpload } from '../../api/model/fileUpload';
import { MatSnackBar } from '@angular/material/snack-bar';
import {
FileUploadComponent,
FileUploadItem,
} from '../../shared/ui/file-upload/file-upload.component';
import {
MatButtonToggleModule,
MatButtonToggleGroup,
} from '@angular/material/button-toggle';
import {
topicHierarchyColor,
TopicHierarchyColorInput,
} from '../../resolvers/utils/topic-colors';
import {
buildTopicLegendGroups,
TopicLegendGroup,
TopicLegendTopic,
} from '../../resolvers/utils/topic-legend';
import { MatTooltipModule } from '@angular/material/tooltip';
import { A11yModule } from '@angular/cdk/a11y';
import { DomSanitizer } from '@angular/platform-browser';
import { SearchResultsPayload } from './search-results/search-results-state.service';
import { clearPatentsCache } from './patent-search.utils';
type InputMode = 'url' | 'text' | 'file';
type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual';
type KeywordView = 'llm' | 'topic';
type KeywordPatentLevel = 'broad' | 'coarse' | 'fine' | 'custom';
@Component({
selector: 'app-keywords-search',
imports: [
ReactiveFormsModule,
MatTabsModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
MatIconModule,
MatDividerModule,
MatCardModule,
MatExpansionModule,
MatProgressBarModule,
TopicAutocompleteComponent,
TopicChipComponent,
TopicLegendComponent,
MatButtonToggleModule,
MatButtonToggleGroup,
MatTooltipModule,
A11yModule,
NgTemplateOutlet,
LoadingComponent,
MatSlideToggleModule,
MatSliderModule,
FileUploadComponent,
],
templateUrl: './keywords-search.component.html',
styleUrl: './keywords-search.component.scss',
})
export class KeywordsSearchComponent {
private readonly formBuilder = inject(FormBuilder);
private readonly sanitizer = inject(DomSanitizer);
private readonly route = inject(ActivatedRoute);
private readonly router = inject(Router);
private readonly _snackBar = inject(MatSnackBar);
private readonly destroyRef = inject(DestroyRef);
private readonly websocketService = inject(KeywordWebSocketService);
private readonly topicsService = inject(TopicsService);
private readonly breakpointObserver = inject(BreakpointObserver);
readonly form = this.formBuilder.nonNullable.group({
selectedInputType: 'url' as InputMode,
urlInput: '',
textInput: '',
fileInput: '',
});
private readonly SESSION_KEY = 'keywords-search-source';
private readonly SEARCH_RESULTS_HANDOFF_KEY = 'search-results-handoff';
isMobile = toSignal(
this.breakpointObserver
.observe('(max-width: 768px)')
.pipe(map((r) => r.matches)),
{ initialValue: false },
);
// Category signals - the full backend entries are the source of truth;
// the *Keywords() computed signals below just project the label out of them.
private readonly broadKeywordEntries = signal<KeywordEntryWithTopic[]>([]);
private readonly coarseKeywordEntries = signal<KeywordEntryWithTopic[]>([]);
private readonly fineKeywordEntries = signal<KeywordEntryWithTopic[]>([]);
private readonly manualKeywordEntries = signal<KeywordEntryWithTopic[]>([]);
readonly broadKeywords = computed(() => this.broadKeywordEntries());
readonly coarseKeywords = computed(() => this.coarseKeywordEntries());
readonly fineKeywords = computed(() => this.fineKeywordEntries());
readonly manualKeywords = computed(() => this.manualKeywordEntries());
readonly selectedKeywords = signal<string[]>([]);
readonly isExtracting = signal(false);
readonly loadingNewKeyword = signal(false);
readonly extractionSource = signal<InputMode | null>(null);
readonly topicMappingSearch = signal<boolean>(false);
readonly showVisualization = signal<boolean>(false);
readonly uploadedFiles = signal<FileUploadItem[]>([]);
readonly keywordsExist = computed(
() =>
this.broadKeywords().length > 0 ||
this.coarseKeywords().length > 0 ||
this.fineKeywords().length > 0 ||
this.manualKeywords().length > 0,
);
readonly sourceContent = signal<string>('');
readonly sourceUrl = signal<string | null>(null);
readonly highlightedSourceContent = computed(() => {
const content = this.sourceContent();
if (!content) return '';
const selectedKeywords = this.selectedKeywords();
if (selectedKeywords.length === 0) return content;
let highlightedContent = content;
const normalizeText = (text: string): string => {
return text
.trim()
.toLowerCase()
.replace(/[\u2010-\u2015\u2026—–]/g, '-')
.replace(/[\u2018\u2019\u201b\u201c\u201d\u201f]/g, "'")
.replace(/[\s\n\r\t]+/g, ' ')
.replace(/[^a-zA-Z0-9\s\-]/g, '');
};
// Normalize keyword for matching
const normalizeKeyword = (keyword: string): string => {
return keyword
.trim()
.toLowerCase()
.replace(/[\s\-]+/g, '')
.replace(/[^a-zA-Z0-9]/g, '');
};
for (const keyword of selectedKeywords) {
const normalizedKeyword = normalizeKeyword(keyword);
const entry = this.allKeywordEntries().find((e) => {
const label = this.getKeywordLabel(e);
return normalizeKeyword(label) === normalizedKeyword;
});
if (!entry) continue;
const topic = this.getTopic(entry);
if (!topic) continue;
const color = this.getTopicColor(topic);
const escapedKeyword = keyword
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#039;');
const escapedRegexKeyword = keyword
.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
.replace(/\s+/g, '\\s*');
const regex = new RegExp(escapedRegexKeyword, 'gi');
const replacement = `<span style="text-decoration: underline; background-color: color-mix(in srgb, ${color} 27%, #ffffff); font-weight: bold;" title="Keyword: ${escapedKeyword}">${escapedKeyword}</span>`;
highlightedContent = highlightedContent.replace(regex, replacement);
}
return this.sanitizer.bypassSecurityTrustHtml(highlightedContent);
});
private isRestoringState = false;
// Set right before we call router.navigate() ourselves (from
// updateQueryParams()). Lets the queryParamMap subscription below tell
// "we just wrote this URL" apart from "someone else navigated here" (a
// fresh mount, a deep link such as ?selected=x&manual=y from another
// page, a manual URL edit, browser back/forward). Only the latter should
// trigger a full restoreStateFromQueryParams().
private isOwnNavigation = false;
readonly progress = signal(0);
readonly statusMessage = signal('');
readonly errorMessage = signal('');
readonly keywordView = signal<KeywordView>('llm');
readonly subfieldLegendVisible = signal(true);
readonly subfieldLegendExpanded = signal(false);
get topicLegendGroups(): TopicLegendGroup[] {
const topics = [
...this.broadKeywordEntries(),
...this.coarseKeywordEntries(),
...this.fineKeywordEntries(),
...this.manualKeywordEntries(),
]
.map((entry) => entry.topic_mapping?.topic)
.filter((topic): topic is Topic => Boolean(topic))
.map((topic) => this.toTopicLegendTopic(topic));
return buildTopicLegendGroups(topics);
}
constructor() {
this.route.queryParamMap.pipe(takeUntilDestroyed()).subscribe(() => {
if (this.isOwnNavigation) {
this.isOwnNavigation = false;
return;
}
this.restoreStateFromQueryParams();
});
this.form.controls.selectedInputType.valueChanges
.pipe(distinctUntilChanged(), takeUntilDestroyed())
.subscribe(() => this.updateQueryParams());
this.form.controls.urlInput.valueChanges
.pipe(debounceTime(400), distinctUntilChanged(), takeUntilDestroyed())
.subscribe(() => this.updateQueryParams());
this.form.controls.textInput.valueChanges
.pipe(debounceTime(400), distinctUntilChanged(), takeUntilDestroyed())
.subscribe(() => this.updateQueryParams());
this.websocketService
.getMessages()
.subscribe((event: WsEvent) => this.handleWsEvent(event));
effect(() => {
const message = this.errorMessage();
if (message) {
this._snackBar.open(message, 'Schließen', {
duration: 5000,
});
}
});
// this.destroyRef.onDestroy(() => {
// this.websocketService.close();
// const isReload = this.router.lastSuccessfulNavigation === null;
// if (!isReload) {
// this.clearStateFromSession();
// }
// });
}
// --- Websocket event handling ---------------------------------------
private handleWsEvent(event: WsEvent): void {
switch (event.type) {
case 'status':
this.handleStatusEvent(event);
break;
case 'keywords':
if (event.keywords) this.addExtractedKeyword(event.keywords);
break;
case 'completed':
this.handleCompletedEvent(event);
break;
case 'error':
this.handleErrorEvent(event);
break;
}
}
private handleStatusEvent(event: WsEvent): void {
this.statusMessage.set(event.message || '');
this.progress.set(this.getProgressForStep(event.step || ''));
}
private handleCompletedEvent(event: WsEvent): void {
this.processExtractedKeywords(event.result as ExtractedKeywordsResponse);
this.progress.set(100);
this.statusMessage.set('Fertig!');
this.websocketService.close();
this.isExtracting.set(false);
if (!this.keywordsExist()) {
this.errorMessage.set('Keine Keywords extrahiert');
}
}
private handleErrorEvent(event: WsEvent): void {
this.progress.set(0);
this.errorMessage.set(event.message || 'Unbekannter Fehler');
//this.statusMessage.set('Fehler: ' + event.message);
this.broadKeywordEntries.set([]);
this.coarseKeywordEntries.set([]);
this.fineKeywordEntries.set([]);
clearPatentsCache();
this.websocketService.close();
this.isExtracting.set(false);
this.loadingNewKeyword.set(false);
// Keep manual, but remove selected that are not in manual
this.selectedKeywords.set(
this.selectedKeywords().filter((k) =>
this.getKeywordLabels(this.manualKeywords()).includes(k),
),
);
this.updateQueryParams();
}
// --- Topic enrichment --------------------------------------------------
enrichManualKeywordsWithTopics(keywords: string[]): void {
if (keywords.length === 0) return;
const currentEntries = this.manualKeywordEntries();
const entriesByKeyword = new Map(
currentEntries.map((e) => [
this.normalizeKeyword(e.llm_keyword.keyword),
e,
]),
);
const toEnrich = keywords.filter((k) => {
const entry = entriesByKeyword.get(this.normalizeKeyword(k));
return entry && !entry.topic_mapping?.topic;
});
if (toEnrich.length === 0) return;
const request: KeywordsTopicsRequest = { keywords: toEnrich };
this.topicsService.vectorSearchTopicsBatch(request).subscribe({
next: ({ results }) => {
const current = this.manualKeywordEntries();
const resultMap = new Map(
results.map((r) => [this.normalizeKeyword(r.keyword), r]),
);
const updated = current.map((entry) => {
const normalized = this.normalizeKeyword(entry.llm_keyword.keyword);
const enriched = resultMap.get(normalized);
if (enriched && !entry.topic_mapping?.topic) {
return {
...entry,
topic_mapping: {
keyword: entry.llm_keyword.keyword,
topic: enriched.topic,
},
};
}
return entry;
});
this.manualKeywordEntries.set(updated);
this.updateQueryParams();
},
error: (error) => {
console.error('Error enriching topics:', error);
},
});
}
// --- Tabs ---------------------------------------------------------------
selectedTabIndex(): number {
if (this.form.controls.selectedInputType.value === 'url') return 0;
if (this.form.controls.selectedInputType.value === 'text') return 1;
return 2;
}
onTabChange(index: number): void {
let nextMode: InputMode;
if (index === 0) {
nextMode = 'url';
} else if (index === 1) {
nextMode = 'text';
} else {
nextMode = 'file';
}
this.form.controls.selectedInputType.setValue(nextMode);
}
// fileupload
onFilesSelected(files: FileUploadItem[]): void {
this.uploadedFiles.set(files);
}
// Helper: Send files to WebSocket for server-side extraction
private sendFilesToWebSocket(files: FileUpload[]) {
const keywordsRequest: KeywordsRequest = {
query: '',
files,
mode: 'files',
limit: undefined,
};
this.statusMessage.set('Files uploaded. Extracting keywords...');
this.websocketService
.sendRequest(keywordsRequest)
.then(() => {
this.statusMessage.set('Extracting keywords...');
})
.catch((err) => {
console.error('WebSocket error: OPA', err);
this.errorMessage.set('Failed to send content');
this.isExtracting.set(false);
});
}
// --- Keyword selection & manual entry ------------------------------------
private keywordExists(keyword: string): boolean {
const normalized = this.normalizeKeyword(keyword);
return [
...this.getKeywordLabels(this.broadKeywords()),
...this.getKeywordLabels(this.coarseKeywords()),
...this.getKeywordLabels(this.fineKeywords()),
...this.getKeywordLabels(this.manualKeywords()),
].some((k) => this.normalizeKeyword(k) === normalized);
}
addKeywordFromInput(keyword: Topic): void {
const normalizedKeyword = keyword.display_name?.trim() ?? '';
if (!normalizedKeyword) return;
if (this.keywordExists(normalizedKeyword)) {
this.errorMessage.set(`"${normalizedKeyword}" ist bereits vorhanden.`);
return;
}
this.loadingNewKeyword.set(true);
if (keyword.id === null) {
console.log('Adding new keyword without topic:', normalizedKeyword);
this.topicsService.vectorSearchTopics(normalizedKeyword).subscribe({
next: ({ results }) => {
const newEntry: KeywordEntryWithTopic = {
llm_keyword: { keyword: normalizedKeyword, relevance_score: 1 },
topic_mapping: { keyword: normalizedKeyword, topic: results?.[0] },
};
this.manualKeywordEntries.set(
this.uniqueKeywordEntries([
...this.manualKeywordEntries(),
newEntry,
]),
);
this.selectedKeywords.set([
...this.selectedKeywords(),
normalizedKeyword,
]);
this.loadingNewKeyword.set(false);
this.updateQueryParams(); // now fires after state is actually updated
},
error: (err) => {
console.error('vectorSearchTopics failed', err);
this.loadingNewKeyword.set(false);
this.errorMessage.set(
`Fehler beim Hinzufügen von "${normalizedKeyword}".`,
);
},
});
} else {
console.log('topic was already there', keyword);
const newEntry: KeywordEntryWithTopic = {
llm_keyword: { keyword: normalizedKeyword, relevance_score: 1 },
topic_mapping: { keyword: normalizedKeyword, topic: keyword },
};
this.manualKeywordEntries.set(
this.uniqueKeywordEntries([...this.manualKeywordEntries(), newEntry]),
);
this.selectedKeywords.set([
...this.selectedKeywords(),
normalizedKeyword,
]);
this.loadingNewKeyword.set(false);
this.updateQueryParams();
}
}
removeSelectedKeyword(keyword: string): void {
this.selectedKeywords.set(
this.selectedKeywords().filter((v) => v !== keyword),
);
this.updateQueryParams();
}
toggleKeywordSelection(keyword: KeywordEntryWithTopic): void {
const label = this.getKeywordLabel(keyword);
const nextSelection = this.selectedKeywords().includes(label)
? this.selectedKeywords().filter((value) => value !== label)
: [...this.selectedKeywords(), label];
this.selectedKeywords.set(this.uniqueKeywords(nextSelection));
this.updateQueryParams();
}
isKeywordSelected(keyword: KeywordEntryWithTopic): boolean {
const normalized = this.normalizeKeyword(this.getKeywordLabel(keyword));
return this.selectedKeywords().some(
(value) => this.normalizeKeyword(value) === normalized,
);
}
removeManualKeyword(keyword: KeywordEntryWithTopic): void {
const label = this.getKeywordLabel(keyword);
this.manualKeywordEntries.set(
this.filterKeywordEntries(this.manualKeywordEntries(), label),
);
this.selectedKeywords.set(
this.selectedKeywords().filter((value) => value !== label),
);
this.updateQueryParams();
}
allKeywordEntries = computed(() => [
...this.manualKeywords(),
...this.broadKeywords(),
...this.coarseKeywords(),
...this.fineKeywords(),
]);
selectAll(): void {
const seen = new Set<string>();
const result: string[] = [];
for (const entry of this.allKeywordEntries()) {
const label = entry.llm_keyword.keyword;
const normalized = this.normalizeKeyword(label);
if (!seen.has(normalized)) {
seen.add(normalized);
result.push(label);
}
}
this.selectedKeywords.set(result);
this.updateQueryParams();
}
deselectAll(): void {
this.selectedKeywords.set([]);
this.updateQueryParams();
}
clearKeywords(): void {
this.broadKeywordEntries.set([]);
this.coarseKeywordEntries.set([]);
this.fineKeywordEntries.set([]);
this.manualKeywordEntries.set([]);
this.sourceContent.set('');
this.sourceUrl.set(null);
clearPatentsCache();
const manualSet = new Set(this.getKeywordLabels(this.manualKeywords()));
this.selectedKeywords.set(
this.selectedKeywords().filter((k) => manualSet.has(k)),
);
// Reset the extraction source (no extracted keywords left)
this.extractionSource.set(null);
// updateQueryParams() persists this cleared state to sessionStorage too
// (see saveStateToSession() call inside it), so there's no need to
// separately wipe the session key here.
this.updateQueryParams();
}
areAllSelected(): boolean {
const allExtracted = [
...this.getKeywordLabels(this.broadKeywords()),
...this.getKeywordLabels(this.coarseKeywords()),
...this.getKeywordLabels(this.fineKeywords()),
...this.getKeywordLabels(this.manualKeywords()),
];
return allExtracted.every((k) => this.selectedKeywords().includes(k));
}
isSearchDisabled(): boolean {
return this.selectedKeywords().length === 0 || this.isExtracting();
}
onExtractKeywordsClick(): void {
this.clearKeywords();
if (this.isExtracting()) {
this.cancelKeywordExtraction();
return;
}
const mode = this.form.controls.selectedInputType.value;
if (mode === 'file') {
const files = this.uploadedFiles();
if (!files || files.length === 0) {
this.errorMessage.set('Bitte Datei hochladen.');
return;
}
this.isExtracting.set(true);
this.progress.set(0);
this.statusMessage.set('Dateien werden verarbeitet...');
const totalFiles = files.length;
let processedFiles = 0;
const fileUploads: FileUpload[] = new Array(totalFiles);
files.forEach((fileItem, index) => {
const file = fileItem.file;
const reader = new FileReader();
reader.onload = (e) => {
const dataUrl = e.target?.result as string;
const base64 = dataUrl.split(',')[1] ?? '';
fileUploads[index] = {
filename: file.name,
content_base64: base64,
mime_type: file.type || 'application/octet-stream',
};
processedFiles++;
if (processedFiles === totalFiles) {
this.sendFilesToWebSocket(fileUploads);
}
};
reader.onerror = () => {
console.error('Error reading file:', file.name);
fileUploads[index] = {
filename: file.name,
content_base64: '',
mime_type: file.type || 'application/octet-stream',
};
processedFiles++;
if (processedFiles === totalFiles) {
this.sendFilesToWebSocket(fileUploads);
}
};
reader.readAsDataURL(file);
});
return;
}
// For URL and text, fall back to original behavior
void this.extractKeywords();
}
addExtractedKeyword(keywords: ExtractedKeywords): void {
this.applyExtractedKeywords(keywords);
}
processExtractedKeywords(result: ExtractedKeywordsResponse): void {
if (result === undefined || !result.results) return;
const { results, source, source_content, source_url } = result;
this.applyExtractedKeywords(results);
this.sourceContent.set(source_content);
this.extractionSource.set(source as InputMode);
this.sourceUrl.set(source_url ?? '');
// Keep only selected keywords that still exist in any category (including manual)
const allExtracted = [
...this.getKeywordLabels(this.broadKeywords()),
...this.getKeywordLabels(this.coarseKeywords()),
...this.getKeywordLabels(this.fineKeywords()),
...this.getKeywordLabels(this.manualKeywords()),
];
this.selectedKeywords.set(
this.selectedKeywords().filter((k) => allExtracted.includes(k)),
);
// updateQueryParams() also calls saveStateToSession() - no need to call
// it separately here.
this.updateQueryParams();
}
async extractKeywords(): Promise<void> {
this.clearKeywords();
const query = this.getCurrentExtractionQuery();
if (!query) return;
this.progress.set(0);
this.statusMessage.set('Starte Extraktion...');
const currentMode = this.form.controls.selectedInputType.value;
const keywordsRequest: KeywordsRequest = {
query,
mode: currentMode,
limit: undefined,
};
this.isExtracting.set(true);
try {
// sendRequest now waits internally for the connection to open
await this.websocketService.sendRequest(keywordsRequest);
} catch (error) {
console.error('WebSocket send error:', error);
this.isExtracting.set(false);
this.errorMessage.set('Fehler beim Senden der Anfrage');
}
}
cancelKeywordExtraction(): void {
this.websocketService.close();
this.isExtracting.set(false);
this.progress.set(0);
this.errorMessage.set('Extraktion abgebrochen');
}
search(): void {
this.showVisualization.set(false);
const fuzzySearch = this.topicMappingSearch();
const payload: SearchResultsPayload = {
extractedKeywords: this.getSelectedExtractedKeywordEntries(),
manualKeywords: this.getSelectedManualKeywordEntries(),
patentKeywordEntries: this.getSelectedPatentKeywordEntries(),
keywords: this.selectedKeywords(),
options: {
fuzzy: fuzzySearch,
},
};
// Best-effort cache for the heavier, topic-enriched entries.
// Not authoritative — search-results must work without it.
try {
sessionStorage.setItem(
this.SEARCH_RESULTS_HANDOFF_KEY,
JSON.stringify(payload),
);
} catch (error) {
console.error('Failed to cache search-results handoff:', error);
}
// Authoritative, reload-safe, shareable.
this.router.navigate(['keywords/search-results'], {
queryParams: {
keywords: this.serializeKeywords(payload.keywords),
fuzzy: fuzzySearch,
},
});
}
visualize(): void {
this.showVisualization.set(true);
}
// --- Helpers --------------------------------------------------------------
private applyExtractedKeywords(keywords: ExtractedKeywords): void {
const seenKeywords = new Set(
this.getKeywordLabels(this.manualKeywords()).map((keyword) =>
this.normalizeKeyword(keyword),
),
);
this.broadKeywordEntries.set(
this.uniqueKeywordEntries(keywords.broad_keywords, seenKeywords),
);
this.coarseKeywordEntries.set(
this.uniqueKeywordEntries(keywords.coarse_grained, seenKeywords),
);
this.fineKeywordEntries.set(
this.uniqueKeywordEntries(keywords.fine_grained, seenKeywords),
);
this.selectAll();
}
private getSelectedExtractedKeywordEntries(): KeywordEntryWithTopic[] {
const selected = new Set(
this.selectedKeywords().map((k) => this.normalizeKeyword(k)),
);
return [
...this.broadKeywordEntries(),
...this.coarseKeywordEntries(),
...this.fineKeywordEntries(),
].filter((item) =>
selected.has(this.normalizeKeyword(this.getKeywordLabel(item))),
);
}
private getSelectedManualKeywordEntries(): KeywordEntryWithTopic[] {
const selected = new Set(
this.selectedKeywords().map((k) => this.normalizeKeyword(k)),
);
return this.manualKeywordEntries().filter((item) =>
selected.has(this.normalizeKeyword(this.getKeywordLabel(item))),
);
}
private filterKeywordEntries(
items: KeywordEntryWithTopic[],
keyword: string,
): KeywordEntryWithTopic[] {
const normalized = this.normalizeKeyword(keyword);
return items.filter(
(item) =>
this.normalizeKeyword(this.getKeywordLabel(item)) !== normalized,
);
}
onViewToggleChange(value: KeywordView): void {
if (this.keywordView() !== value) {
this.keywordView.set(value);
}
this.updateQueryParams();
}
onSubfieldLegendVisibleChange(visible: boolean): void {
this.subfieldLegendVisible.set(visible);
this.updateQueryParams();
}
onSubfieldLegendExpandedChange(expanded: boolean): void {
this.subfieldLegendExpanded.set(expanded);
this.updateQueryParams();
}
// Use this instead of directly binding keyword.topic_mapping?.topic?.display_name
getChipLabel(keyword: KeywordEntryWithTopic): string {
if (this.keywordView() == 'llm') {
return keyword.llm_keyword?.keyword ?? '';
}
return (
keyword.topic_mapping?.topic?.display_name ??
keyword.llm_keyword?.keyword ??
''
);
}
private getKeywordLabel(item: KeywordEntryWithTopic): string {
return item.llm_keyword.keyword;
}
private getKeywordLabels(items: KeywordEntryWithTopic[]): string[] {
return items.map((item) => this.getKeywordLabel(item));
}
private getTopic(item: KeywordEntryWithTopic) {
return item.topic_mapping?.topic ?? null;
}
getChipDescription(item: KeywordEntryWithTopic): string | null {
return this.getTopic(item)?.description ?? null;
}
getChipSubfieldName(item: KeywordEntryWithTopic): string | null {
return this.getTopic(item)?.subfield?.display_name ?? null;
}
getChipFieldName(item: KeywordEntryWithTopic): string | null {
return this.getTopic(item)?.field?.display_name ?? null;
}
getChipDomainName(item: KeywordEntryWithTopic): string | null {
return this.getTopic(item)?.domain?.display_name ?? null;
}
getChipCount(item: KeywordEntryWithTopic): number | null {
const topic = this.getTopic(item);
return topic?.works_count ?? null;
}
private toTopicLegendTopic(topic: Topic): TopicLegendTopic {
return {
id: topic.id ?? topic.display_name ?? '',
name: topic.display_name ?? '',
field_id: topic.field?.id ?? null,
field_name: topic.field?.display_name ?? null,
field_description: null,
domain_id: topic.domain?.id ?? null,
domain_name: topic.domain?.display_name ?? null,
domain_description: null,
subfield_id: topic.subfield?.id ?? null,
subfield_name: topic.subfield?.display_name ?? null,
subfield_description: null,
};
}
getTopicColor(topic: Topic | undefined | null): string {
const topicInput: TopicHierarchyColorInput = {
id: topic?.id ?? null,
name: topic?.display_name ?? null,
field_id: topic?.field?.id ?? null,
field_name: topic?.field?.display_name ?? null,
domain_id: topic?.domain?.id ?? null,
domain_name: topic?.domain?.display_name ?? null,
};
return topicHierarchyColor(topicInput);
}
private keywordEntriesFromStrings(
keywords: string[],
seenKeywords: Set<string> = new Set(),
): KeywordEntryWithTopic[] {
const entries: KeywordEntryWithTopic[] = [];
for (const keyword of this.uniqueKeywords(keywords)) {
const normalized = this.normalizeKeyword(keyword);
if (!normalized || seenKeywords.has(normalized)) continue;
seenKeywords.add(normalized);
entries.push({
llm_keyword: { keyword, relevance_score: 0 },
topic_mapping: null,
});
}
return entries;
}
private uniqueKeywordEntries(
items: KeywordEntryWithTopic[],
seenKeywords: Set<string> = new Set(),
): KeywordEntryWithTopic[] {
const uniqueItems: KeywordEntryWithTopic[] = [];
for (const item of items ?? []) {
const normalized = this.normalizeKeyword(this.getKeywordLabel(item));
if (!normalized || seenKeywords.has(normalized)) continue;
seenKeywords.add(normalized);
uniqueItems.push(item);
}
return uniqueItems;
}
// --- URL <-> state sync -----------------------------------------------
restoreStateFromQueryParams(): void {
const queryParams = this.route.snapshot.queryParamMap;
const mode = this.parseMode(queryParams.get('mode'));
const urlInput = queryParams.get('url') ?? '';
const textInput = queryParams.get('text') ?? '';
const manual = this.parseKeywordList(queryParams.get('manual'));
const selected = this.parseKeywordList(queryParams.get('selected'));
const source = queryParams.get('source') ?? '';
const view = queryParams.get('view') ?? 'llm';
const legend = queryParams.get('legend') ?? 'on';
const legendExpanded = queryParams.get('legendExpanded') ?? 'off';
this.isRestoringState = true;
this.form.patchValue(
{
selectedInputType: mode,
urlInput,
textInput,
},
{ emitEvent: false },
);
this.keywordView.set(view as KeywordView);
this.subfieldLegendVisible.set(legend === 'on');
this.subfieldLegendExpanded.set(legendExpanded === 'on');
this.extractionSource.set(source as InputMode);
this.restoreStateFromSession();
const merged = this.uniqueKeywordEntries([
...this.manualKeywordEntries(), // session restored entries
...this.keywordEntriesFromStrings(manual), // query param entries
]);
this.manualKeywordEntries.set(merged);
// enrich only newly added keywords that have no topic yet
this.enrichManualKeywordsWithTopics(manual);
// clean up the selection to only include keywords that actually exist in
const manualKeywordSet = new Set(
this.getKeywordLabels(this.manualKeywords()).map((k) =>
this.normalizeKeyword(k),
),
);
const broadKeywordSet = new Set(
this.getKeywordLabels(this.broadKeywords()).map((k) =>
this.normalizeKeyword(k),
),
);
const coarseKeywordSet = new Set(
this.getKeywordLabels(this.coarseKeywords()).map((k) =>
this.normalizeKeyword(k),
),
);
const fineKeywordSet = new Set(
this.getKeywordLabels(this.fineKeywords()).map((k) =>
this.normalizeKeyword(k),
),
);
const validSelected = [...this.selectedKeywords(), ...selected].filter(
(k) =>
manualKeywordSet.has(this.normalizeKeyword(k)) ||
broadKeywordSet.has(this.normalizeKeyword(k)) ||
coarseKeywordSet.has(this.normalizeKeyword(k)) ||
fineKeywordSet.has(this.normalizeKeyword(k)),
);
const selectionWasTrimmed = validSelected.length !== selected.length;
this.selectedKeywords.set(this.uniqueKeywords(validSelected));
if (selectionWasTrimmed) {
this.updateQueryParams();
}
this.isRestoringState = false;
}
updateQueryParams(): void {
if (this.isRestoringState) return;
const queryParams = {
mode: this.form.controls.selectedInputType.value,
url: this.toNullableParam(this.form.controls.urlInput.value),
text: this.toNullableParam(this.form.controls.textInput.value),
view: this.keywordView(),
legend: this.subfieldLegendVisible() ? 'on' : 'off',
legendExpanded: this.subfieldLegendExpanded() ? 'on' : 'off',
broad: this.serializeKeywords(
this.getKeywordLabels(this.broadKeywords()),
),
coarse: this.serializeKeywords(
this.getKeywordLabels(this.coarseKeywords()),
),
fine: this.serializeKeywords(this.getKeywordLabels(this.fineKeywords())),
manual: this.serializeKeywords(
this.getKeywordLabels(this.manualKeywords()),
),
selected: this.serializeKeywords(this.selectedKeywords()),
};
this.isOwnNavigation = true;
this.router
.navigate([], {
relativeTo: this.route,
queryParams,
queryParamsHandling: 'merge',
replaceUrl: true,
})
.then((navigated) => {
// If Angular decided there was nothing to navigate (e.g. the URL
// would be identical), queryParamMap never emits, so the flag would
// otherwise stay stuck `true` and incorrectly swallow the *next*
// real external navigation. Reset it defensively in that case.
if (!navigated) {
this.isOwnNavigation = false;
}
});
// IMPORTANT: every state mutation flows through here, so this is also
// the single place that keeps sessionStorage in sync. Previously the
// session cache was only saved after a full extraction completed, so
// adding a manual keyword (or removing one, etc.) never updated it. The
// *next* query-param change then triggered restoreStateFromQueryParams()
// -> restoreStateFromSession(), which overwrote the fresh manual
// keyword with that stale snapshot - making manually added keywords
// seem to vanish immediately. Saving here fixes that race.
this.saveStateToSession();
}
private saveStateToSession(): void {
const data = {
source: this.extractionSource(),
sourceContent: this.sourceContent(),
sourceUrl: this.sourceUrl(),
broadKeywordEntries: this.broadKeywordEntries(),
coarseKeywordEntries: this.coarseKeywordEntries(),
fineKeywordEntries: this.fineKeywordEntries(),
manualKeywordEntries: this.manualKeywordEntries(),
selectedKeywords: this.selectedKeywords(),
};
try {
sessionStorage.setItem(this.SESSION_KEY, JSON.stringify(data));
} catch (error) {
console.error('Failed to persist keyword search state:', error);
}
}
private restoreStateFromSession(): void {
const raw = sessionStorage.getItem(this.SESSION_KEY);
if (!raw) return;
try {
const {
source,
sourceContent,
sourceUrl,
broadKeywordEntries,
coarseKeywordEntries,
fineKeywordEntries,
manualKeywordEntries,
selectedKeywords,
} = JSON.parse(raw);
this.extractionSource.set(source as InputMode);
this.sourceContent.set(sourceContent ?? '');
this.sourceUrl.set(sourceUrl ?? null);
this.broadKeywordEntries.set(broadKeywordEntries ?? []);
this.coarseKeywordEntries.set(coarseKeywordEntries ?? []);
this.fineKeywordEntries.set(fineKeywordEntries ?? []);
this.manualKeywordEntries.set(manualKeywordEntries ?? []);
this.selectedKeywords.set(selectedKeywords ?? []);
} catch {
sessionStorage.removeItem(this.SESSION_KEY);
}
}
private clearStateFromSession(): void {
sessionStorage.removeItem(this.SESSION_KEY);
}
private getCurrentExtractionQuery(): string {
const mode = this.form.controls.selectedInputType.value;
if (mode === 'url') return this.form.controls.urlInput.value.trim();
if (mode === 'text') return this.form.controls.textInput.value.trim();
return this.selectedKeywords().join(', ').trim();
}
private parseMode(mode: string | null): InputMode {
if (mode === 'url') return 'url';
if (mode === 'text') return 'text';
if (mode === 'file') return 'file';
return 'url';
}
private parseKeywordList(rawValue: string | null): string[] {
if (!rawValue) return [];
return this.uniqueKeywords(
rawValue
.split(',')
.map((v) => v.trim())
.filter((v) => !!v),
);
}
private serializeKeywords(keywords: string[]): string | null {
const sanitized = this.uniqueKeywords(keywords);
return sanitized.length ? sanitized.join(',') : null;
}
private uniqueKeywords(values: string[]): string[] {
const uniqueValues: string[] = [];
const seenKeywords = new Set<string>();
for (const value of values) {
const normalized = this.normalizeKeyword(value);
if (!normalized || seenKeywords.has(normalized)) continue;
seenKeywords.add(normalized);
uniqueValues.push(value.trim());
}
return uniqueValues;
}
private normalizeKeyword(value: string): string {
return value.trim().toLowerCase();
}
private toNullableParam(value: string): string | null {
const normalized = value.trim();
return normalized.length ? normalized : null;
}
private getProgressForStep(step: string): number {
switch (step) {
case 'started':
return 10;
case 'fetching_url':
return 20;
case 'content_extracted':
return 30;
case 'calling_llm':
return 40;
case 'enriching':
return 60;
default:
return 50; // fallback for unknown steps
}
}
private getSelectedPatentKeywordEntries(): Array<{
entry: KeywordEntryWithTopic;
level: KeywordPatentLevel;
}> {
const selected = new Set(
this.selectedKeywords().map((k) => this.normalizeKeyword(k)),
);
const isSelected = (item: KeywordEntryWithTopic) =>
selected.has(this.normalizeKeyword(this.getKeywordLabel(item)));
return [
...this.broadKeywordEntries()
.filter(isSelected)
.map((entry) => ({ entry, level: 'broad' as const })),
...this.coarseKeywordEntries()
.filter(isSelected)
.map((entry) => ({ entry, level: 'coarse' as const })),
...this.fineKeywordEntries()
.filter(isSelected)
.map((entry) => ({ entry, level: 'fine' as const })),
...this.manualKeywordEntries()
.filter(isSelected)
.map((entry) => ({ entry, level: 'custom' as const })),
];
}
}