feature/keywords-analysis #199

Merged
genja merged 9 commits from feature/keywords-analysis into dev 2026-07-08 03:36:22 +02:00
23 changed files with 1951 additions and 56 deletions
+16 -1
View File
@@ -24,7 +24,9 @@ import { accountViewerGuard } from './shared/guards/account-viewer.guard';
import { accountsPageResolver } from './resolvers/accounts-page.resolver';
import { accountsOrganizationResolver } from './resolvers/accounts-organizations.resolver';
import { organizationsOrganizationsResolver } from './resolvers/organizations-organizations.resolver';
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';
export const routes: Routes = [
{
path: '',
@@ -103,6 +105,19 @@ export const routes: Routes = [
(mod) => mod.KeywordsSearchComponent,
),
},
{
path: 'keywords/search-results',
loadComponent: () =>
import('./modules/keywords-search/search-results/search-results.component').then(
(mod) => mod.KeywordsSearchResultsComponent,
),
children: [
{ path: '', pathMatch: 'full', redirectTo: 'persons' },
{ path: 'persons', component: KeywordsToPersonsResultsComponent },
{ path: 'projects', component: KeywordsToProjectsResultsComponent },
{ path: 'patents', component: KeywordsToPatentsResultsComponent },
],
},
{
path: 'news',
canActivate: [userGuard],
@@ -99,9 +99,17 @@
<span>Alle auswählen</span>
</button>
}
<button
mat-stroked-button
color="warn"
[disabled]="isExtracting()"
(click)="clearKeywords()"
matTooltip="Alle extrahierten Keywords löschen">
<mat-icon>delete_outline</mat-icon>
<span>Alle löschen</span>
</button>
</div>
<div class="toolbar-divider"></div>
<mat-button-toggle-group
[value]="keywordView()"
(change)="onViewToggleChange($event.value)"
@@ -113,26 +121,26 @@
<mat-icon>text_fields</mat-icon>
<span>Extrahierte Keywords</span>
</mat-button-toggle>
<mat-button-toggle
[disabled]="isExtracting()"
value="topic"
matTooltip="Topic Mapping">
<mat-icon>account_tree</mat-icon>
<span>Topic Mapping</span>
</mat-button-toggle>
@if (topicMappingSearch()) {
<mat-button-toggle
[disabled]="isExtracting()"
value="topic"
matTooltip="Topic Mapping">
<mat-icon>account_tree</mat-icon>
<span>Topic Mapping</span>
</mat-button-toggle>
}
</mat-button-toggle-group>
<div class="toolbar-divider"></div>
<div class="toolbar-group toolbar-group--view">
<button
mat-stroked-button
color="warn"
[disabled]="isExtracting()"
(click)="clearKeywords()"
matTooltip="Alle extrahierten Keywords löschen">
<mat-icon>delete_outline</mat-icon>
<span>Alle löschen</span>
</button>
<mat-slide-toggle
(change)="onToggleTopicMappingSearch($event)"
labelPosition="before"
[checked]="topicMappingSearch()"
class="mapping-toggle">
Topic Mapping
</mat-slide-toggle>
</div>
</div>
@@ -366,8 +374,8 @@
</div>
@if (keywordsExist()) {
<!-- Search Buttons -->
<div class="search-container" style="display: flex; gap: 1rem">
<!-- Search buttons -->
<div class="search-actions">
<button
mat-flat-button
color="primary"
@@ -377,6 +385,7 @@
<mat-icon>search</mat-icon>
Suchen
</button>
<button
mat-flat-button
color="accent"
@@ -60,10 +60,8 @@ $touch-target: 44px;
.toolbar-controls {
display: flex;
align-items: center;
justify-content: center;
justify-content: space-around;
gap: 0.75rem;
flex-wrap: nowrap; /* fixed: was invalid "no-wrap" */
padding: 0.5rem 0.75rem;
background: var(--sg-background-muted, #f4f5f7);
}
@@ -83,6 +81,25 @@ $touch-target: 44px;
.manual-input-controls {
min-width: 0;
}
.toolbar-group {
display: flex;
justify-content: space-around;
gap: auto;
::ng-deep .mdc-switch {
position: relative;
width: 100%;
}
::ng-deep .mdc-form-field {
position: relative;
min-width: 90px;
font-size: 0.8rem;
}
::ng-deep .mdc-label {
position: absolute;
top: 30px;
}
}
@container keyword-tool (max-width: #{$tablet}) {
.toolbar-wrapper {
@@ -97,8 +114,10 @@ $touch-target: 44px;
.toolbar-group {
display: flex;
justify-content: center;
gap: 0.5rem;
flex-wrap: nowrap; /* fixed: was invalid "no-wrap" */
align-items: center;
gap: 0.6rem;
}
.toolbar-group button {
@@ -268,6 +287,10 @@ mat-button-toggle-group {
width: 100%;
opacity: 0.4;
}
::ng-deep app-topic-chip .topic-chip__count {
display: none;
}
}
.thick-border {
@@ -416,33 +439,68 @@ mat-button-toggle-group {
opacity: 0.6;
}
}
/* ============================================================
SEARCH BUTTON (sticky on mobile — improves conversion/UX)
SEARCH BUTTONS
============================================================ */
.search-container {
display: flex;
justify-content: center;
margin-top: 0.5rem;
align-items: center;
gap: 1rem;
margin-top: 1rem;
padding: 0 1rem;
}
.search-btn {
min-width: 240px;
align-self: center;
.search-actions {
display: flex;
justify-content: center;
align-items: center;
gap: 0.75rem;
}
.search-btn,
.visualize-btn {
min-width: 220px;
min-height: $touch-target;
align-self: center;
white-space: nowrap;
}
/* Tablet */
@media (max-width: $tablet) {
.search-container {
padding: 0;
}
.search-actions {
width: 100%;
}
.search-btn,
.visualize-btn {
width: 100%;
}
}
/* Phone */
@media (max-width: $phone) {
.search-container {
position: sticky;
bottom: 0;
z-index: 5;
background: var(--sg-background);
background: var(--sg-background, #fff);
padding: 0.75rem 0.5rem;
margin-top: 0.75rem;
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.08);
}
.search-btn {
.search-actions {
flex-direction: column;
width: 100%;
}
.search-btn,
.visualize-btn {
width: 100%;
}
}
@@ -28,8 +28,10 @@ import { TopicChipComponent } from '../../shared/ui/topic-chip/topic-chip.compon
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 {
MatButtonToggleModule,
MatButtonToggleGroup,
@@ -72,6 +74,8 @@ type KeywordView = 'llm' | 'topic';
A11yModule,
NgTemplateOutlet,
LoadingComponent,
MatSlideToggleModule,
MatSliderModule,
],
templateUrl: './keywords-search.component.html',
styleUrl: './keywords-search.component.scss',
@@ -118,6 +122,7 @@ export class KeywordsSearchComponent {
readonly loadingNewKeyword = signal(false);
readonly extractionSource = signal<InputMode | null>(null);
readonly showVisualization = signal<boolean>(false);
readonly topicMappingSearch = signal<boolean>(false);
readonly keywordsExist = computed(
() =>
@@ -160,7 +165,7 @@ export class KeywordsSearchComponent {
.replace(/>/g, '&gt;');
// Create the replacement span HTML
const replacement = `<span style="background-color: color-mix(in srgb, ${color} 27%, #ffffff); 100%); font-weight: bold;" title="Keyword: ${keyword}">${escapedKeyword}</span>`;
const replacement = `<span style="text-decoration: underline; background-color: color-mix(in srgb, ${color} 27%, #ffffff); 100%); font-weight: bold;" title="Keyword: ${keyword}">${escapedKeyword}</span>`;
const escapedRegexKeyword = keyword.replace(
/[.*+?^${}()|[\]\\]/g,
@@ -212,9 +217,6 @@ export class KeywordsSearchComponent {
constructor() {
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;
}
@@ -237,13 +239,11 @@ export class KeywordsSearchComponent {
.getMessages()
.subscribe((event: WsEvent) => this.handleWsEvent(event));
// 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 isReload = this.router.lastSuccessfulNavigation === null;
if (!isReload) {
this.clearSourceFromSession();
this.clearStateFromSession();
}
});
}
@@ -512,7 +512,7 @@ export class KeywordsSearchComponent {
this.extractionSource.set(null);
// updateQueryParams() persists this cleared state to sessionStorage too
// (see saveSourceToSession() call inside it), so there's no need to
// (see saveStateToSession() call inside it), so there's no need to
// separately wipe the session key here.
this.updateQueryParams();
}
@@ -564,7 +564,7 @@ export class KeywordsSearchComponent {
this.selectedKeywords().filter((k) => allExtracted.includes(k)),
);
// updateQueryParams() also calls saveSourceToSession() - no need to call
// updateQueryParams() also calls saveStateToSession() - no need to call
// it separately here.
this.updateQueryParams();
}
@@ -609,11 +609,13 @@ export class KeywordsSearchComponent {
extractedKeywords: this.getSelectedExtractedKeywordEntries(),
manualKeywords: this.getSelectedManualKeywordEntries(),
keywords: this.selectedKeywords(),
options: {
softSearch: this.topicMappingSearch(),
},
};
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 });
this.router.navigate(['keywords/search-results'], { state: payload });
}
visualize(): void {
@@ -672,14 +674,16 @@ export class KeywordsSearchComponent {
this.normalizeKeyword(this.getKeywordLabel(item)) !== normalized,
);
}
onViewToggleChange(value: KeywordView): void {
if (this.keywordView() !== value) {
this.keywordView.set(value);
}
this.updateQueryParams();
}
onToggleTopicMappingSearch(event: any): void {
this.topicMappingSearch.set(event.checked);
this.updateQueryParams();
}
onSubfieldLegendVisibleChange(visible: boolean): void {
this.subfieldLegendVisible.set(visible);
this.updateQueryParams();
@@ -810,18 +814,23 @@ 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';
this.isRestoringState = true;
this.form.patchValue(
{ selectedInputType: mode, urlInput, textInput },
{
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.restoreSourceFromSession();
this.topicMappingSearch.set(softSearch);
this.restoreStateFromSession();
const merged = this.uniqueKeywordEntries([
...this.manualKeywordEntries(), // session restored entries
@@ -859,7 +868,7 @@ export class KeywordsSearchComponent {
this.normalizeKeyword(k),
),
);
const validSelected = selected.filter(
const validSelected = [...this.selectedKeywords(), ...selected].filter(
(k) =>
manualKeywordSet.has(this.normalizeKeyword(k)) ||
broadKeywordSet.has(this.normalizeKeyword(k)) ||
@@ -888,6 +897,7 @@ export class KeywordsSearchComponent {
view: this.keywordView(),
legend: this.subfieldLegendVisible() ? 'on' : 'off',
legendExpanded: this.subfieldLegendExpanded() ? 'on' : 'off',
softSearch: this.topicMappingSearch() ? 'on' : 'off',
broad: this.serializeKeywords(
this.getKeywordLabels(this.broadKeywords()),
),
@@ -924,13 +934,13 @@ export class KeywordsSearchComponent {
// 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
// -> 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.saveSourceToSession();
this.saveStateToSession();
}
private saveSourceToSession(): void {
private saveStateToSession(): void {
const data = {
source: this.extractionSource(),
sourceContent: this.sourceContent(),
@@ -939,6 +949,7 @@ export class KeywordsSearchComponent {
coarseKeywordEntries: this.coarseKeywordEntries(),
fineKeywordEntries: this.fineKeywordEntries(),
manualKeywordEntries: this.manualKeywordEntries(),
selectedKeywords: this.selectedKeywords(),
};
try {
@@ -948,7 +959,7 @@ export class KeywordsSearchComponent {
}
}
private restoreSourceFromSession(): void {
private restoreStateFromSession(): void {
const raw = sessionStorage.getItem(this.SESSION_KEY);
if (!raw) return;
@@ -961,6 +972,7 @@ export class KeywordsSearchComponent {
coarseKeywordEntries,
fineKeywordEntries,
manualKeywordEntries,
selectedKeywords,
} = JSON.parse(raw);
this.extractionSource.set(source as InputMode);
@@ -970,12 +982,13 @@ export class KeywordsSearchComponent {
this.coarseKeywordEntries.set(coarseKeywordEntries ?? []);
this.fineKeywordEntries.set(fineKeywordEntries ?? []);
this.manualKeywordEntries.set(manualKeywordEntries ?? []);
this.selectedKeywords.set(selectedKeywords ?? []);
} catch {
sessionStorage.removeItem(this.SESSION_KEY);
}
}
private clearSourceFromSession(): void {
private clearStateFromSession(): void {
sessionStorage.removeItem(this.SESSION_KEY);
}
@@ -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>Patentenliste</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="Patenten-Gewichtung"
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
resetLabel="Ausgewogen"
applyLabel="Neu gewichten"
normalizedTitle="Normalisiert"
queryParamPrefix="personW_"
[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,112 @@
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-patents-results',
imports: [MatCardModule, MatIconModule, WeightsSlidersComponent],
templateUrl: './patents-results.component.html',
styleUrl: './patents-results.component.scss',
})
export class KeywordsToPatentsResultsComponent {
// 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;
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),
* });
*/
}
}
@@ -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>Personenliste</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="Personen-Gewichtung"
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
resetLabel="Ausgewogen"
applyLabel="Neu gewichten"
normalizedTitle="Normalisiert"
queryParamPrefix="personW_"
[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,135 @@
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-persons-results',
standalone: true,
imports: [MatCardModule, MatIconModule, WeightsSlidersComponent],
templateUrl: './persons-results.component.html',
styleUrl: './persons-results.component.scss',
})
export class KeywordsToPersonsResultsComponent {
// injects the state set by the parent route — no duplicate parsing here
private readonly state = inject(SearchResultsStateService);
readonly defaultWeights: WeightMap = {
publications: 0.5,
citations: 0.5,
patents: 0.5,
projects: 0.5,
mediaVisibility: 0.5,
};
readonly weightOptions: WeightSliderOption[] = [
{
key: 'publications',
label: 'Publikationen',
icon: 'article',
description:
'Gewichtet die Anzahl und Relevanz wissenschaftlicher Arbeiten.',
defaultValue: 0.5,
queryParamName: 'wPublications',
},
{
key: 'citations',
label: 'Zitationen',
icon: 'format_quote',
description: 'Gewichtet wissenschaftlichen Einfluss über Zitationen.',
defaultValue: 0.5,
queryParamName: 'wCitations',
},
{
key: 'patents',
label: 'Patente',
icon: 'workspace_premium',
description: 'Gewichtet Innovations- und Transferleistung.',
defaultValue: 0.5,
queryParamName: 'wPatents',
},
{
key: 'projects',
label: 'Projekte',
icon: 'account_tree',
description: 'Gewichtet Beteiligung an relevanten Forschungsprojekten.',
defaultValue: 0.5,
queryParamName: 'wProjects',
},
{
key: 'mediaVisibility',
label: 'Medien-Sichtbarkeit',
icon: 'visibility',
description: 'Gewichtet öffentliche und mediale Sichtbarkeit.',
defaultValue: 0.5,
queryParamName: 'wMedia',
},
];
readonly currentWeights = signal<WeightsSlidersValue>({
raw: this.defaultWeights,
normalized: {
publications: 0.2,
citations: 0.2,
patents: 0.2,
projects: 0.2,
mediaVisibility: 0.2,
},
rawSum: 2.5,
normalizedSum: 1,
valid: true,
});
readonly persons = 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.loadPersons();
}
}
onApplyWeights(value: WeightsSlidersValue): void {
this.currentWeights.set(value);
this.loadPersons();
}
private loadPersons(): 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.personsService.searchPersons(requestPayload).subscribe({
* next: results => this.persons.set(results),
* error: error => console.error(error),
* });
*/
}
}
@@ -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>Projectsliste</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="Projects-Gewichtung"
description="Werte zwischen 0 und 1. Summe wird normalisiert zu 1."
resetLabel="Ausgewogen"
applyLabel="Neu gewichten"
normalizedTitle="Normalisiert"
queryParamPrefix="ProjectW_"
[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-projects-results',
imports: [MatCardModule, MatIconModule, WeightsSlidersComponent],
templateUrl: './projects-results.component.html',
styleUrl: './projects-results.component.scss',
})
export class KeywordsToProjectsResultsComponent {
// 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;
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),
* });
*/
}
}
@@ -0,0 +1,44 @@
import { Injectable, computed, signal } from '@angular/core';
import { KeywordEntryWithTopic } from '../../../api/model/keywordEntryWithTopic';
export interface SearchResultsPayload {
extractedKeywords: KeywordEntryWithTopic[];
manualKeywords: KeywordEntryWithTopic[];
keywords: string[];
options: {
softSearch: boolean;
};
}
/**
* Provided at the parent route (KeywordsSearchResultsComponent) so it's
* created once when entering /search-results and destroyed when leaving it.
* Child routes (persons/projects/patents) inject it read-only to build
* their own search requests without re-deriving the keyword state.
*/
@Injectable()
export class SearchResultsStateService {
private readonly _payload = signal<SearchResultsPayload | null>(null);
readonly payload = this._payload.asReadonly();
readonly hasValidSearch = computed(() => {
const payload = this._payload();
return !!payload && payload.keywords.length > 0;
});
readonly keywords = computed(() => this._payload()?.keywords ?? []);
readonly softSearch = computed(
() => this._payload()?.options.softSearch ?? false,
);
readonly extractedKeywords = computed(
() => this._payload()?.extractedKeywords ?? [],
);
readonly manualKeywords = computed(
() => this._payload()?.manualKeywords ?? [],
);
setPayload(payload: SearchResultsPayload): void {
this._payload.set(payload);
}
}
@@ -0,0 +1,77 @@
<div class="search-results-page">
<div class="search-results-header">
<button mat-stroked-button color="primary" (click)="goBackToSearch()">
<mat-icon>arrow_back</mat-icon>
Keywords anpassen
</button>
</div>
@if (state.hasValidSearch()) {
<mat-card class="summary-card">
<mat-card-content>
<div class="summary-header">
<div>
<span class="summary-label">Suchprofil</span>
<span class="summary-count"
>{{ selectedKeywordCount() }} Keywords</span
>
</div>
<span class="mode-badge">
<mat-icon>account_tree</mat-icon>
{{ state.softSearch() ? 'Topic Mapping' : 'Keyword Matching' }}
</span>
</div>
<div class="keyword-stack">
@for (entry of selectedKeywordEntries(); track getEntryTrack(entry)) {
<app-topic-chip
[label]="getChipLabel(entry)"
[count]="getChipCount(entry)"
[description]="getChipDescription(entry)"
[subfieldName]="getChipSubfieldName(entry)"
[fieldName]="getChipFieldName(entry)"
[domainName]="getChipDomainName(entry)"
[color]="getTopicColor(entry.topic_mapping?.topic)"
[active]="true"
countIcon="article"
descriptionTooltipTarget="button" />
}
@for (keyword of missingKeywordLabels(); track keyword) {
<app-topic-chip
[label]="keyword"
[active]="true"
countIcon="article" />
}
</div>
</mat-card-content>
</mat-card>
<nav mat-tab-nav-bar [tabPanel]="resultTabPanel" class="result-nav">
@for (route of childRoutes; track route.path) {
<a
mat-tab-link
[routerLink]="route.path"
routerLinkActive
#rla="routerLinkActive"
[active]="rla.isActive">
<mat-icon>{{ route.icon }}</mat-icon>
{{ route.label }}
</a>
}
</nav>
<mat-tab-nav-panel #resultTabPanel>
<router-outlet />
</mat-tab-nav-panel>
} @else {
<mat-card class="empty-card">
<mat-card-content class="empty-state">
<mat-icon>manage_search</mat-icon>
<h2>Keine Suchdaten</h2>
<p>Starte eine neue Suche, um Ergebnisse zu sehen.</p>
<button mat-flat-button color="primary" (click)="goBackToSearch()">
Zur Suche
</button>
</mat-card-content>
</mat-card>
}
</div>
@@ -0,0 +1,209 @@
/* ============================================================
DESIGN TOKENS
============================================================ */
$phone: 599px;
$tablet: 900px;
$touch-target: 44px;
/* ============================================================
SEARCH RESULTS PAGE (parent shell)
============================================================ */
.search-results-page {
display: flex;
flex-direction: column;
gap: 0.75rem;
padding: 0.75rem 1rem;
}
.page-header {
display: flex;
align-items: flex-start;
gap: 0.75rem;
h1 {
margin: 0;
font-size: clamp(1.2rem, 2vw, 1.6rem);
font-weight: 650;
color: var(--sg-text-primary);
}
p {
margin: 0.2rem 0 0;
color: var(--sg-text-secondary);
font-size: 0.9rem;
}
}
/* ============================================================
KEYWORD SUMMARY CARD
============================================================ */
.summary-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;
}
}
.summary-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 0.5rem;
margin-bottom: 0.5rem;
}
.summary-label {
display: block;
font-size: 0.75rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.03em;
color: var(--sg-text-secondary);
}
.summary-count {
display: block;
margin-top: 0.15rem;
font-size: 0.95rem;
font-weight: 650;
color: var(--sg-text-primary);
}
.mode-badge {
display: inline-flex;
align-items: center;
gap: 0.25rem;
border-radius: 999px;
padding: 0.25rem 0.5rem;
background: var(--sg-background-muted, #f4f5f7);
color: var(--sg-text-secondary);
font-size: 0.75rem;
font-weight: 500;
mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
}
}
.keyword-stack {
display: flex;
flex-wrap: wrap;
gap: 0.6rem;
::ng-deep app-topic-chip .topic-chip__count {
display: none;
}
}
/* ============================================================
CHILD ROUTE NAV
============================================================ */
.result-nav {
display: flex;
gap: 0.25rem;
border-bottom: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
}
.result-nav__link {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.5rem 0.85rem;
border-radius: 6px 6px 0 0;
color: var(--sg-text-secondary);
text-decoration: none;
font-size: 0.85rem;
font-weight: 500;
border-bottom: 2px solid transparent;
transition:
color 0.15s ease,
border-color 0.15s ease;
mat-icon {
font-size: 18px;
width: 18px;
height: 18px;
}
&:hover {
color: var(--sg-text-primary);
}
&--active {
color: var(--sg-text-primary);
border-bottom-color: var(--sg-primary, currentColor);
}
}
/* ============================================================
EMPTY STATE
============================================================ */
.empty-card {
background: var(--sg-surface, #ffffff);
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
box-shadow: none;
}
.empty-state {
min-height: 240px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 0.5rem;
text-align: center;
color: var(--sg-text-secondary);
mat-icon {
font-size: 48px;
width: 48px;
height: 48px;
opacity: 0.65;
}
h2 {
margin: 0;
color: var(--sg-text-primary);
font-size: 1.1rem;
}
p {
margin: 0;
max-width: 480px;
line-height: 1.4;
}
button {
margin-top: 0.5rem;
min-height: $touch-target;
}
}
/* ============================================================
PHONE
============================================================ */
@media (max-width: $phone) {
.search-results-page {
padding: 0.5rem;
}
.summary-header {
flex-direction: column;
align-items: flex-start;
gap: 0.3rem;
}
.mode-badge {
width: 100%;
justify-content: center;
}
.result-nav {
overflow-x: auto;
}
}
@@ -0,0 +1,191 @@
import { Component, computed, inject } from '@angular/core';
import {
Router,
RouterLink,
RouterLinkActive,
RouterOutlet,
} from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatIconModule } from '@angular/material/icon';
import { KeywordEntryWithTopic } from '../../../api/model/keywordEntryWithTopic';
import { Topic } from '../../../api/model/topic';
import { TopicChipComponent } from '../../../shared/ui/topic-chip/topic-chip.component';
import {
topicHierarchyColor,
TopicHierarchyColorInput,
} from '../../../resolvers/utils/topic-colors';
import { MatTabsModule } from '@angular/material/tabs';
import {
SearchResultsPayload,
SearchResultsStateService,
} from './search-results-state.service';
@Component({
selector: 'app-keywords-search-results',
standalone: true,
imports: [
RouterLink,
RouterLinkActive,
RouterOutlet,
MatButtonModule,
MatCardModule,
MatIconModule,
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);
protected readonly state = inject(SearchResultsStateService);
protected readonly childRoutes = [
{ path: 'persons', label: 'Personen', icon: 'groups' },
{ path: 'projects', label: 'Projekte', icon: 'account_tree' },
{ path: 'patents', label: 'Patente', icon: 'workspace_premium' },
];
readonly selectedKeywordCount = computed(() => this.state.keywords().length);
readonly selectedKeywordEntries = computed(() => {
const payload = this.state.payload();
if (!payload) return [];
const allEntries = [
...(payload.extractedKeywords ?? []),
...(payload.manualKeywords ?? []),
];
const entryByKeyword = new Map<string, KeywordEntryWithTopic>();
for (const entry of allEntries) {
entryByKeyword.set(
this.normalizeKeyword(this.getKeywordLabel(entry)),
entry,
);
}
const result: KeywordEntryWithTopic[] = [];
const seen = new Set<string>();
for (const keyword of payload.keywords) {
const normalized = this.normalizeKeyword(keyword);
const entry = entryByKeyword.get(normalized);
if (!entry || seen.has(normalized)) continue;
seen.add(normalized);
result.push(entry);
}
return result;
});
readonly missingKeywordLabels = computed(() => {
const payload = this.state.payload();
if (!payload) return [];
const entryKeywordSet = new Set(
this.selectedKeywordEntries().map((entry) =>
this.normalizeKeyword(this.getKeywordLabel(entry)),
),
);
return payload.keywords.filter(
(keyword) => !entryKeywordSet.has(this.normalizeKeyword(keyword)),
);
});
constructor() {
const navigationState =
this.router.currentNavigation()?.extras.state ?? window.history.state;
const restoredPayload = this.parsePayload(navigationState);
if (restoredPayload) {
this.state.setPayload(restoredPayload);
}
}
goBackToSearch(): void {
void this.router.navigate(['/keywords']);
}
getChipLabel(keyword: KeywordEntryWithTopic): string {
return keyword.llm_keyword?.keyword ?? '';
}
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 {
return this.getTopic(item)?.works_count ?? 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);
}
getEntryTrack(entry: KeywordEntryWithTopic): string {
return this.getKeywordLabel(entry);
}
private parsePayload(value: unknown): SearchResultsPayload | null {
if (!value || typeof value !== 'object') return null;
const maybePayload = value as Partial<SearchResultsPayload>;
if (!Array.isArray(maybePayload.keywords)) return null;
return {
extractedKeywords: maybePayload.extractedKeywords ?? [],
manualKeywords: maybePayload.manualKeywords ?? [],
keywords: maybePayload.keywords ?? [],
options: {
softSearch: maybePayload.options?.softSearch ?? false,
},
};
}
private getKeywordLabel(item: KeywordEntryWithTopic): string {
return item.llm_keyword.keyword;
}
private getTopic(item: KeywordEntryWithTopic): Topic | null {
return item.topic_mapping?.topic ?? null;
}
private normalizeKeyword(value: string): string {
return value.trim().toLowerCase();
}
}
@@ -215,6 +215,13 @@
<p class="kw-suggestion-label">
Vorgeschlagen durch das Schlüsselwort im Text:
</p>
<button
mat-icon-button
class="analyse-btn"
matTooltip="Suche nach dem Schlüsselwort"
(click)="analyseKeyword(topic.source_keyword)">
<mat-icon>search</mat-icon>
</button>
<button
type="button"
class="kw-pill"
@@ -417,12 +417,21 @@ main {
}
.topic-item-body {
position: relative;
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 8px;
padding: 14px 14px 14px;
background: #ffffff;
.analyse-btn {
position: absolute;
color: color-mix(in srgb, var(--t) 90%, #0f172a);
font-size: 18px;
top: 0.1em;
right: 0.1em;
}
}
.kw-suggestion-label {
@@ -8,7 +8,7 @@ import {
} from '@angular/core';
import { Location } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { ActivatedRoute, Router, RouterLink } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
@@ -61,7 +61,7 @@ interface NewsArticleDetail {
})
export class NewsDetailComponent implements OnInit {
@ViewChild('articleBody') articleBodyRef?: ElementRef<HTMLElement>;
private readonly router = inject(Router);
private readonly destroyRef = inject(DestroyRef);
private readonly route = inject(ActivatedRoute);
private readonly httpClient = inject(HttpClient);
@@ -132,6 +132,12 @@ export class NewsDetailComponent implements OnInit {
}
}
analyseKeyword(keyword: string | null | undefined): void {
this.router.navigate(['/keywords'], {
queryParams: { manual: keyword ?? '', selected: keyword ?? '' },
});
}
ngOnInit(): void {
this.route.paramMap
.pipe(takeUntilDestroyed(this.destroyRef))
@@ -0,0 +1,74 @@
<!-- weights-sliders.component.html -->
<mat-card class="weights-card">
<mat-card-content>
<!-- Header -->
<div class="weights-header">
<h2>{{ title }}</h2>
@if (showResetButton) {
<button mat-stroked-button color="primary" (click)="resetWeights()">
<mat-icon>restart_alt</mat-icon>
{{ resetLabel }}
</button>
}
</div>
<!-- Sliders -->
<div class="weight-list">
@for (option of options; track option.key) {
<div class="weight-row">
<div
class="weight-label"
[matTooltip]="option.description || option.label"
[matTooltipPosition]="'above'"
[matTooltipClass]="'tooltip-sm'">
@if (option.icon) {
<mat-icon class="icon-small">{{ option.icon }}</mat-icon>
}
<span>{{ option.label }}</span>
</div>
<mat-slider
class="weight-slider"
[min]="min"
[max]="max"
[step]="step"
[discrete]="true"
[showTickMarks]="true"
[displayWith]="formatRawWeightLabel"
[attr.aria-label]="option.label + ' Gewichtung'">
<input
matSliderThumb
[formControl]="weightControl(option.key)"
[attr.aria-label]="option.label + ' Gewichtung'" />
</mat-slider>
<div class="weight-value">
{{ formatRawWeightLabel(weightControl(option.key).value) }}
</div>
</div>
}
</div>
<!-- Validation Warning -->
@if (!weightsState().valid) {
<div class="weight-warning">
<mat-icon>warning</mat-icon>
Mindestens ein Gewicht > 0
</div>
}
<!-- Apply Button -->
@if (showApplyButton) {
<div class="weight-actions">
<button
mat-flat-button
color="primary"
[disabled]="!weightsState().valid"
(click)="onApplyClick()">
<mat-icon>tune</mat-icon>
{{ applyLabel }}
</button>
</div>
}
</mat-card-content>
</mat-card>
@@ -0,0 +1,215 @@
/* weights-sliders.component.scss */
$phone: 599px;
$tablet: 900px;
$touch-target: 44px;
/* ============================================================
CARD
============================================================ */
::ng-deep .weights-card {
background: var(--sg-surface, #fff);
border: 1px solid var(--sg-divider, rgba(0, 0, 0, 0.12));
box-shadow: none;
mat-card-content.mat-mdc-card-content {
padding: 0.5rem 0.5rem 0.25rem; /* compact bottom */
border: none;
}
}
/* ============================================================
HEADER
============================================================ */
.weights-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.4rem;
margin-bottom: 0.3rem;
h2 {
margin: 0;
font-size: 0.85rem;
font-weight: 650;
color: var(--sg-text-primary);
}
button {
min-height: $touch-target;
padding: 0.2rem 0.4rem;
font-size: 0.75rem;
line-height: 1.2;
}
}
/* ============================================================
SLIDERS
============================================================ */
.weight-list {
display: flex;
flex-direction: column;
gap: 0.2rem;
margin-top: 0.1rem;
}
.weight-row {
display: grid;
grid-template-columns: 1fr 1fr 40px;
align-items: center;
gap: 0.2rem;
min-height: 34px;
font-size: 0.8rem;
}
.weight-label {
display: flex;
align-items: center;
gap: 0.2rem;
color: var(--sg-text-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
.icon-small {
font-size: 14px;
width: 14px;
height: 14px;
color: var(--sg-text-secondary);
}
span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-weight: 500;
}
}
.weight-slider {
width: 100%;
height: 20px; /* reduced from 24px */
margin: 0;
}
.weight-value {
font-size: 0.75rem;
font-weight: 650;
color: var(--sg-text-secondary);
text-align: right;
font-variant-numeric: tabular-nums;
}
/* ============================================================
WARNING
============================================================ */
.weight-warning {
display: flex;
align-items: center;
gap: 0.2rem;
margin-top: 0.2rem;
padding: 0.2rem 0.3rem;
border-radius: 3px;
background: color-mix(in srgb, #ff9800 12%, #ffffff);
color: #8a5200;
font-size: 0.7rem;
font-weight: 500;
mat-icon {
font-size: 14px;
width: 14px;
height: 14px;
}
}
/* ============================================================
ACTIONS
============================================================ */
.weight-actions {
display: flex;
justify-content: flex-end;
margin-top: 0.3rem;
button {
min-height: $touch-target;
padding: 0.2rem 0.6rem;
font-size: 0.8rem;
}
}
/* ============================================================
TOOLTIP
============================================================ */
.tooltip-sm {
font-size: 0.75rem;
padding: 0.3rem 0.5rem;
max-width: 200px;
border-radius: 3px;
background: var(--sg-surface, #fff);
color: var(--sg-text-primary);
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.12);
}
/* ============================================================
TABLET & PHONE
============================================================ */
@media (max-width: $tablet) {
.weight-row {
grid-template-columns: 1fr 40px;
gap: 0.15rem;
padding: 0.1rem 0;
}
.weight-label {
grid-column: 1 / -1;
font-size: 0.75rem;
}
.weight-slider {
grid-column: 1 / 2;
}
.weight-value {
grid-column: 2 / 3;
}
.weight-actions {
position: sticky;
bottom: 0;
z-index: 5;
background: var(--sg-background, #fff);
padding: 0.4rem;
margin: 0.3rem -0.5rem -0.25rem -0.5rem;
box-shadow: 0 -2px 6px rgba(0, 0, 0, 0.06);
}
}
@media (max-width: $phone) {
.weights-header {
flex-direction: column;
align-items: flex-start;
gap: 0.2rem;
}
.weight-row {
gap: 0.1rem;
min-height: 30px;
}
.weight-label {
font-size: 0.7rem;
}
.weight-slider {
height: 18px;
}
.weight-value {
font-size: 0.7rem;
}
.weight-actions {
padding: 0.3rem;
margin: 0.2rem -0.4rem -0.2rem -0.4rem;
}
}
@@ -0,0 +1,430 @@
import {
Component,
DestroyRef,
EventEmitter,
Input,
OnChanges,
OnInit,
Output,
SimpleChanges,
inject,
signal,
} from '@angular/core';
import { FormControl, FormRecord, ReactiveFormsModule } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { debounceTime, skip } from 'rxjs';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatSliderModule } from '@angular/material/slider';
import { MatTooltipModule } from '@angular/material/tooltip';
export interface WeightSliderOption {
key: string;
label: string;
icon?: string;
description?: string;
/**
* Optional default raw weight.
* Must be between 0 and 1.
*/
defaultValue?: number;
/**
* Optional explicit query param name.
* If not set, queryParamPrefix + key is used.
*/
queryParamName?: string;
}
export type WeightMap = Record<string, number>;
export interface WeightsSlidersValue {
raw: WeightMap;
normalized: WeightMap;
rawSum: number;
normalizedSum: number;
valid: boolean;
}
@Component({
selector: 'app-weights-sliders',
standalone: true,
imports: [
ReactiveFormsModule,
MatButtonModule,
MatCardModule,
MatDividerModule,
MatIconModule,
MatSliderModule,
MatTooltipModule,
],
templateUrl: './weights-sliders.component.html',
styleUrl: './weights-sliders.component.scss',
})
export class WeightsSlidersComponent implements OnInit, OnChanges {
private readonly router = inject(Router);
private readonly route = inject(ActivatedRoute);
private readonly destroyRef = inject(DestroyRef);
@Input({ required: true }) options: WeightSliderOption[] = [];
@Input() title = 'Suchgewichtung';
@Input() description =
'Werte zwischen 0 und 1. Die normalisierte Gewichtung wird durch Sum-Normalisierung berechnet und ergibt zusammen 1.';
@Input() resetLabel = 'Ausgewogen';
@Input() applyLabel = 'Ergebnisse neu gewichten';
@Input() normalizedTitle = 'Normalisierte Gewichtung';
@Input() showApplyButton = true;
@Input() showResetButton = true;
@Input() showNormalizedPreview = true;
@Input() showDescriptions = true;
@Input() persistInQueryParams = true;
/**
* If option.queryParamName is not set, the query param becomes:
* queryParamPrefix + option.key
*
* Example:
* queryParamPrefix = 'personW_'
* key = 'publications'
* query param = personW_publications
*/
@Input() queryParamPrefix = 'w_';
/**
* Initial raw values from parent.
* Example:
* {
* publications: 0.5,
* citations: 0.2
* }
*/
@Input() initialWeights: Partial<WeightMap> | null = null;
/**
* If old values like 50 or 80 arrive, they can be converted to 0.5 / 0.8.
*/
@Input() convertPercentValues = true;
@Input() min = 0;
@Input() max = 1;
@Input() step = 0.05;
@Input() decimals = 2;
@Input() normalizedDecimals = 3;
@Output() weightsChange = new EventEmitter<WeightsSlidersValue>();
@Output() applyWeights = new EventEmitter<WeightsSlidersValue>();
readonly form = new FormRecord<FormControl<number>>({});
readonly weightsState = signal<WeightsSlidersValue>({
raw: {},
normalized: {},
rawSum: 0,
normalizedSum: 0,
valid: false,
});
private initialized = false;
private isOwnNavigation = false;
constructor() {
this.form.valueChanges
.pipe(debounceTime(250), takeUntilDestroyed(this.destroyRef))
.subscribe(() => {
this.updateState({
emit: true,
persist: this.persistInQueryParams,
});
});
}
ngOnInit(): void {
this.rebuildForm();
if (this.persistInQueryParams) {
this.patchWeightsFromQueryParams();
}
this.updateState({
emit: true,
persist: false,
});
this.initialized = true;
if (this.persistInQueryParams) {
this.route.queryParamMap
.pipe(skip(1), takeUntilDestroyed(this.destroyRef))
.subscribe(() => {
if (this.isOwnNavigation) {
this.isOwnNavigation = false;
return;
}
this.patchWeightsFromQueryParams();
this.updateState({
emit: true,
persist: false,
});
});
}
}
ngOnChanges(changes: SimpleChanges): void {
if (
changes['options'] ||
changes['initialWeights'] ||
changes['min'] ||
changes['max']
) {
this.rebuildForm();
if (this.initialized) {
if (this.persistInQueryParams) {
this.patchWeightsFromQueryParams();
}
this.updateState({
emit: true,
persist: false,
});
}
}
}
weightControl(key: string): FormControl<number> {
const control = this.form.controls[key];
if (!control) {
throw new Error(`Weight control "${key}" does not exist.`);
}
return control;
}
formatRawWeightLabel = (value: number): string => {
return Number(value).toFixed(this.decimals);
};
formatNormalizedWeight(value: number): string {
return Number(value).toFixed(this.normalizedDecimals);
}
resetWeights(): void {
const nextValues: WeightMap = {};
for (const option of this.options) {
nextValues[option.key] = this.sanitizeWeightValue(
option.defaultValue ?? 0.5,
);
}
this.form.setValue(nextValues);
}
onApplyClick(): void {
const value = this.calculateValue();
this.updateState({
emit: true,
persist: this.persistInQueryParams,
});
this.applyWeights.emit(value);
}
normalizedEntries(): Array<{
key: string;
label: string;
value: number;
}> {
const normalized = this.weightsState().normalized;
return this.options.map((option) => ({
key: option.key,
label: option.label,
value: normalized[option.key] ?? 0,
}));
}
private rebuildForm(): void {
const wantedKeys = new Set(this.options.map((option) => option.key));
for (const existingKey of Object.keys(this.form.controls)) {
if (!wantedKeys.has(existingKey)) {
this.form.removeControl(existingKey);
}
}
for (const option of this.options) {
const initialValue = this.resolveInitialValue(option);
if (this.form.controls[option.key]) {
this.form.controls[option.key].setValue(initialValue, {
emitEvent: false,
});
} else {
this.form.addControl(
option.key,
new FormControl(initialValue, { nonNullable: true }),
{ emitEvent: false },
);
}
}
}
private resolveInitialValue(option: WeightSliderOption): number {
const fromInput = this.initialWeights?.[option.key];
if (fromInput !== undefined && fromInput !== null) {
return this.sanitizeWeightValue(fromInput);
}
return this.sanitizeWeightValue(option.defaultValue ?? 0.5);
}
private patchWeightsFromQueryParams(): void {
const queryParams = this.route.snapshot.queryParamMap;
const patch: Record<string, number> = {};
for (const option of this.options) {
const queryParamName = this.getQueryParamName(option);
const rawValue = queryParams.get(queryParamName);
if (rawValue === null) continue;
patch[option.key] = this.sanitizeWeightValue(rawValue);
}
if (Object.keys(patch).length > 0) {
this.form.patchValue(patch, { emitEvent: false });
}
}
private updateState(config: { emit: boolean; persist: boolean }): void {
const value = this.calculateValue();
this.weightsState.set(value);
if (config.persist) {
this.updateQueryParams(value.raw);
}
if (config.emit) {
this.weightsChange.emit(value);
}
}
private calculateValue(): WeightsSlidersValue {
const raw = this.getRawWeights();
const rawSum = this.sumWeights(raw);
const normalized = this.sumNormalize(raw, rawSum);
const normalizedSum = this.sumWeights(normalized);
return {
raw,
normalized,
rawSum,
normalizedSum,
valid: rawSum > 0,
};
}
private getRawWeights(): WeightMap {
const rawFormValue = this.form.getRawValue();
const result: WeightMap = {};
for (const option of this.options) {
result[option.key] = this.sanitizeWeightValue(rawFormValue[option.key]);
}
return result;
}
private sumNormalize(raw: WeightMap, rawSum: number): WeightMap {
const normalized: WeightMap = {};
for (const option of this.options) {
if (rawSum <= 0 || !Number.isFinite(rawSum)) {
normalized[option.key] = 0;
} else {
normalized[option.key] = raw[option.key] / rawSum;
}
}
return normalized;
}
private sumWeights(weights: WeightMap): number {
return Object.values(weights).reduce((sum, value) => sum + value, 0);
}
private updateQueryParams(rawWeights: WeightMap): void {
const queryParams: Record<string, number> = {};
for (const option of this.options) {
const queryParamName = this.getQueryParamName(option);
const value = rawWeights[option.key] ?? 0;
queryParams[queryParamName] = Number(value.toFixed(this.decimals));
}
this.isOwnNavigation = true;
this.router
.navigate([], {
relativeTo: this.route,
queryParams,
queryParamsHandling: 'merge',
replaceUrl: true,
})
.then((navigated) => {
if (!navigated) {
this.isOwnNavigation = false;
}
});
}
private getQueryParamName(option: WeightSliderOption): string {
return option.queryParamName ?? `${this.queryParamPrefix}${option.key}`;
}
private sanitizeWeightValue(value: unknown): number {
const parsed = Number(value);
if (!Number.isFinite(parsed)) {
return 0;
}
let normalizedInput = parsed;
if (this.convertPercentValues && this.max === 1 && parsed > 1) {
normalizedInput = parsed / 100;
}
return Math.min(
this.max,
Math.max(this.min, Number(normalizedInput.toFixed(this.decimals))),
);
}
}