used sessionStorage for keywords handoff from keywords extraction to search results

This commit is contained in:
2026-07-08 12:53:26 +02:00
parent 87b7e207e3
commit 9be024bb13
2 changed files with 86 additions and 21 deletions
@@ -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()),
),
@@ -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;
}