feature/keywords-analysis #200

Merged
genja merged 4 commits from feature/keywords-analysis into dev 2026-07-08 12:57:48 +02:00
12 changed files with 443 additions and 24 deletions
+4
View File
@@ -27,6 +27,8 @@ import { organizationsOrganizationsResolver } from './resolvers/organizations-or
import { KeywordsToPersonsResultsComponent } from './modules/keywords-search/search-results/persons-results/persons-results.component';
import { KeywordsToProjectsResultsComponent } from './modules/keywords-search/search-results/projects-results/projects-results.component';
import { KeywordsToPatentsResultsComponent } from './modules/keywords-search/search-results/patents-results/patents-results.component';
import { KeywordsToNewsResultsComponent } from './modules/keywords-search/search-results/news-results/news-results.component';
import { KeywordsToWorksResultsComponent } from './modules/keywords-search/search-results/works-results/works-results.component';
export const routes: Routes = [
{
path: '',
@@ -116,6 +118,8 @@ export const routes: Routes = [
{ path: 'persons', component: KeywordsToPersonsResultsComponent },
{ path: 'projects', component: KeywordsToProjectsResultsComponent },
{ path: 'patents', component: KeywordsToPatentsResultsComponent },
{ path: 'works', component: KeywordsToWorksResultsComponent },
{ path: 'news', component: KeywordsToNewsResultsComponent },
],
},
{
@@ -48,6 +48,7 @@ import {
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';
type InputMode = 'url' | 'text';
type KeywordCategory = 'broad' | 'coarse' | 'fine' | 'manual';
type KeywordView = 'llm' | 'topic';
@@ -96,6 +97,8 @@ export class KeywordsSearchComponent {
});
private readonly SESSION_KEY = 'keywords-search-source';
private readonly SEARCH_RESULTS_HANDOFF_KEY = 'search-results-handoff';
// in component class:
private breakpointObserver = inject(BreakpointObserver);
@@ -239,13 +242,13 @@ export class KeywordsSearchComponent {
.getMessages()
.subscribe((event: WsEvent) => this.handleWsEvent(event));
this.destroyRef.onDestroy(() => {
this.websocketService.close();
const isReload = this.router.lastSuccessfulNavigation === null;
if (!isReload) {
this.clearStateFromSession();
}
});
// this.destroyRef.onDestroy(() => {
// this.websocketService.close();
// const isReload = this.router.lastSuccessfulNavigation === null;
// if (!isReload) {
// this.clearStateFromSession();
// }
// });
}
// --- Websocket event handling ---------------------------------------
@@ -605,7 +608,8 @@ export class KeywordsSearchComponent {
search(): void {
this.showVisualization.set(false);
const payload = {
const payload: SearchResultsPayload = {
extractedKeywords: this.getSelectedExtractedKeywordEntries(),
manualKeywords: this.getSelectedManualKeywordEntries(),
keywords: this.selectedKeywords(),
@@ -614,8 +618,24 @@ export class KeywordsSearchComponent {
},
};
console.log('searching for keywords:', payload);
this.router.navigate(['keywords/search-results'], { state: payload });
// 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),
softSearch: payload.options.softSearch ? true : false,
},
});
}
visualize(): void {
@@ -814,7 +834,7 @@ export class KeywordsSearchComponent {
const view = queryParams.get('view') ?? 'llm';
const legend = queryParams.get('legend') ?? 'on';
const legendExpanded = queryParams.get('legendExpanded') ?? 'off';
const softSearch = queryParams.get('softSearch') === 'on';
const softSearch = queryParams.get('softSearch') === 'true';
this.isRestoringState = true;
this.form.patchValue(
@@ -897,7 +917,7 @@ export class KeywordsSearchComponent {
view: this.keywordView(),
legend: this.subfieldLegendVisible() ? 'on' : 'off',
legendExpanded: this.subfieldLegendExpanded() ? 'on' : 'off',
softSearch: this.topicMappingSearch() ? 'on' : 'off',
softSearch: this.topicMappingSearch() ? true : false,
broad: this.serializeKeywords(
this.getKeywordLabels(this.broadKeywords()),
),
@@ -0,0 +1,31 @@
<div class="result-layout">
<mat-card class="results-card">
<mat-card-content class="results-placeholder">
<mat-icon>groups</mat-icon>
<h2>Newsliste</h2>
<p>
Die aktuelle Gewichtung ist unter <code>normalized</code> verfügbar.
</p>
</mat-card-content>
</mat-card>
<mat-card class="weights-card">
<mat-card-content>
<app-weights-sliders
[options]="weightOptions"
[initialWeights]="defaultWeights"
title="News-Gewichtung"
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
resetLabel="Ausgewogen"
applyLabel="Neu gewichten"
normalizedTitle="Normalisiert"
queryParamPrefix="newsW_"
[persistInQueryParams]="true"
[showApplyButton]="true"
[showResetButton]="true"
[showNormalizedPreview]="true"
(weightsChange)="onWeightsChange($event)"
(applyWeights)="onApplyWeights($event)" />
</mat-card-content>
</mat-card>
</div>
@@ -0,0 +1,29 @@
/* ============================================================
RESULT LAYOUT
============================================================ */
.result-layout {
display: grid;
grid-template-columns: minmax(300px, 420px) 1fr;
grid-template-areas: 'summary results';
gap: 0.75rem;
align-items: start;
}
.search-summary-card {
grid-area: summary;
}
.results-card {
grid-area: results;
}
.search-summary-card,
.results-card {
background: var(--sg-surface, #ffffff);
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
box-shadow: none;
.mat-mdc-card-content {
padding: 0.75rem;
}
}
@@ -0,0 +1,115 @@
import { Component, inject, signal } from '@angular/core';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import {
WeightMap,
WeightSliderOption,
WeightsSlidersComponent,
WeightsSlidersValue,
} from '../../../../shared/ui/weights-sliders/weights-sliders.component';
import { SearchResultsStateService } from '../search-results-state.service';
@Component({
selector: 'app-news-results',
imports: [MatCardModule, MatIconModule, WeightsSlidersComponent],
templateUrl: './news-results.component.html',
styleUrl: './news-results.component.scss',
})
export class KeywordsToNewsResultsComponent {
// injects the state set by the parent route — no duplicate parsing here
private readonly state = inject(SearchResultsStateService);
readonly defaultWeights: WeightMap = {
param1: 0.33,
param2: 0.33,
param3: 0.34,
};
readonly weightOptions: WeightSliderOption[] = [
{
key: 'param1',
label: 'Parameter 1',
icon: 'workspace_premium',
description: 'Gewichtet Parameter 1.',
defaultValue: 0.5,
queryParamName: 'wParam1',
},
{
key: 'param2',
label: 'Parameter 2',
icon: 'workspace_premium',
description: 'Gewichtet Parameter 2.',
defaultValue: 0.5,
queryParamName: 'wParam2',
},
{
key: 'param3',
label: 'Parameter 3',
icon: 'workspace_premium',
description: 'Gewichtet Parameter 3.',
defaultValue: 0.5,
queryParamName: 'wParam3',
},
];
readonly currentWeights = signal<WeightsSlidersValue>({
raw: this.defaultWeights,
normalized: {
param1: 0.33,
param2: 0.33,
param3: 0.34,
},
rawSum: 2.5,
normalizedSum: 1,
valid: true,
});
readonly projects = signal<unknown[]>([]); // placeholder until the results service lands
private hasLoadedInitial = false;
constructor() {
console.log('check', this.state.payload());
}
onWeightsChange(value: WeightsSlidersValue): void {
this.currentWeights.set(value);
// fires once with the query-param-aware initial state — use it to load
if (!this.hasLoadedInitial) {
this.hasLoadedInitial = true;
this.loadprojects();
}
}
onApplyWeights(value: WeightsSlidersValue): void {
this.currentWeights.set(value);
this.loadprojects();
}
private loadprojects(): void {
const weights = this.currentWeights();
const requestPayload = {
manualKeywords: this.state.manualKeywords(),
extractedKeywords: this.state.extractedKeywords(),
keywords: this.state.keywords(),
softSearch: this.state.softSearch(),
weights: {
raw: weights.raw,
normalized: weights.normalized,
},
};
console.log(requestPayload);
/**
* TODO:
* this.projectsService.searchprojects(requestPayload).subscribe({
* next: results => this.projects.set(results),
* error: error => console.error(error),
* });
*/
}
}
@@ -19,7 +19,7 @@
resetLabel="Ausgewogen"
applyLabel="Neu gewichten"
normalizedTitle="Normalisiert"
queryParamPrefix="personW_"
queryParamPrefix="patentW_"
[persistInQueryParams]="true"
[showApplyButton]="true"
[showResetButton]="true"
@@ -19,7 +19,7 @@
resetLabel="Ausgewogen"
applyLabel="Neu gewichten"
normalizedTitle="Normalisiert"
queryParamPrefix="ProjectW_"
queryParamPrefix="projectW_"
[persistInQueryParams]="true"
[showApplyButton]="true"
[showResetButton]="true"
@@ -52,7 +52,11 @@
[routerLink]="route.path"
routerLinkActive
#rla="routerLinkActive"
[active]="rla.isActive">
[active]="rla.isActive"
[queryParams]="{
keywords: state.payload()?.keywords?.join(','),
softSearch: state.payload()?.options?.softSearch,
}">
<mat-icon>{{ route.icon }}</mat-icon>
{{ route.label }}
</a>
@@ -1,5 +1,7 @@
import { Component, computed, inject } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import {
ActivatedRoute,
Router,
RouterLink,
RouterLinkActive,
@@ -36,21 +38,26 @@ import {
TopicChipComponent,
MatTabsModule,
],
// Scoped to this component's route subtree: created on entering /results,
// destroyed on leaving it entirely — survives switching persons/projects/patents.
providers: [SearchResultsStateService],
templateUrl: './search-results.component.html',
styleUrl: './search-results.component.scss',
})
export class KeywordsSearchResultsComponent {
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
protected readonly state = inject(SearchResultsStateService);
// Must match KeywordsSearchComponent.SEARCH_RESULTS_HANDOFF_KEY exactly —
// that's where search() writes the enriched entries before navigating.
private readonly HANDOFF_KEY = 'search-results-handoff';
protected readonly childRoutes = [
{ path: 'persons', label: 'Personen', icon: 'groups' },
{ path: 'projects', label: 'Projekte', icon: 'account_tree' },
{ path: 'projects', label: 'Projekte', icon: 'work' },
{ path: 'patents', label: 'Patente', icon: 'workspace_premium' },
{ path: 'works', label: 'Publikationen', icon: 'article' },
{ path: 'news', label: 'Nachrichten', icon: 'newspaper' },
];
readonly selectedKeywordCount = computed(() => this.state.keywords().length);
@@ -105,14 +112,26 @@ export class KeywordsSearchResultsComponent {
});
constructor() {
const navigationState =
this.router.currentNavigation()?.extras.state ?? window.history.state;
// Query params are authoritative (URL survives reload, deep links,
// browser back/forward). sessionStorage is a best-effort cache for the
// heavier, topic-enriched entries — only trusted if its keyword set
// still matches what's in the URL right now, so a stale cache from a
// previous search never gets silently applied to a new one.
this.route.queryParamMap.pipe(takeUntilDestroyed()).subscribe((params) => {
const keywords = this.parseKeywordList(params.get('keywords'));
const softSearch = params.get('softSearch') === 'on';
const restoredPayload = this.parsePayload(navigationState);
const cached = this.readHandoffCache();
const cacheMatches =
cached && this.sameKeywordSet(cached.keywords, keywords);
if (restoredPayload) {
this.state.setPayload(restoredPayload);
}
this.state.setPayload({
keywords,
options: { softSearch },
extractedKeywords: cacheMatches ? cached!.extractedKeywords : [],
manualKeywords: cacheMatches ? cached!.manualKeywords : [],
});
});
}
goBackToSearch(): void {
@@ -160,6 +179,18 @@ export class KeywordsSearchResultsComponent {
return this.getKeywordLabel(entry);
}
private readHandoffCache(): SearchResultsPayload | null {
const raw = sessionStorage.getItem(this.HANDOFF_KEY);
if (!raw) return null;
try {
return this.parsePayload(JSON.parse(raw));
} catch {
sessionStorage.removeItem(this.HANDOFF_KEY);
return null;
}
}
private parsePayload(value: unknown): SearchResultsPayload | null {
if (!value || typeof value !== 'object') return null;
@@ -177,6 +208,20 @@ export class KeywordsSearchResultsComponent {
};
}
private sameKeywordSet(a: string[], b: string[]): boolean {
if (a.length !== b.length) return false;
const setA = new Set(a.map((k) => this.normalizeKeyword(k)));
return b.every((k) => setA.has(this.normalizeKeyword(k)));
}
private parseKeywordList(raw: string | null): string[] {
if (!raw) return [];
return raw
.split(',')
.map((v) => v.trim())
.filter(Boolean);
}
private getKeywordLabel(item: KeywordEntryWithTopic): string {
return item.llm_keyword.keyword;
}
@@ -0,0 +1,31 @@
<div class="result-layout">
<mat-card class="results-card">
<mat-card-content class="results-placeholder">
<mat-icon>groups</mat-icon>
<h2>Publikationsliste</h2>
<p>
Die aktuelle Gewichtung ist unter <code>normalized</code> verfügbar.
</p>
</mat-card-content>
</mat-card>
<mat-card class="weights-card">
<mat-card-content>
<app-weights-sliders
[options]="weightOptions"
[initialWeights]="defaultWeights"
title="Publikations-Gewichtung"
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
resetLabel="Ausgewogen"
applyLabel="Neu gewichten"
normalizedTitle="Normalisiert"
queryParamPrefix="workW_"
[persistInQueryParams]="true"
[showApplyButton]="true"
[showResetButton]="true"
[showNormalizedPreview]="true"
(weightsChange)="onWeightsChange($event)"
(applyWeights)="onApplyWeights($event)" />
</mat-card-content>
</mat-card>
</div>
@@ -0,0 +1,29 @@
/* ============================================================
RESULT LAYOUT
============================================================ */
.result-layout {
display: grid;
grid-template-columns: minmax(300px, 420px) 1fr;
grid-template-areas: 'summary results';
gap: 0.75rem;
align-items: start;
}
.search-summary-card {
grid-area: summary;
}
.results-card {
grid-area: results;
}
.search-summary-card,
.results-card {
background: var(--sg-surface, #ffffff);
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
box-shadow: none;
.mat-mdc-card-content {
padding: 0.75rem;
}
}
@@ -0,0 +1,111 @@
import { Component, inject, signal } from '@angular/core';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import {
WeightMap,
WeightSliderOption,
WeightsSlidersComponent,
WeightsSlidersValue,
} from '../../../../shared/ui/weights-sliders/weights-sliders.component';
import { SearchResultsStateService } from '../search-results-state.service';
@Component({
selector: 'app-works-results',
imports: [MatCardModule, MatIconModule, WeightsSlidersComponent],
templateUrl: './works-results.component.html',
styleUrl: './works-results.component.scss',
})
export class KeywordsToWorksResultsComponent {
// injects the state set by the parent route — no duplicate parsing here
private readonly state = inject(SearchResultsStateService);
readonly defaultWeights: WeightMap = {
param1: 0.33,
param2: 0.33,
param3: 0.34,
};
readonly weightOptions: WeightSliderOption[] = [
{
key: 'param1',
label: 'Parameter 1',
icon: 'workspace_premium',
description: 'Gewichtet Parameter 1.',
defaultValue: 0.5,
queryParamName: 'wParam1',
},
{
key: 'param2',
label: 'Parameter 2',
icon: 'workspace_premium',
description: 'Gewichtet Parameter 2.',
defaultValue: 0.5,
queryParamName: 'wParam2',
},
{
key: 'param3',
label: 'Parameter 3',
icon: 'workspace_premium',
description: 'Gewichtet Parameter 3.',
defaultValue: 0.5,
queryParamName: 'wParam3',
},
];
readonly currentWeights = signal<WeightsSlidersValue>({
raw: this.defaultWeights,
normalized: {
param1: 0.33,
param2: 0.33,
param3: 0.34,
},
rawSum: 2.5,
normalizedSum: 1,
valid: true,
});
readonly works = signal<unknown[]>([]); // placeholder until the results service lands
private hasLoadedInitial = false;
onWeightsChange(value: WeightsSlidersValue): void {
this.currentWeights.set(value);
// fires once with the query-param-aware initial state — use it to load
if (!this.hasLoadedInitial) {
this.hasLoadedInitial = true;
this.loadworks();
}
}
onApplyWeights(value: WeightsSlidersValue): void {
this.currentWeights.set(value);
this.loadworks();
}
private loadworks(): void {
const weights = this.currentWeights();
const requestPayload = {
manualKeywords: this.state.manualKeywords(),
extractedKeywords: this.state.extractedKeywords(),
keywords: this.state.keywords(),
softSearch: this.state.softSearch(),
weights: {
raw: weights.raw,
normalized: weights.normalized,
},
};
console.log(requestPayload);
/**
* TODO:
* this.worksService.searchworks(requestPayload).subscribe({
* next: results => this.works.set(results),
* error: error => console.error(error),
* });
*/
}
}