Files
smartguide/webapp/src/app/shared/ui/searchable-select/searchable-select.component.ts
T
Mats Paul Tončik 0a97b3797e
LocationBasedServices/smartguide/pipeline/head This commit looks good
feat(works-v2): optimized and documented works v2 service
2026-07-19 15:17:57 +02:00

102 lines
2.7 KiB
TypeScript

import {
Component,
computed,
DestroyRef,
inject,
input,
output,
signal,
} from '@angular/core';
import { MatSelectModule } from '@angular/material/select';
import { FormsModule } from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import {
BehaviorSubject,
catchError,
debounceTime,
distinctUntilChanged,
Observable,
of,
switchMap,
tap,
} from 'rxjs';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
type Page<T> = {
elements?: T[];
page?: number;
size?: number;
total?: number;
};
@Component({
selector: 'app-searchable-select',
imports: [
MatSelectModule,
MatInputModule,
MatIconModule,
MatButtonModule,
FormsModule,
],
templateUrl: './searchable-select.component.html',
styleUrl: './searchable-select.component.scss',
})
export class SearchableSelectComponent<T> {
searchValue: string = '';
handleSelectChange = output<T>();
_elements = computed<T[]>(() => {
const predefined = this.selectedElements();
const fetched = this.fetchedElements();
return [...predefined, ...fetched.elements!];
});
isLoading = signal<boolean>(false);
icon = input<string>('');
label = input.required<string>();
selectedLabel = input<string>('Ausgewählt');
fetchedLabel = input<string>('Verfügbar');
fetchElements = input<(searchTerm: string) => Observable<Page<T>>>();
fetchedElements = signal<Page<T>>({ elements: [] });
selectedElements = input<T[]>([]);
getSelectLabel = input.required<(element: T) => string>();
getSelectValue = input.required<(element: T) => string>();
getSelectDescription = input<(element: T) => string>();
inputPlaceholder = input<string>('Suche');
private readonly searchTerms = new BehaviorSubject<string>('');
private readonly destroyRef = inject(DestroyRef);
constructor() {
this.searchTerms
.pipe(
debounceTime(300),
distinctUntilChanged(),
tap(() => this.isLoading.set(true)),
switchMap((term) => {
const fetchFn = this.fetchElements();
if (!fetchFn) {
return of({ elements: [] } as Page<T>);
}
return fetchFn(term).pipe(catchError(() => of({ elements: [] } as Page<T>)));
}),
tap(() => this.isLoading.set(false)),
takeUntilDestroyed(this.destroyRef),
)
.subscribe((results) => this.fetchedElements.set(results));
}
_handleValueChange(newValue: string): void {
this.searchValue = newValue;
this.searchTerms.next(newValue);
}
_clearSearchValue(): void {
this.searchValue = '';
this.fetchedElements.set({ elements: [] });
}
}