All files / app/features/search search.component.ts

98% Statements 49/50
100% Branches 14/14
93.33% Functions 14/15
100% Lines 46/46

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 1271x 1x 1x 1x   1x               1x   1x                             1x 24x 24x 24x     24x   24x 24x 24x 24x 24x 24x   43x 24x   51x           24x     2x       24x     53x     50x 50x       36x             1x             34x 34x 34x         29x 29x       6x 6x 6x     6x 1x     5x   5x       2x         5x 3x 3x   5x        
import { ArticleService } from '../../services/articles';
import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, OnInit, signal } from '@angular/core';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { RouterLink } from '@angular/router';
import { ArticleSearchResult } from '@drevo-web/shared';
import {
    SpinnerComponent,
    TextInputComponent,
    VirtualScrollerComponent,
    VirtualScrollerItemDirective,
    MODAL_DATA,
    ModalData,
} from '@drevo-web/ui';
import { catchError, debounceTime, distinctUntilChanged, map, of, startWith, Subject, switchMap, tap } from 'rxjs';
 
const DEBOUNCE_TIME_MS = 500;
 
@Component({
    selector: 'app-search',
    imports: [
        RouterLink,
        TextInputComponent,
        SpinnerComponent,
        VirtualScrollerComponent,
        VirtualScrollerItemDirective,
    ],
    templateUrl: './search.component.html',
    styleUrl: './search.component.scss',
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SearchComponent implements OnInit {
    private readonly articleService = inject(ArticleService);
    private readonly destroyRef = inject(DestroyRef);
    private readonly modalData = inject<ModalData>(MODAL_DATA, {
        optional: true,
    });
    private readonly searchSubject = new Subject<string>();
 
    readonly searchQuery = signal('');
    readonly searchResults = signal<ArticleSearchResult[]>([]);
    readonly isLoading = signal(false);
    readonly isLoadingMore = signal(false);
    readonly totalResults = signal(0);
    readonly currentPage = signal(1);
 
    readonly hasResults = computed(() => this.searchResults().length > 0 && !this.isLoading());
    readonly showNoResults = computed(
        () =>
            this.searchQuery().length > 0 &&
            !this.isLoading() &&
            this.totalResults() === 0 &&
            this.searchResults().length === 0
    );
 
    readonly trackByFn = (_index: number, item: ArticleSearchResult): number => item.id;
 
    closeModal(): void {
        this.modalData?.close();
    }
 
    ngOnInit(): void {
        this.searchSubject
            .pipe(
                startWith(''),
                map(query => query.trim()),
                distinctUntilChanged(),
                tap(() => {
                    this.isLoading.set(true);
                    this.currentPage.set(1);
                }),
                debounceTime(DEBOUNCE_TIME_MS),
                switchMap(query => {
                    return this.articleService
                        .searchArticles({
                            query,
                            page: 1,
                        })
                        .pipe(
                            catchError(() => {
                                return of({ items: [], total: 0 });
                            })
                        );
                }),
                takeUntilDestroyed(this.destroyRef)
            )
            .subscribe(response => {
                this.searchResults.set([...response.items]);
                this.totalResults.set(response.total);
                this.isLoading.set(false);
            });
    }
 
    onSearchChange(value: string): void {
        this.searchQuery.set(value);
        this.searchSubject.next(value);
    }
 
    onLoadMore(): void {
        const query = this.searchQuery();
        const nextPage = this.currentPage() + 1;
        const currentResults = this.searchResults();
 
        // Check if we already have all results
        if (currentResults.length >= this.totalResults()) {
            return;
        }
 
        this.isLoadingMore.set(true);
 
        this.articleService
            .searchArticles({ query, page: nextPage })
            .pipe(
                catchError(() => {
                    return of({ items: [], total: 0 });
                }),
                takeUntilDestroyed(this.destroyRef)
            )
            .subscribe(response => {
                if (response.items.length > 0) {
                    this.searchResults.set([...currentResults, ...response.items]);
                    this.currentPage.set(nextPage);
                }
                this.isLoadingMore.set(false);
            });
    }
}