added keywords-search component

This commit is contained in:
2026-06-29 22:23:14 +02:00
parent 1fdd5339fa
commit 642fda7542
3 changed files with 906 additions and 0 deletions
@@ -0,0 +1,235 @@
<div class="content">
<h1>Keywords Scout</h1>
<mat-divider />
<!-- Tabs and Extract Button (unchanged) -->
<mat-tab-group
[selectedIndex]="selectedTabIndex()"
(selectedIndexChange)="onTabChange($event)">
<mat-tab label="URL">
<div class="tab-content">
<mat-form-field appearance="outline" class="full-width">
<mat-label>Füge eine URL ein, um Keywords zu extrahieren</mat-label>
<input
matInput
placeholder="https://example.com/article"
[formControl]="form.controls.urlInput" />
</mat-form-field>
</div>
</mat-tab>
<mat-tab label="Text">
<div class="tab-content">
<mat-form-field appearance="outline" class="full-width">
<mat-label>Schreibe einen Text, um Keywords zu extrahieren</mat-label>
<textarea
matInput
rows="10"
placeholder="Large language models are transforming innovation scouting..."
[formControl]="form.controls.textInput"></textarea>
</mat-form-field>
</div>
</mat-tab>
<mat-tab label="Eigine Keywords">
<div class="tab-content keyword-input-row">
<mat-form-field appearance="outline" class="full-width">
<mat-label>Definieren Sie Ihre eigene Keywords</mat-label>
<input
matInput
placeholder="z. B. Knowledge Graphs"
[formControl]="form.controls.keywordInput"
(keydown.enter)="addKeywordFromInput(); $event.preventDefault()" />
</mat-form-field>
<button
mat-stroked-button
type="button"
color="primary"
(click)="addKeywordFromInput()">
<mat-icon>add</mat-icon>
Hinzufügen
</button>
</div>
</mat-tab>
</mat-tab-group>
<div class="actions">
@if (form.controls.selectedInputType.value !== 'keywords') {
<button
mat-flat-button
type="button"
color="primary"
(click)="extractKeywords()"
[disabled]="isExtracting()">
<mat-icon>troubleshoot</mat-icon>
@if (isExtracting()) {
Extrahiere...
} @else {
Keywords extrahieren
}
</button>
}
</div>
<!-- Grid with two columns: Extracted | Selected -->
<div class="extraction-grid">
<!-- Extracted Keywords Card -->
<mat-card appearance="outlined" class="keyword-card extracted-card">
<!--Source content display === -->
@if (sourceContent().length > 0 && extractionSource() === 'url') {
<mat-expansion-panel class="source-expansion">
<mat-expansion-panel-header>
<mat-panel-title
>Extrahierte Inhalte: {{ sourceUrl() }}</mat-panel-title
>
</mat-expansion-panel-header>
<div class="source-text">{{ sourceContent() }}</div>
</mat-expansion-panel>
<mat-divider />
}
<mat-card-content>
<!-- Extracted Keywords Section -->
<div class="extracted-section">
<mat-card-title class="section-title"
>Extrahierte Keywords</mat-card-title
>
@if (extractedKeywordsExist()) {
<div class="category-grid">
<!-- Broad -->
@if (broadKeywords().length > 0) {
<div class="category-section">
<h4>Breite Keywords</h4>
<mat-chip-listbox
multiple
[value]="selectedBroadKeywords()"
(change)="onCategoryChange('broad', $event)">
@for (keyword of broadKeywords(); track keyword) {
<mat-chip-option
[value]="keyword"
class="compact-chip broad-chip"
>{{ keyword }}</mat-chip-option
>
}
</mat-chip-listbox>
</div>
}
<!-- Coarse -->
@if (coarseKeywords().length > 0) {
<div class="category-section">
<h4>Coarse Keywords</h4>
<mat-chip-listbox
multiple
dense
[value]="selectedCoarseKeywords()"
(change)="onCategoryChange('coarse', $event)">
@for (keyword of coarseKeywords(); track keyword) {
<mat-chip-option
[value]="keyword"
class="compact-chip coarse-chip"
>{{ keyword }}</mat-chip-option
>
}
</mat-chip-listbox>
</div>
}
<!-- Fine -->
@if (fineKeywords().length > 0) {
<div class="category-section">
<h4>Fine Keywords</h4>
<mat-chip-listbox
multiple
dense
[value]="selectedFineKeywords()"
(change)="onCategoryChange('fine', $event)">
@for (keyword of fineKeywords(); track keyword) {
<mat-chip-option
[value]="keyword"
class="compact-chip fine-chip"
>{{ keyword }}</mat-chip-option
>
}
</mat-chip-listbox>
</div>
}
</div>
<!-- Select/Deselect All Extracted -->
<div class="select-all-container">
<!-- Existing select/deselect buttons -->
@if (areAllExtractedSelected()) {
<button
mat-stroked-button
color="primary"
size="small"
(click)="deselectAllExtracted()">
<mat-icon>select_all</mat-icon> Alle extrahierten Keywords
abwählen
</button>
} @else {
<button
mat-stroked-button
color="primary"
size="small"
(click)="selectAllExtracted()">
<mat-icon>select_all</mat-icon> Alle extrahierten Keywords
auswählen
</button>
}
<!-- NEW: Clear extracted keywords button -->
<button
mat-stroked-button
color="warn"
size="small"
(click)="clearExtractedKeywords()">
<mat-icon>delete_outline</mat-icon> Clear extracted keywords
</button>
</div>
} @else {
<p class="empty-state">
Keine extrahierten Keywords vorhanden. Extrahiere Keywords, um sie
hier zu sehen oder füge sie manuell hinzu.
</p>
}
</div>
<mat-divider></mat-divider>
<!-- Manually Added Section -->
<div class="manual-section">
<mat-card-title class="section-title">Eigene Keywords</mat-card-title>
@if (manualKeywords().length > 0) {
<mat-chip-listbox
multiple
dense
[value]="selectedManualKeywords()"
(change)="onCategoryChange('manual', $event)">
@for (keyword of manualKeywords(); track keyword) {
<mat-chip-option
[value]="keyword"
class="compact-chip manual-chip"
>{{ keyword }}</mat-chip-option
>
}
</mat-chip-listbox>
} @else {
<p class="empty-state">Keine manuell hinzugefügten Keywords.</p>
}
</div>
</mat-card-content>
</mat-card>
</div>
<!-- NEW: Search Button -->
<div class="search-container">
<button
mat-flat-button
color="primary"
[disabled]="isSearchDisabled()"
(click)="search()">
<mat-icon>search</mat-icon>
Suchen
</button>
</div>
</div>
@@ -0,0 +1,244 @@
.content {
display: flex;
flex-direction: column;
gap: 0.75rem;
padding: 1rem;
}
.tab-content {
padding: 0.5rem 0;
}
.full-width {
width: 100%;
}
.keyword-input-row {
display: flex;
align-items: flex-start;
gap: 0.75rem;
}
.actions {
display: flex;
justify-content: flex-end;
}
.extraction-grid {
display: grid;
grid-template-columns: 1fr;
gap: 1rem;
}
.keyword-card {
background-color: var(--sg-background);
padding: 0.5rem;
.mat-card-header {
padding: 0 0 0.5rem 0;
}
.mat-card-content {
padding: 0;
}
}
.category-grid {
display: grid;
grid-template-columns: 1fr;
gap: 0.75rem 1.5rem;
}
.category-section {
h4 {
margin: 0 0 0.25rem 0;
font-weight: 500;
color: var(--sg-text-secondary);
font-size: 0.75rem;
text-transform: uppercase;
letter-spacing: 0.05em;
}
mat-chip-listbox {
width: 100%;
}
}
.compact-chip {
font-size: 0.8rem;
padding: 0.2rem 0.6rem;
min-height: 28px;
line-height: 1.2;
}
::ng-deep .mat-mdc-chip-option.compact-chip {
.mat-mdc-chip-action-label {
padding: 0 4px;
}
.mat-mdc-chip-action {
padding: 0 4px;
}
}
/* Selected keywords buttons */
.selected-keywords {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.selected-keyword {
display: inline-flex;
align-items: center;
gap: 0.15rem;
font-size: 0.8rem;
padding: 0.2rem 0.6rem;
min-height: 28px;
.mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
line-height: 18px;
}
}
.section-title {
margin: 0.5rem 0 0.25rem 0;
font-size: 1rem;
font-weight: 500;
color: var(--sg-text-primary);
}
.extracted-section,
.manual-section {
margin-bottom: 0.5rem;
}
.manual-section {
margin-top: 0.5rem;
}
.mat-divider {
margin: 0.5rem 0;
}
.select-all-container {
display: flex;
justify-content: flex-end;
margin-top: 0.5rem;
button {
font-size: 0.75rem;
padding: 0 12px;
line-height: 30px;
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
}
}
}
.select-all-container {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
justify-content: flex-end;
margin-top: 0.5rem;
button {
font-size: 0.75rem;
padding: 0 12px;
line-height: 30px;
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
}
}
}
.empty-state {
color: var(--sg-text-secondary);
margin: 0;
font-size: 0.9rem;
padding: 0.5rem 0;
}
/* NEW: Search button container */
.search-container {
display: flex;
justify-content: flex-end;
margin-top: 0.5rem;
}
/* Responsive: stack on small screens */
@media (max-width: 768px) {
.extraction-grid {
grid-template-columns: 1fr;
}
.category-grid {
grid-template-columns: 1fr;
gap: 0.75rem;
}
.keyword-input-row {
flex-direction: column;
}
.actions {
justify-content: flex-start;
}
.search-container {
justify-content: flex-start;
}
}
/* Source expansion panel */
.source-expansion {
margin: 0.75rem 0;
background: var(--sg-background-muted, #f5f5f5);
border-radius: 4px;
border-left: 4px solid var(--sg-primary, #1976d2);
::ng-deep .mat-expansion-panel-header {
padding: 0.5rem 0.75rem;
height: auto;
min-height: 36px;
font-size: 1rem;
text-transform: uppercase;
color: var(--sg-text-secondary);
letter-spacing: 0.05em;
.mat-expansion-panel-header-title {
font-size: 0.8rem;
font-weight: 500;
color: inherit;
}
.mat-expansion-indicator {
margin-left: 0.5rem;
}
}
::ng-deep .mat-expansion-panel-content {
font-size: 0.85rem;
line-height: 1.5;
color: var(--sg-text-primary);
}
::ng-deep .mat-expansion-panel-body {
padding: 0 0.75rem 0.75rem 0.75rem;
max-height: 120px; // scrollable if content is long
overflow-y: auto;
white-space: pre-wrap; // preserve line breaks
word-break: break-word;
}
// Remove the default Material box-shadow for a cleaner outline look
::ng-deep .mat-expansion-panel {
box-shadow: none !important;
background: transparent;
}
// Ripple effect on header – keep it subtle
::ng-deep .mat-expansion-panel-header:hover {
background: rgba(0, 0, 0, 0.03);
}
}
@@ -0,0 +1,427 @@
import { Component, signal, computed } from '@angular/core';
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 { MatChipListboxChange, MatChipsModule } from '@angular/material/chips';
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 { KeywordsService } from '../../api/api/keywords.service';
import { KeywordsRequest } from '../../api/model/keywordsRequest';
import { MatExpansionModule } from '@angular/material/expansion';
type InputMode = 'url' | 'text' | 'keywords';
@Component({
selector: 'app-keywords-search',
imports: [
ReactiveFormsModule,
MatTabsModule,
MatFormFieldModule,
MatInputModule,
MatButtonModule,
MatIconModule,
MatChipsModule,
MatDividerModule,
MatCardModule,
MatExpansionModule,
],
templateUrl: './keywords-search.component.html',
styleUrl: './keywords-search.component.scss',
})
export class KeywordsSearchComponent {
readonly form = this.formBuilder.nonNullable.group({
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[]>([]);
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)),
);
readonly extractedKeywordsExist = computed(
() =>
this.broadKeywords().length > 0 ||
this.coarseKeywords().length > 0 ||
this.fineKeywords().length > 0,
);
readonly sourceContent = signal<string>('');
readonly sourceUrl = signal<string | null>(null);
private isRestoringState = false;
constructor(
private readonly formBuilder: FormBuilder,
private readonly route: ActivatedRoute,
private readonly router: Router,
private readonly keywordsService: KeywordsService,
) {
this.route.queryParamMap.pipe(takeUntilDestroyed()).subscribe(() => {
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();
});
}
selectedTabIndex(): number {
const mode = this.form.controls.selectedInputType.value;
if (mode === 'text') return 1;
if (mode === 'keywords') return 2;
return 0;
}
onTabChange(index: number): void {
const nextMode: InputMode =
index === 1 ? 'text' : index === 2 ? 'keywords' : '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;
this.manualKeywords.set(
this.uniqueKeywords([...this.manualKeywords(), keyword]),
);
this.selectedKeywords.set(
this.uniqueKeywords([...this.selectedKeywords(), keyword]),
);
this.form.controls.keywordInput.setValue('');
this.updateQueryParams();
}
removeSelectedKeyword(keyword: string): void {
this.selectedKeywords.set(
this.selectedKeywords().filter((v) => v !== keyword),
);
this.updateQueryParams();
}
onCategoryChange(
category: 'broad' | 'coarse' | 'fine' | 'manual',
event: MatChipListboxChange,
): void {
const newSelection = (event.value as string[]) || [];
const otherCategories = ['broad', 'coarse', 'fine', 'manual'].filter(
(c) => c !== category,
);
const otherSelected = otherCategories.flatMap((c) => {
const keywords = this.getCategoryKeywords(c);
return this.selectedKeywords().filter((k) => keywords.includes(k));
});
const updated = [...otherSelected, ...newSelection];
this.selectedKeywords.set(this.uniqueKeywords(updated));
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(),
...this.broadKeywords(),
...this.coarseKeywords(),
...this.fineKeywords(),
];
this.selectedKeywords.set(this.uniqueKeywords(all));
this.updateQueryParams();
}
deselectAllExtracted(): void {
const manual = this.selectedManualKeywords();
this.selectedKeywords.set(this.uniqueKeywords(manual));
this.updateQueryParams();
}
clearExtractedKeywords(): void {
this.broadKeywords.set([]);
this.coarseKeywords.set([]);
this.fineKeywords.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(
this.selectedKeywords().filter((k) => manualSet.has(k)),
);
// Reset the extraction source (no extracted keywords left)
this.extractionSource.set(null);
this.updateQueryParams();
}
areAllExtractedSelected(): boolean {
const allExtracted = [
...this.broadKeywords(),
...this.coarseKeywords(),
...this.fineKeywords(),
];
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();
}
extractKeywords(): void {
const query = this.getCurrentExtractionQuery();
if (!query) return;
const currentMode = this.form.controls.selectedInputType.value;
const keywordsRequest: KeywordsRequest = {
query: query,
mode: currentMode,
limit: undefined,
};
this.isExtracting.set(true);
this.keywordsService.extractKeywords(keywordsRequest).subscribe({
next: ({ results, source, source_content, source_url }) => {
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.sourceContent.set(source_content);
this.extractionSource.set(source as InputMode);
this.sourceUrl.set(source_url ?? '');
this.saveSourceToSession();
console.log('Extracted keywords:', {
broad,
coarse,
fine,
manual: this.manualKeywords(),
});
// Keep only selected keywords that still exist in any category (including manual)
const allExtracted = [
...broad,
...coarse,
...fine,
...this.manualKeywords(),
];
this.selectedKeywords.set(
this.selectedKeywords().filter((k) => allExtracted.includes(k)),
);
this.updateQueryParams();
},
error: () => {
this.broadKeywords.set([]);
this.coarseKeywords.set([]);
this.fineKeywords.set([]);
// 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();
},
complete: () => {
this.isExtracting.set(false);
},
});
}
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(',') } });
}
private extractKeywordStrings(items: any[] | undefined): string[] {
return this.uniqueKeywords(
(items ?? []).map((kw) => kw.keyword?.trim() ?? '').filter((kw) => !!kw),
);
}
// State restoration from URL
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,
},
{ 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();
this.isRestoringState = false;
}
// Update URL query params
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),
broad: this.serializeKeywords(this.broadKeywords()),
coarse: this.serializeKeywords(this.coarseKeywords()),
fine: this.serializeKeywords(this.fineKeywords()),
manual: this.serializeKeywords(this.manualKeywords()),
selected: this.serializeKeywords(this.selectedKeywords()),
};
this.router.navigate([], {
relativeTo: this.route,
queryParams,
queryParamsHandling: 'merge',
replaceUrl: true,
});
}
// Save to sessionStorage
private saveSourceToSession(): void {
const data = {
source: this.extractionSource(),
sourceContent: this.sourceContent(),
sourceUrl: this.sourceUrl(),
};
sessionStorage.setItem(this.SESSION_KEY, JSON.stringify(data));
}
// Restore from sessionStorage
private restoreSourceFromSession(): void {
const raw = sessionStorage.getItem(this.SESSION_KEY);
if (!raw) return;
try {
const { source, sourceContent, sourceUrl } = JSON.parse(raw);
this.extractionSource.set(source as InputMode);
this.sourceContent.set(sourceContent ?? '');
this.sourceUrl.set(sourceUrl ?? null);
} 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();
if (mode === 'text') return this.form.controls.textInput.value.trim();
return this.selectedKeywords().join(', ').trim();
}
private parseMode(mode: string | null): InputMode {
if (mode === 'text' || mode === 'keywords') return mode;
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[] {
return Array.from(new Set(values.map((v) => v.trim()).filter(Boolean)));
}
private toNullableParam(value: string): string | null {
const normalized = value.trim();
return normalized.length ? normalized : null;
}
}