From ea5289dc67f7c1cfd976a32a07d2777bb0c169af Mon Sep 17 00:00:00 2001 From: Mohammed Abad Date: Fri, 10 May 2024 10:14:55 +0100 Subject: [PATCH] implemented advanced library filter --- .../src/app/core/services/library.service.ts | 51 +-- .../features/library/library.component.css | 28 ++ .../features/library/library.component.html | 133 ++++-- .../app/features/library/library.component.ts | 395 ++++++++++++++++-- .../app/shared/models/LibraryQueryParams.ts | 11 + 5 files changed, 493 insertions(+), 125 deletions(-) create mode 100644 frontend/src/app/shared/models/LibraryQueryParams.ts diff --git a/frontend/src/app/core/services/library.service.ts b/frontend/src/app/core/services/library.service.ts index e2e4328..d5cecfd 100644 --- a/frontend/src/app/core/services/library.service.ts +++ b/frontend/src/app/core/services/library.service.ts @@ -5,15 +5,13 @@ import { catchError, switchMap, tap } from 'rxjs/operators'; import { Entry } from '../../shared/models/entry.model'; import { EntryId } from '../../shared/models/entryId.model'; import { EntryRating } from '../../shared/models/entryRating.model'; -// import { environment } from '../../../environments/environment'; @Injectable({ providedIn: 'root', }) export class LibraryService implements OnInit { - // libraryEntries: Entry[] = []; private libraryEntriesSubject = new ReplaySubject(1); - private entriesLoaded = false; // Flag to track if the entries have been loaded + private entriesLoaded = false; private backend_apiUrl = ' http://localhost:4000/api/v1'; @@ -27,28 +25,18 @@ export class LibraryService implements OnInit { if (this.entriesLoaded && !forceFetch) { return this.libraryEntriesSubject.asObservable(); } else { - // Note: This now properly chains the observable without directly subscribing here. return this.fetchAllEntries(forceFetch); } } - // public refreshEntries(forceFetch: boolean = true): Observable { - // return this.getAllEntries(forceFetch); - // } + public refrechEntries() { + return this.fetchAllEntries(true); + } - // private apiUrl = environment.apiBaseUrl; - - /** - * Fetches data from the specified endpoint and returns an Observable. - * @param {string} endPoint The URL of the API endpoint to fetch data from. - * @param {Object} params Optional query parameters to append to the request URL. - * @returns {Observable} An Observable that emits the fetched data. - */ fetchData( endPoint: string, params?: { [param: string]: string | number } ): Observable { - // Initialize HttpParams from the provided params object let httpParams = new HttpParams(); if (params) { Object.keys(params).forEach((key) => { @@ -75,7 +63,6 @@ export class LibraryService implements OnInit { this.entriesLoaded = true; }), catchError((error) => { - // Log and rethrow the error for the caller to handle. console.error('Failed to fetch entries:', error); this.entriesLoaded = false; // Allow for a retry on subsequent calls. return throwError(() => new Error('Failed to fetch entries')); @@ -84,36 +71,6 @@ export class LibraryService implements OnInit { } } - // /** - // * Fetches library data with page and pagesize and returns an Observable. - // * @param {string} endPoint The URL of the API endpoint to fetch data from. - // * @param {Object} params Optional query parameters to append to the request URL. - // * @returns {Observable} An Observable that emits the fetched data. - // */ - // getEntries(page: number, pageSize: number): Observable { - // var endPoint = `${this.backend_apiUrl}/entries`; - // return this.fetchData(endPoint, { page: page, pageSize: pageSize }).pipe( - // map((response) => - // response.results.map((movie: any) => this.mapMovieToEntry(movie)) - // ) - // ); - // } - - // /** - // * Retrieves a specific page of entries from the library. - // * - // * @param page The page number to retrieve. - // * @param pageSize Defines the number of entries on each page. - // * @returns An Observable emitting the requested page of entries. - // */ - // getEntriesUsingEndPoint(endPoint: string): Observable { - // return this.fetchData(endPoint).pipe( - // map((response) => - // response.results.map((movie: any) => this.mapMovieToEntry(movie)) - // ) - // ); - // } - addEntry(tmdb_id: string, is_tvserie: boolean): Observable { return this.getAllEntries().pipe( switchMap((entries) => { diff --git a/frontend/src/app/features/library/library.component.css b/frontend/src/app/features/library/library.component.css index 2709cf5..5ca8d33 100644 --- a/frontend/src/app/features/library/library.component.css +++ b/frontend/src/app/features/library/library.component.css @@ -1,3 +1,4 @@ +/* ! buttons style */ .custom-group .form-select { border-top-right-radius: 0; border-bottom-right-radius: 0; @@ -33,4 +34,31 @@ #single-select-field { max-width: 120px; +} + +.align-items-baseline { + align-items: baseline; +} + +/* ! filter switches style */ +.form-check-label { + margin-bottom: 0; +} + +a.clear-filter-link { + display: inline-block; + padding: 0.375rem 0; +} + +.filter-switches { + margin-left: auto; +} + +/* ! filter title, year, genre */ +.select2 .select2-container .select2-container--default { + height: 50px !important; +} + +.select2 .select2-container .select2-container--default .selection span .select2-selection .select2-selection--multiple { + padding: 0 !important; } \ No newline at end of file diff --git a/frontend/src/app/features/library/library.component.html b/frontend/src/app/features/library/library.component.html index c36d32f..758a267 100644 --- a/frontend/src/app/features/library/library.component.html +++ b/frontend/src/app/features/library/library.component.html @@ -12,48 +12,115 @@ -
-
-
Show
- +
+ -
- - - + + + +
+ + +
+ +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + + Clear Filter +
+ + +
+ + +
+
+ +
+
+ search + +
+
+ + +
+
+ +
+
+ + +
+
+
- + + +
-
- +
+
+
+ Total entries {{entriesCount}} +
+
+ +
+
+ + diff --git a/frontend/src/app/features/library/library.component.ts b/frontend/src/app/features/library/library.component.ts index f048b0d..875bd23 100644 --- a/frontend/src/app/features/library/library.component.ts +++ b/frontend/src/app/features/library/library.component.ts @@ -1,42 +1,101 @@ -import { Component } from '@angular/core'; +import { AfterViewInit, Component, OnDestroy, OnInit } from '@angular/core'; import { Entry } from '../../shared/models/entry.model'; import { LibraryService } from '../../core/services/library.service'; -import { Event, NavigationEnd, Router } from '@angular/router'; +import { ActivatedRoute, Event, NavigationEnd, Router } from '@angular/router'; +import { LibraryQueryParams } from '../../shared/models/LibraryQueryParams'; +declare var $: any; @Component({ selector: 'app-library', templateUrl: './library.component.html', styleUrls: ['./library.component.css'], }) -export class LibraryComponent { - entryType: number = 0; - +export class LibraryComponent implements OnInit, AfterViewInit { entries: Entry[] = []; entriesToShow: Entry[] = []; + // ? pagination entriesCount: number = 0; maxPage: number = 10; currentPage: number = 1; pageSize: number = 10; - constructor(private router: Router, private libraryService: LibraryService) {} + // ? filter + years: number[] = []; + genres: string[] = [ + 'Action & Adventure', + 'Animation', + 'Comedy', + 'Crime', + 'Documentary', + 'Drama', + 'Family', + 'Kids', + 'Mystery', + 'News', + 'Reality', + 'Sci-Fi & Fantasy', + 'Soap', + 'Talk', + 'War & Politics', + 'Western', + 'Action', + 'Adventure', + 'Fantasy', + 'History', + 'Horror', + 'Music', + 'Romance', + 'Science Fiction', + 'TV Movie', + 'Thriller', + 'War', + ]; - ngOnInit() { - this.pageSize = this.getDefaultPageSize(); - this.getEntries(true); + filterCriteria: { + title?: string; + type: number; + years?: number[]; + genres?: string[]; + favorit: boolean; + watchlist: boolean; + hidden: boolean; + matchAll: boolean; + } = { + title: '', + type: 0, + years: [], + genres: [], + favorit: false, + watchlist: false, + hidden: false, + matchAll: true, + }; + + constructor( + private router: Router, + private route: ActivatedRoute, + private libraryService: LibraryService + ) {} + + async ngOnInit() { + this.pageSize = await this.getDefaultPageSize(); + await this.getEntries(true); // this.router.events.subscribe((event) => { // if (event instanceof NavigationEnd && event.url === '/library') { // this.pageSize = this.getDefaultPageSize(); // this.getEntries(true); // } // }); + await this.populateYears(); } // ? uses libraryService to get library all entries getEntries(forceFetch: boolean = false) { this.libraryService.getAllEntries(forceFetch).subscribe({ next: (entries) => { - this.entries = entries; + this.entries = entries.filter((e) => !e.watchlist); + this.getQueryParameters(); this.filterEntries(); }, error: (error) => { @@ -46,24 +105,198 @@ export class LibraryComponent { }); } + getQueryParameters() { + this.route.queryParams.subscribe((params) => { + this.currentPage = params['page'] ? parseInt(params['page'], 10) : 1; + this.filterCriteria.title = params['title'] || ''; + this.filterCriteria.favorit = params.hasOwnProperty('favorit') + ? params['favorit'] + : false; + this.filterCriteria.years = params['years'] + ? params['years'].split(',') + : []; + this.filterCriteria.genres = params['genres'] + ? params['genres'].split(',') + : []; + this.filterCriteria.type = params.hasOwnProperty('type') + ? params['type'] + : 0; + this.filterCriteria.hidden = params.hasOwnProperty('hidden') + ? params['hidden'] + : false; + this.filterCriteria.matchAll = params.hasOwnProperty('matchAll') + ? params['matchAll'] + : true; + }); + } + + setQueryParameters() { + let params = { page: this.currentPage } as LibraryQueryParams; + + if (this.filterCriteria.title?.trim() != '') { + params.title = this.filterCriteria.title?.trim(); + } else { + delete params.title; + } + + if (this.filterCriteria.years?.length) { + params.years = this.filterCriteria.years.join(','); + } else { + delete params.years; + } + + if (this.filterCriteria.genres?.length) { + params.genres = this.filterCriteria.genres.join(','); + } else { + delete params.genres; + } + + if (this.filterCriteria.type != 0) { + params.type = this.filterCriteria.type; + } else { + delete params.type; + } + + if (this.filterCriteria.favorit != false) { + params.favorit = this.filterCriteria.favorit; + } else { + delete params.favorit; + } + + if (this.filterCriteria.hidden != false) { + params.hidden = this.filterCriteria.hidden; + } else { + delete params.hidden; + } + + if (this.filterCriteria.matchAll != true) { + params.matchAll = this.filterCriteria.matchAll; + } else { + delete params.matchAll; + } + + this.router.navigate([], { + relativeTo: this.route, + queryParams: params, + queryParamsHandling: '', + }); + } + + // ! FILTER + ngAfterViewInit() { + $('#year-select') + .select2({ + placeholder: 'Year(s)...', + allowClear: true, + closeOnSelect: false, + }) + .on('change', (event: { target: any }) => { + this.onYearsChange(event); + }); + + $('#genre-select') + .select2({ + placeholder: 'Genre(s)...', + allowClear: true, + closeOnSelect: false, + }) + .on('change', (event: { target: any }) => { + this.onGenresChange(event); + }); + } + + populateYears() { + const currentYear = new Date().getFullYear(); + for (let year = currentYear; year >= 1950; year--) { + this.years.push(year); + } + } + + initializeSelect2() { + setTimeout(() => { + // Ensure that the DOM is fully loaded + $('.select2').select2({ + placeholder: 'Select an option', + allowClear: true, + }); + }, 500); + } + + clearFilter() { + this.filterCriteria = { + title: '', + type: 0, + years: [], + genres: [], + favorit: false, + watchlist: false, + hidden: false, + matchAll: true, + }; + + this.setQueryParameters(); + this.filterEntries(); + } + async filterEntries() { var temp = [] as Entry[]; - // ? type filter - if (this.entryType != 0) { - await this.entries.forEach((entry) => { - if (this.entryType == 1 && !entry.is_tvseries) temp.push(entry); - else if (this.entryType == 2 && entry.is_tvseries) temp.push(entry); - }); - } else { - temp = this.entries; - } + const formattedTitle = + this.filterCriteria.title?.toLowerCase().trim() || ''; + temp = await this.entries.filter((entry) => { + // Type check + let filterType = this.filterCriteria.type - 1 == 0 ? false : true; + if (this.filterCriteria.type != 0 && filterType != entry.is_tvseries) { + return false; // Skip entry if the type does not match, unless type is 'all' (0) + } + + // Hidden check + // skip hidden if show hidden is not check + if (!this.filterCriteria.hidden && entry.hidden) { + return false; + } + + const year = new Date(entry.release_date).getFullYear(); + // ! Match all criteria logic + if (this.filterCriteria.matchAll) { + return ( + (formattedTitle + ? entry.title.toLowerCase().includes(formattedTitle) || + entry.original_title.toLowerCase().includes(formattedTitle) + : true) && + (this.filterCriteria.genres?.length + ? this.filterCriteria.genres.every((genre) => + entry.genres.includes(genre) + ) + : true) && + (this.filterCriteria.years?.length + ? this.filterCriteria.years.includes(year) + : true) && + (this.filterCriteria.favorit ? entry.favorit : true) && + (this.filterCriteria.watchlist ? entry.watchlist : true) && + (this.filterCriteria.hidden ? entry.hidden : true) + ); + } + + // ! Match at least one criteria logic + return ( + (formattedTitle + ? entry.title.toLowerCase().includes(formattedTitle) || + entry.original_title.toLowerCase().includes(formattedTitle) + : true) || + (this.filterCriteria.genres?.length && + this.filterCriteria.genres.some((genre) => + entry.genres.includes(genre) + )) || + (this.filterCriteria.years?.length && + this.filterCriteria.years.includes(year)) || + (this.filterCriteria.favorit && entry.favorit) || + (this.filterCriteria.watchlist && entry.watchlist) + ); + }); // ? sort filter - temp = temp.sort( - (a, b) => - new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime() - ); + temp = await this.sortEntries(temp); this.entriesCount = temp.length; this.maxPage = Math.ceil(this.entriesCount / this.pageSize); @@ -74,20 +307,112 @@ export class LibraryComponent { this.entriesToShow = temp.slice(startIndex, endIndex); } + // + FILTER END + // ! sorting + sortEntries(entries: Entry[]) { + return entries.sort( + (a, b) => + new Date(b.date_last_seen).getTime() - + new Date(a.date_last_seen).getTime() + ); + } + + // ! calculated fields + moviesCount() { + return this.entries.filter((e) => !e.is_tvseries).length; + } + + seriesCount() { + return this.entries.filter((e) => e.is_tvseries).length; + } + + favoritCount() { + return this.entries.filter((e) => e.favorit).length; + } + hiddenCount() { + return this.entries.filter((e) => e.hidden).length; + } + + // ! events entryRemoved(event: Event) { this.entries = this.entries.filter( (e) => e.id.toString() != event.toString() ); this.pageSize = this.getDefaultPageSize(); this.filterEntries(); - // this.getEntries(true); + this.setQueryParameters(); // * update url query + } + + // * filter events + onYearsChange(event: any) { + this.currentPage = 1; + + const selected = $(event.target).val(); + this.filterCriteria.years = Array.isArray(selected) + ? selected.map(Number) + : [Number(selected)]; + + this.filterEntries(); + this.setQueryParameters(); // * update url query + } + + onGenresChange(event: any) { + this.currentPage = 1; + + const selected = $(event.target).val(); + this.filterCriteria.genres = Array.isArray(selected) ? selected : []; + + this.filterEntries(); + this.setQueryParameters(); // * update url query + } + + onFilterChange() { + this.currentPage = 1; + this.filterEntries(); + this.setQueryParameters(); // * update url query + } + + onEntryTypeChange(entryType: number) { + this.filterCriteria.type = entryType; + + this.currentPage = 1; + this.filterEntries(); + this.setQueryParameters(); // * update url query + } + + setFavorit() { + this.filterCriteria.favorit = !this.filterCriteria.favorit; + + this.currentPage = 1; + this.filterEntries(); + this.setQueryParameters(); // * update url query + } + + setHidden() { + this.filterCriteria.hidden = !this.filterCriteria.hidden; + + this.currentPage = 1; + this.filterEntries(); + this.setQueryParameters(); // * update url query + } + // + end filter event + + // ! pagination + setPageSize(event: any) { + this.pageSize = event.target.value; + this.filterEntries(); + } + + getDefaultPageSize() { + // TODO get default page size from settings service + return 54; } - // ? pagination goToPage(page: number) { this.currentPage = page; this.filterEntries(); + this.setQueryParameters(); // * update url query } get pageNumbers(): number[] { @@ -113,24 +438,4 @@ export class LibraryComponent { (_, i) => startPage + i ); } - // ? end pagination - - // ? setter - setEntryType(entryType: number) { - this.entryType = entryType; - this.currentPage = 1; - - this.filterEntries(); - } - - setPageSize(event: any) { - this.pageSize = event.target.value; - this.filterEntries(); - } - - // ? getters - getDefaultPageSize() { - // TODO get default page size from settings service - return 20; - } } diff --git a/frontend/src/app/shared/models/LibraryQueryParams.ts b/frontend/src/app/shared/models/LibraryQueryParams.ts new file mode 100644 index 0000000..ace6e09 --- /dev/null +++ b/frontend/src/app/shared/models/LibraryQueryParams.ts @@ -0,0 +1,11 @@ +export interface LibraryQueryParams { + page: number; + title?: string; + type?: number; + years?: string; + genres?: string; + favorit?: boolean; + watchlist?: boolean; + hidden?: boolean; + matchAll?: boolean; +}