added keywords enrichment, refactored
This commit is contained in:
@@ -1,4 +1,10 @@
|
||||
import { Component, signal, computed } from '@angular/core';
|
||||
import {
|
||||
Component,
|
||||
computed,
|
||||
signal,
|
||||
Signal,
|
||||
WritableSignal,
|
||||
} from '@angular/core';
|
||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
||||
import { FormBuilder, ReactiveFormsModule } from '@angular/forms';
|
||||
import { MatButtonModule } from '@angular/material/button';
|
||||
@@ -18,8 +24,13 @@ import { ExtractedKeywordsResponse } from '../../api/model/extractedKeywordsResp
|
||||
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';
|
||||
type InputMode = 'url' | 'text' | 'keywords';
|
||||
import { TopicAutocompleteComponent } from '../../shared/ui/topic-autocomplete/topic-autocomplete.component';
|
||||
|
||||
type InputMode = 'url' | 'text';
|
||||
type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual';
|
||||
|
||||
@Component({
|
||||
selector: 'app-keywords-search',
|
||||
@@ -35,6 +46,7 @@ type InputMode = 'url' | 'text' | 'keywords';
|
||||
MatCardModule,
|
||||
MatExpansionModule,
|
||||
MatProgressBarModule,
|
||||
TopicAutocompleteComponent,
|
||||
],
|
||||
templateUrl: './keywords-search.component.html',
|
||||
styleUrl: './keywords-search.component.scss',
|
||||
@@ -44,33 +56,61 @@ export class KeywordsSearchComponent {
|
||||
selectedInputType: 'url' as InputMode,
|
||||
urlInput: '',
|
||||
textInput: '',
|
||||
keywordInput: '',
|
||||
});
|
||||
|
||||
private readonly SESSION_KEY = 'keywords-search-source';
|
||||
// Category signals
|
||||
readonly broadKeywords = signal<string[]>([]);
|
||||
readonly coarseKeywords = signal<string[]>([]);
|
||||
readonly fineKeywords = signal<string[]>([]);
|
||||
readonly manualKeywords = signal<string[]>([]);
|
||||
|
||||
// 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().map((item) => this.getKeywordLabel(item)),
|
||||
);
|
||||
readonly coarseKeywords = computed(() =>
|
||||
this.coarseKeywordEntries().map((item) => this.getKeywordLabel(item)),
|
||||
);
|
||||
readonly fineKeywords = computed(() =>
|
||||
this.fineKeywordEntries().map((item) => this.getKeywordLabel(item)),
|
||||
);
|
||||
readonly manualKeywords = computed(() =>
|
||||
this.manualKeywordEntries().map((item) => this.getKeywordLabel(item)),
|
||||
);
|
||||
|
||||
readonly selectedKeywords = signal<string[]>([]);
|
||||
readonly isExtracting = signal(false);
|
||||
|
||||
readonly extractionSource = signal<InputMode | null>(null);
|
||||
|
||||
readonly selectedBroadKeywords = computed(() =>
|
||||
this.selectedKeywords().filter((k) => this.broadKeywords().includes(k)),
|
||||
);
|
||||
readonly selectedCoarseKeywords = computed(() =>
|
||||
this.selectedKeywords().filter((k) => this.coarseKeywords().includes(k)),
|
||||
);
|
||||
readonly selectedFineKeywords = computed(() =>
|
||||
this.selectedKeywords().filter((k) => this.fineKeywords().includes(k)),
|
||||
);
|
||||
readonly selectedManualKeywords = computed(() =>
|
||||
this.selectedKeywords().filter((k) => this.manualKeywords().includes(k)),
|
||||
);
|
||||
// Single place mapping a category name to its label signal and its
|
||||
// backing entries signal. Replaces four near-identical computed()s and
|
||||
// a category switch statement that used to live below.
|
||||
private readonly categoryKeywordsMap: Record<
|
||||
KeywordCategory,
|
||||
Signal<string[]>
|
||||
> = {
|
||||
broad: this.broadKeywords,
|
||||
coarse: this.coarseKeywords,
|
||||
fine: this.fineKeywords,
|
||||
manual: this.manualKeywords,
|
||||
};
|
||||
private readonly categoryEntriesMap: Record<
|
||||
KeywordCategory,
|
||||
WritableSignal<KeywordEntryWithTopic[]>
|
||||
> = {
|
||||
broad: this.broadKeywordEntries,
|
||||
coarse: this.coarseKeywordEntries,
|
||||
fine: this.fineKeywordEntries,
|
||||
manual: this.manualKeywordEntries,
|
||||
};
|
||||
|
||||
readonly selectedBroadKeywords = this.selectedInCategory('broad');
|
||||
readonly selectedCoarseKeywords = this.selectedInCategory('coarse');
|
||||
readonly selectedFineKeywords = this.selectedInCategory('fine');
|
||||
readonly selectedManualKeywords = this.selectedInCategory('manual');
|
||||
|
||||
readonly extractedKeywordsExist = computed(
|
||||
() =>
|
||||
this.broadKeywords().length > 0 ||
|
||||
@@ -83,126 +123,224 @@ export class KeywordsSearchComponent {
|
||||
|
||||
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('');
|
||||
|
||||
constructor(
|
||||
private readonly formBuilder: FormBuilder,
|
||||
private readonly route: ActivatedRoute,
|
||||
private readonly router: Router,
|
||||
private readonly destroyRef: DestroyRef,
|
||||
private readonly websocketService: KeywordWebSocketService,
|
||||
private readonly topicsService: TopicsService,
|
||||
) {
|
||||
this.route.queryParamMap.pipe(takeUntilDestroyed()).subscribe((event) => {
|
||||
//console.log('Component received event:', event);
|
||||
this.route.queryParamMap.pipe(takeUntilDestroyed()).subscribe(() => {
|
||||
if (this.isOwnNavigation) {
|
||||
// This emission is just the router confirming the navigation we
|
||||
// triggered ourselves in updateQueryParams(); our signals are
|
||||
// already correct, so skip re-deriving state from the URL.
|
||||
this.isOwnNavigation = false;
|
||||
return;
|
||||
}
|
||||
this.restoreStateFromQueryParams();
|
||||
});
|
||||
|
||||
this.form.controls.selectedInputType.valueChanges
|
||||
.pipe(distinctUntilChanged(), takeUntilDestroyed())
|
||||
.subscribe(() => {
|
||||
this.updateQueryParams();
|
||||
});
|
||||
.subscribe(() => this.updateQueryParams());
|
||||
|
||||
this.form.controls.urlInput.valueChanges
|
||||
.pipe(debounceTime(400), distinctUntilChanged(), takeUntilDestroyed())
|
||||
.subscribe(() => {
|
||||
this.updateQueryParams();
|
||||
});
|
||||
.subscribe(() => this.updateQueryParams());
|
||||
|
||||
this.form.controls.textInput.valueChanges
|
||||
.pipe(debounceTime(400), distinctUntilChanged(), takeUntilDestroyed())
|
||||
.subscribe(() => {
|
||||
this.updateQueryParams();
|
||||
});
|
||||
.subscribe(() => this.updateQueryParams());
|
||||
|
||||
//get streamed data
|
||||
this.websocketService.getMessages().subscribe((event: WsEvent) => {
|
||||
switch (event.type) {
|
||||
case 'status':
|
||||
console.log('STATUS:', event.step, event.message);
|
||||
this.statusMessage.set(event.message || '');
|
||||
this.progress.set(this.getProgressForStep(event.step || ''));
|
||||
break;
|
||||
case 'keywords':
|
||||
console.log('KEYWORDS:', event.keywords);
|
||||
if (event.keywords) this.addExtractedKeyword(event.keywords);
|
||||
break;
|
||||
this.websocketService
|
||||
.getMessages()
|
||||
.subscribe((event: WsEvent) => this.handleWsEvent(event));
|
||||
|
||||
case 'completed':
|
||||
console.log('COMPLETED:', event.result);
|
||||
this.processExtractedKeywords(
|
||||
event.result as ExtractedKeywordsResponse,
|
||||
);
|
||||
this.isExtracting.set(false);
|
||||
this.progress.set(100);
|
||||
this.statusMessage.set('Fertig!');
|
||||
this.websocketService.close();
|
||||
this.isExtracting.set(false);
|
||||
break;
|
||||
|
||||
case 'error':
|
||||
console.error('ERROR:', event.message);
|
||||
this.progress.set(0);
|
||||
this.statusMessage.set('Fehler: ' + event.message);
|
||||
this.broadKeywords.set([]);
|
||||
this.coarseKeywords.set([]);
|
||||
this.fineKeywords.set([]);
|
||||
this.websocketService.close();
|
||||
this.isExtracting.set(false);
|
||||
// Keep manual, but remove selected that are not in manual
|
||||
this.selectedKeywords.set(
|
||||
this.selectedKeywords().filter((k) =>
|
||||
this.manualKeywords().includes(k),
|
||||
),
|
||||
);
|
||||
// extractionSource stays as it was (or reset? we keep it)
|
||||
this.updateQueryParams();
|
||||
break;
|
||||
default:
|
||||
console.warn('Unknown event type:', event);
|
||||
}
|
||||
// this.destroyRef.onDestroy(() => {
|
||||
// this.websocketService.close();
|
||||
// });
|
||||
});
|
||||
|
||||
// Clear session storage on component destroy
|
||||
// Clear session storage on component destroy, unless this is a page
|
||||
// reload (in which case we want the cache to survive).
|
||||
this.destroyRef.onDestroy(() => {
|
||||
this.websocketService.close();
|
||||
const nav = this.router.lastSuccessfulNavigation;
|
||||
const isReload = nav === null;
|
||||
const isReload = this.router.lastSuccessfulNavigation === null;
|
||||
if (!isReload) {
|
||||
this.clearSourceFromSession();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// --- 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);
|
||||
}
|
||||
|
||||
private handleErrorEvent(event: WsEvent): void {
|
||||
this.progress.set(0);
|
||||
this.statusMessage.set('Fehler: ' + event.message);
|
||||
this.broadKeywordEntries.set([]);
|
||||
this.coarseKeywordEntries.set([]);
|
||||
this.fineKeywordEntries.set([]);
|
||||
this.websocketService.close();
|
||||
this.isExtracting.set(false);
|
||||
// Keep manual, but remove selected that are not in manual
|
||||
this.selectedKeywords.set(
|
||||
this.selectedKeywords().filter((k) => 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 {
|
||||
const mode = this.form.controls.selectedInputType.value;
|
||||
if (mode === 'text') return 1;
|
||||
if (mode === 'keywords') return 2;
|
||||
return 0;
|
||||
return this.form.controls.selectedInputType.value === 'text' ? 1 : 0;
|
||||
}
|
||||
|
||||
onTabChange(index: number): void {
|
||||
const nextMode: InputMode =
|
||||
index === 1 ? 'text' : index === 2 ? 'keywords' : 'url';
|
||||
const nextMode: InputMode = index === 1 ? 'text' : 'url';
|
||||
this.form.controls.selectedInputType.setValue(nextMode);
|
||||
}
|
||||
|
||||
// Add manually from Keywords tab
|
||||
addKeywordFromInput(): void {
|
||||
const keyword = this.form.controls.keywordInput.value.trim();
|
||||
if (!keyword) return;
|
||||
// --- Keyword selection & manual entry ------------------------------------
|
||||
|
||||
this.manualKeywords.set(
|
||||
this.uniqueKeywords([...this.manualKeywords(), keyword]),
|
||||
);
|
||||
this.selectedKeywords.set(
|
||||
this.uniqueKeywords([...this.selectedKeywords(), keyword]),
|
||||
);
|
||||
this.form.controls.keywordInput.setValue('');
|
||||
this.updateQueryParams();
|
||||
private keywordExists(keyword: string): boolean {
|
||||
const normalized = this.normalizeKeyword(keyword);
|
||||
return [
|
||||
...this.broadKeywords(),
|
||||
...this.coarseKeywords(),
|
||||
...this.fineKeywords(),
|
||||
...this.manualKeywords(),
|
||||
].some((k) => this.normalizeKeyword(k) === normalized);
|
||||
}
|
||||
|
||||
// Add manually from Keywords tab
|
||||
addKeywordFromInput(keyword: string): void {
|
||||
const normalizedKeyword = keyword.trim();
|
||||
if (!normalizedKeyword) return;
|
||||
|
||||
if (this.keywordExists(normalizedKeyword)) {
|
||||
this.statusMessage.set(`"${normalizedKeyword}" ist bereits vorhanden.`);
|
||||
return;
|
||||
}
|
||||
|
||||
this.topicsService.vectorSearchTopics(normalizedKeyword).subscribe({
|
||||
next: ({ results }) => {
|
||||
const newEntry: KeywordEntryWithTopic = {
|
||||
llm_keyword: {
|
||||
keyword: normalizedKeyword,
|
||||
relevance_score: 1,
|
||||
},
|
||||
topic_mapping: {
|
||||
keyword: normalizedKeyword,
|
||||
topic: results?.[0],
|
||||
},
|
||||
};
|
||||
|
||||
const updated = this.uniqueKeywordEntries([
|
||||
...this.manualKeywordEntries(),
|
||||
newEntry,
|
||||
]);
|
||||
|
||||
this.manualKeywordEntries.set(updated);
|
||||
this.selectedKeywords.set([
|
||||
...this.selectedKeywords(),
|
||||
normalizedKeyword,
|
||||
]);
|
||||
|
||||
// Explicit enrichment trigger for new keywords
|
||||
this.enrichManualKeywordsWithTopics([normalizedKeyword]);
|
||||
this.updateQueryParams();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
removeSelectedKeyword(keyword: string): void {
|
||||
@@ -213,15 +351,15 @@ export class KeywordsSearchComponent {
|
||||
}
|
||||
|
||||
onCategoryChange(
|
||||
category: 'broad' | 'coarse' | 'fine' | 'manual',
|
||||
category: KeywordCategory,
|
||||
event: MatChipListboxChange,
|
||||
): void {
|
||||
const newSelection = (event.value as string[]) || [];
|
||||
const otherCategories = ['broad', 'coarse', 'fine', 'manual'].filter(
|
||||
(c) => c !== category,
|
||||
);
|
||||
const otherCategories = (
|
||||
Object.keys(this.categoryKeywordsMap) as KeywordCategory[]
|
||||
).filter((c) => c !== category);
|
||||
const otherSelected = otherCategories.flatMap((c) => {
|
||||
const keywords = this.getCategoryKeywords(c);
|
||||
const keywords = this.categoryKeywordsMap[c]();
|
||||
return this.selectedKeywords().filter((k) => keywords.includes(k));
|
||||
});
|
||||
const updated = [...otherSelected, ...newSelection];
|
||||
@@ -229,21 +367,6 @@ export class KeywordsSearchComponent {
|
||||
this.updateQueryParams();
|
||||
}
|
||||
|
||||
private getCategoryKeywords(category: string): string[] {
|
||||
switch (category) {
|
||||
case 'broad':
|
||||
return this.broadKeywords();
|
||||
case 'coarse':
|
||||
return this.coarseKeywords();
|
||||
case 'fine':
|
||||
return this.fineKeywords();
|
||||
case 'manual':
|
||||
return this.manualKeywords();
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
selectAllExtracted(): void {
|
||||
const all = [
|
||||
...this.selectedManualKeywords(),
|
||||
@@ -256,18 +379,19 @@ export class KeywordsSearchComponent {
|
||||
}
|
||||
|
||||
deselectAllExtracted(): void {
|
||||
const manual = this.selectedManualKeywords();
|
||||
this.selectedKeywords.set(this.uniqueKeywords(manual));
|
||||
this.selectedKeywords.set(
|
||||
this.uniqueKeywords(this.selectedManualKeywords()),
|
||||
);
|
||||
this.updateQueryParams();
|
||||
}
|
||||
|
||||
clearExtractedKeywords(): void {
|
||||
this.broadKeywords.set([]);
|
||||
this.coarseKeywords.set([]);
|
||||
this.fineKeywords.set([]);
|
||||
this.broadKeywordEntries.set([]);
|
||||
this.coarseKeywordEntries.set([]);
|
||||
this.fineKeywordEntries.set([]);
|
||||
this.sourceContent.set('');
|
||||
this.sourceUrl.set(null);
|
||||
this.clearSourceFromSession();
|
||||
|
||||
// Keep only selected keywords that are in the manual list
|
||||
const manualSet = new Set(this.manualKeywords());
|
||||
this.selectedKeywords.set(
|
||||
@@ -277,6 +401,9 @@ export class KeywordsSearchComponent {
|
||||
// Reset the extraction source (no extracted keywords left)
|
||||
this.extractionSource.set(null);
|
||||
|
||||
// updateQueryParams() persists this cleared state to sessionStorage too
|
||||
// (see saveSourceToSession() call inside it), so there's no need to
|
||||
// separately wipe the session key here.
|
||||
this.updateQueryParams();
|
||||
}
|
||||
|
||||
@@ -288,110 +415,70 @@ export class KeywordsSearchComponent {
|
||||
];
|
||||
return allExtracted.every((k) => this.selectedKeywords().includes(k));
|
||||
}
|
||||
// isExtractionSourceMatch() {
|
||||
// console.log(
|
||||
// this.extractionSource(),
|
||||
// this.form.controls.selectedInputType.value,
|
||||
// );
|
||||
// return (
|
||||
// this.form.controls.selectedInputType.value === this.extractionSource() ||
|
||||
// this.form.controls.selectedInputType.value === 'keywords'
|
||||
// );
|
||||
// }
|
||||
|
||||
isSearchDisabled(): boolean {
|
||||
return this.selectedKeywords().length === 0 || this.isExtracting();
|
||||
}
|
||||
|
||||
onExtractKeywordsClick(): void {
|
||||
if (this.isExtracting()) {
|
||||
this.cancelKeywordExtraction();
|
||||
return;
|
||||
}
|
||||
|
||||
void this.extractKeywords();
|
||||
}
|
||||
|
||||
addExtractedKeyword(keywords: ExtractedKeywords): void {
|
||||
const broad = this.extractKeywordStrings(keywords.broad_keywords);
|
||||
const coarse = this.extractKeywordStrings(keywords.coarse_grained);
|
||||
const fine = this.extractKeywordStrings(keywords.fine_grained);
|
||||
|
||||
this.broadKeywords.set(broad);
|
||||
this.coarseKeywords.set(coarse);
|
||||
this.fineKeywords.set(fine);
|
||||
this.applyExtractedKeywords(keywords);
|
||||
}
|
||||
onKeywordRemoved(
|
||||
category: 'broad' | 'coarse' | 'fine' | 'manual',
|
||||
keyword: string,
|
||||
): void {
|
||||
// Remove from the category list
|
||||
const categoryKeywords = this.getCategoryKeywords(category);
|
||||
const updatedCategoryKeywords = categoryKeywords.filter(
|
||||
(k) => k !== keyword,
|
||||
);
|
||||
switch (category) {
|
||||
case 'broad':
|
||||
this.broadKeywords.set(updatedCategoryKeywords);
|
||||
break;
|
||||
case 'coarse':
|
||||
this.coarseKeywords.set(updatedCategoryKeywords);
|
||||
break;
|
||||
case 'fine':
|
||||
this.fineKeywords.set(updatedCategoryKeywords);
|
||||
break;
|
||||
case 'manual':
|
||||
this.manualKeywords.set(updatedCategoryKeywords);
|
||||
break;
|
||||
}
|
||||
|
||||
// Remove from selected keywords if it was selected
|
||||
onKeywordRemoved(category: KeywordCategory, keyword: string): void {
|
||||
const entries = this.categoryEntriesMap[category];
|
||||
entries.set(this.filterKeywordEntries(entries(), keyword));
|
||||
|
||||
this.selectedKeywords.set(
|
||||
this.selectedKeywords().filter((k) => k !== keyword),
|
||||
);
|
||||
|
||||
this.updateQueryParams();
|
||||
}
|
||||
|
||||
processExtractedKeywords(result: ExtractedKeywordsResponse): void {
|
||||
if (result === undefined || !result.results) {
|
||||
return;
|
||||
}
|
||||
if (result === undefined || !result.results) return;
|
||||
|
||||
const { results, source, source_content, source_url } = result;
|
||||
|
||||
const broad = this.extractKeywordStrings(results.broad_keywords);
|
||||
const coarse = this.extractKeywordStrings(results.coarse_grained);
|
||||
const fine = this.extractKeywordStrings(results.fine_grained);
|
||||
|
||||
this.broadKeywords.set(broad);
|
||||
this.coarseKeywords.set(coarse);
|
||||
this.fineKeywords.set(fine);
|
||||
this.applyExtractedKeywords(results);
|
||||
this.sourceContent.set(source_content);
|
||||
this.extractionSource.set(source as InputMode);
|
||||
this.sourceUrl.set(source_url ?? '');
|
||||
this.saveSourceToSession();
|
||||
|
||||
// Keep only selected keywords that still exist in any category (including manual)
|
||||
const allExtracted = [
|
||||
...broad,
|
||||
...coarse,
|
||||
...fine,
|
||||
...this.broadKeywords(),
|
||||
...this.coarseKeywords(),
|
||||
...this.fineKeywords(),
|
||||
...this.manualKeywords(),
|
||||
];
|
||||
this.selectedKeywords.set(
|
||||
this.selectedKeywords().filter((k) => allExtracted.includes(k)),
|
||||
);
|
||||
|
||||
// updateQueryParams() also calls saveSourceToSession() - no need to call
|
||||
// it separately here.
|
||||
this.updateQueryParams();
|
||||
}
|
||||
|
||||
async extractKeywords(): Promise<void> {
|
||||
this.clearExtractedKeywords();
|
||||
const query = this.getCurrentExtractionQuery();
|
||||
if (!query) return;
|
||||
|
||||
// Reset progress and status
|
||||
this.progress.set(0);
|
||||
this.statusMessage.set('Starte Extraktion...');
|
||||
|
||||
const currentMode = this.form.controls.selectedInputType.value;
|
||||
const keywordsRequest: KeywordsRequest = {
|
||||
query: query,
|
||||
query,
|
||||
mode: currentMode,
|
||||
limit: undefined,
|
||||
};
|
||||
@@ -416,56 +503,168 @@ export class KeywordsSearchComponent {
|
||||
}
|
||||
|
||||
search(): void {
|
||||
console.log('searching for keywords:', this.selectedKeywords());
|
||||
// e.g. navigate to search results page
|
||||
// this.router.navigate(['/search'], { queryParams: { keywords: this.selectedKeywords().join(',') } });
|
||||
const payload = {
|
||||
extractedKeywords: this.getSelectedExtractedKeywordEntries(),
|
||||
manualKeywords: this.getSelectedManualKeywordEntries(),
|
||||
keywords: this.selectedKeywords(),
|
||||
};
|
||||
|
||||
console.log('searching for keywords:', payload);
|
||||
// e.g. navigate to search results page with the full payload in navigation state
|
||||
// this.router.navigate(['/search'], { state: payload });
|
||||
}
|
||||
|
||||
private extractKeywordStrings(items: KeywordEntryWithTopic[]): string[] {
|
||||
return this.uniqueKeywords(
|
||||
(items ?? [])
|
||||
.map((item) => {
|
||||
const openalexKeyword = (item as any).topic_mapping?.keyword?.trim();
|
||||
const llmKeyword = (item as any).llm_keyword?.keyword?.trim();
|
||||
// return openalexKeyword || llmKeyword || '';
|
||||
return openalexKeyword || '';
|
||||
})
|
||||
.filter((kw) => !!kw),
|
||||
// --- Helpers --------------------------------------------------------------
|
||||
|
||||
private selectedInCategory(category: KeywordCategory): Signal<string[]> {
|
||||
return computed(() =>
|
||||
this.selectedKeywords().filter((k) =>
|
||||
this.categoryKeywordsMap[category]().includes(k),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// State restoration from URL
|
||||
private applyExtractedKeywords(keywords: ExtractedKeywords): void {
|
||||
const seenKeywords = new Set(
|
||||
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),
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
);
|
||||
}
|
||||
|
||||
private getKeywordLabel(item: KeywordEntryWithTopic): string {
|
||||
return item.llm_keyword.keyword.trim();
|
||||
}
|
||||
|
||||
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 broad = this.parseKeywordList(queryParams.get('broad'));
|
||||
const coarse = this.parseKeywordList(queryParams.get('coarse'));
|
||||
const fine = this.parseKeywordList(queryParams.get('fine'));
|
||||
const manual = this.parseKeywordList(queryParams.get('manual'));
|
||||
const selected = this.parseKeywordList(queryParams.get('selected'));
|
||||
const source = queryParams.get('source') ?? '';
|
||||
|
||||
this.isRestoringState = true;
|
||||
|
||||
this.form.patchValue(
|
||||
{
|
||||
selectedInputType: mode,
|
||||
urlInput,
|
||||
textInput,
|
||||
},
|
||||
{ selectedInputType: mode, urlInput, textInput },
|
||||
{ emitEvent: false },
|
||||
);
|
||||
this.broadKeywords.set(broad);
|
||||
this.coarseKeywords.set(coarse);
|
||||
this.fineKeywords.set(fine);
|
||||
this.manualKeywords.set(manual);
|
||||
this.selectedKeywords.set(this.uniqueKeywords(selected));
|
||||
|
||||
this.extractionSource.set(source as InputMode);
|
||||
this.restoreSourceFromSession();
|
||||
|
||||
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);
|
||||
|
||||
// User intent (the current selection): the URL is always authoritative
|
||||
// here, deliberately overriding whatever the session cache had. This
|
||||
// is what makes a deep link like ?selected=foo&manual=bar from another
|
||||
// page reliably preselect keywords, instead of getting merged with (or
|
||||
// hidden behind) leftover state from a previous visit in the same tab.
|
||||
|
||||
// clean up the selection to only include keywords that actually exist in
|
||||
const manualKeywordSet = new Set(
|
||||
this.manualKeywords().map((k) => this.normalizeKeyword(k)),
|
||||
);
|
||||
const validSelected = selected.filter((k) =>
|
||||
manualKeywordSet.has(this.normalizeKeyword(k)),
|
||||
);
|
||||
const selectionWasTrimmed = validSelected.length !== selected.length;
|
||||
|
||||
this.selectedKeywords.set(this.uniqueKeywords(validSelected));
|
||||
|
||||
this.isRestoringState = false;
|
||||
|
||||
if (selectionWasTrimmed) {
|
||||
this.updateQueryParams();
|
||||
}
|
||||
}
|
||||
|
||||
// Update URL query params
|
||||
updateQueryParams(): void {
|
||||
if (this.isRestoringState) return;
|
||||
|
||||
@@ -480,42 +679,84 @@ export class KeywordsSearchComponent {
|
||||
selected: this.serializeKeywords(this.selectedKeywords()),
|
||||
};
|
||||
|
||||
this.router.navigate([], {
|
||||
relativeTo: this.route,
|
||||
queryParams,
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true,
|
||||
});
|
||||
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()
|
||||
// -> restoreSourceFromSession(), which overwrote the fresh manual
|
||||
// keyword with that stale snapshot - making manually added keywords
|
||||
// seem to vanish immediately. Saving here fixes that race.
|
||||
this.saveSourceToSession();
|
||||
}
|
||||
|
||||
// Save to sessionStorage
|
||||
private saveSourceToSession(): void {
|
||||
const data = {
|
||||
source: this.extractionSource(),
|
||||
sourceContent: this.sourceContent(),
|
||||
sourceUrl: this.sourceUrl(),
|
||||
broadKeywordEntries: this.broadKeywordEntries(),
|
||||
coarseKeywordEntries: this.coarseKeywordEntries(),
|
||||
fineKeywordEntries: this.fineKeywordEntries(),
|
||||
manualKeywordEntries: this.manualKeywordEntries(),
|
||||
};
|
||||
sessionStorage.setItem(this.SESSION_KEY, JSON.stringify(data));
|
||||
|
||||
try {
|
||||
sessionStorage.setItem(this.SESSION_KEY, JSON.stringify(data));
|
||||
} catch (error) {
|
||||
console.error('Failed to persist keyword search state:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Restore from sessionStorage
|
||||
private restoreSourceFromSession(): void {
|
||||
const raw = sessionStorage.getItem(this.SESSION_KEY);
|
||||
if (!raw) return;
|
||||
|
||||
try {
|
||||
const { source, sourceContent, sourceUrl } = JSON.parse(raw);
|
||||
const {
|
||||
source,
|
||||
sourceContent,
|
||||
sourceUrl,
|
||||
broadKeywordEntries,
|
||||
coarseKeywordEntries,
|
||||
fineKeywordEntries,
|
||||
manualKeywordEntries,
|
||||
} = 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 ?? []);
|
||||
} catch {
|
||||
sessionStorage.removeItem(this.SESSION_KEY);
|
||||
}
|
||||
}
|
||||
|
||||
// Clear sessionStorage
|
||||
private clearSourceFromSession(): 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();
|
||||
@@ -524,8 +765,7 @@ export class KeywordsSearchComponent {
|
||||
}
|
||||
|
||||
private parseMode(mode: string | null): InputMode {
|
||||
if (mode === 'text' || mode === 'keywords') return mode;
|
||||
return 'url';
|
||||
return mode === 'text' ? 'text' : 'url';
|
||||
}
|
||||
|
||||
private parseKeywordList(rawValue: string | null): string[] {
|
||||
@@ -544,23 +784,41 @@ export class KeywordsSearchComponent {
|
||||
}
|
||||
|
||||
private uniqueKeywords(values: string[]): string[] {
|
||||
return Array.from(new Set(values.map((v) => v.trim()).filter(Boolean)));
|
||||
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 30;
|
||||
return 20;
|
||||
case 'content_extracted':
|
||||
return 60;
|
||||
return 30;
|
||||
case 'calling_llm':
|
||||
return 80;
|
||||
return 40;
|
||||
case 'enriching':
|
||||
return 60;
|
||||
default:
|
||||
return 50; // fallback for unknown steps
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user