fix(filter): update filter options to use CountedOption for read statuses and file types (#448)
* fix(filter): update filter options to use CountedOption for read statuses and file types * fix(specification): validate file types and read statuses, throwing APIException for invalid values
This commit is contained in:
@@ -10,8 +10,8 @@ import java.util.List;
|
|||||||
public record AppFilterOptions(
|
public record AppFilterOptions(
|
||||||
List<CountedOption> authors,
|
List<CountedOption> authors,
|
||||||
List<LanguageOption> languages,
|
List<LanguageOption> languages,
|
||||||
List<String> readStatuses,
|
List<CountedOption> readStatuses,
|
||||||
List<String> fileTypes,
|
List<CountedOption> fileTypes,
|
||||||
List<CountedOption> categories,
|
List<CountedOption> categories,
|
||||||
List<CountedOption> publishers,
|
List<CountedOption> publishers,
|
||||||
List<CountedOption> series,
|
List<CountedOption> series,
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
package org.booklore.app.dto;
|
package org.booklore.app.dto;
|
||||||
|
|
||||||
import jakarta.validation.constraints.Size;
|
import jakarta.validation.constraints.Size;
|
||||||
import org.booklore.model.enums.BookFileType;
|
|
||||||
import org.booklore.model.enums.ReadStatus;
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@@ -13,9 +11,9 @@ public record BookListRequest(
|
|||||||
String dir,
|
String dir,
|
||||||
Long libraryId,
|
Long libraryId,
|
||||||
Long shelfId,
|
Long shelfId,
|
||||||
ReadStatus status,
|
@Size(max = 20) List<String> status,
|
||||||
String search,
|
String search,
|
||||||
BookFileType fileType,
|
@Size(max = 20) List<String> fileType,
|
||||||
Integer minRating,
|
Integer minRating,
|
||||||
Integer maxRating,
|
Integer maxRating,
|
||||||
@Size(max = 20) List<String> authors,
|
@Size(max = 20) List<String> authors,
|
||||||
|
|||||||
@@ -362,7 +362,7 @@ public class AppBookService {
|
|||||||
.authors(Collections.emptyList())
|
.authors(Collections.emptyList())
|
||||||
.languages(Collections.emptyList())
|
.languages(Collections.emptyList())
|
||||||
.fileTypes(Collections.emptyList())
|
.fileTypes(Collections.emptyList())
|
||||||
.readStatuses(getReadStatusOptions())
|
.readStatuses(Collections.emptyList())
|
||||||
.categories(Collections.emptyList())
|
.categories(Collections.emptyList())
|
||||||
.publishers(Collections.emptyList())
|
.publishers(Collections.emptyList())
|
||||||
.series(Collections.emptyList())
|
.series(Collections.emptyList())
|
||||||
@@ -409,15 +409,20 @@ public class AppBookService {
|
|||||||
c.count()))
|
c.count()))
|
||||||
.toList();
|
.toList();
|
||||||
|
|
||||||
String fileTypeQuery = "SELECT DISTINCT bf.bookType FROM BookEntity b"
|
String fileTypeQuery = "SELECT bf.bookType, COUNT(DISTINCT b.id) FROM BookEntity b"
|
||||||
+ " JOIN b.bookFiles bf"
|
+ " JOIN b.bookFiles bf"
|
||||||
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
|
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
|
||||||
+ " AND b.bookFiles IS NOT EMPTY"
|
+ " AND b.bookFiles IS NOT EMPTY"
|
||||||
+ " AND bf.isBookFormat = true"
|
+ " AND bf.isBookFormat = true"
|
||||||
+ scopeClause;
|
+ scopeClause
|
||||||
var ftQ = entityManager.createQuery(fileTypeQuery, BookFileType.class);
|
+ " GROUP BY bf.bookType ORDER BY COUNT(DISTINCT b.id) DESC";
|
||||||
|
var ftQ = entityManager.createQuery(fileTypeQuery, Tuple.class);
|
||||||
setFilterQueryParams(ftQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
setFilterQueryParams(ftQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||||
List<String> fileTypes = ftQ.getResultList().stream().map(Enum::name).sorted().toList();
|
List<AppFilterOptions.CountedOption> fileTypes = ftQ.getResultList().stream()
|
||||||
|
.map(t -> new AppFilterOptions.CountedOption(
|
||||||
|
t.get(0, BookFileType.class).name(),
|
||||||
|
t.get(1, Long.class)))
|
||||||
|
.toList();
|
||||||
|
|
||||||
List<AppFilterOptions.CountedOption> categories = queryCountedOptions(
|
List<AppFilterOptions.CountedOption> categories = queryCountedOptions(
|
||||||
"c.name", "JOIN b.metadata m JOIN m.categories c", "",
|
"c.name", "JOIN b.metadata m JOIN m.categories c", "",
|
||||||
@@ -446,11 +451,14 @@ public class AppBookService {
|
|||||||
"AND m.narrator IS NOT NULL AND m.narrator <> ''",
|
"AND m.narrator IS NOT NULL AND m.narrator <> ''",
|
||||||
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||||
|
|
||||||
|
List<AppFilterOptions.CountedOption> readStatuses = queryReadStatusCounts(
|
||||||
|
userId, scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||||
|
|
||||||
AppFilterOptions result = AppFilterOptions.builder()
|
AppFilterOptions result = AppFilterOptions.builder()
|
||||||
.authors(authors)
|
.authors(authors)
|
||||||
.languages(languages)
|
.languages(languages)
|
||||||
.fileTypes(fileTypes)
|
.fileTypes(fileTypes)
|
||||||
.readStatuses(getReadStatusOptions())
|
.readStatuses(readStatuses)
|
||||||
.categories(categories)
|
.categories(categories)
|
||||||
.publishers(publishers)
|
.publishers(publishers)
|
||||||
.series(seriesOptions)
|
.series(seriesOptions)
|
||||||
@@ -514,10 +522,26 @@ public class AppBookService {
|
|||||||
.getResultList());
|
.getResultList());
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<String> getReadStatusOptions() {
|
private List<AppFilterOptions.CountedOption> queryReadStatusCounts(
|
||||||
return Arrays.stream(ReadStatus.values())
|
Long userId, String scopeClause, Set<Long> accessibleLibraryIds,
|
||||||
.filter(s -> s != ReadStatus.UNSET)
|
Long libraryId, Long shelfId, Set<Long> magicBookIds) {
|
||||||
.map(Enum::name)
|
String jpql = "SELECT ubp.readStatus, COUNT(DISTINCT ubp.book.id) FROM UserBookProgressEntity ubp"
|
||||||
|
+ " WHERE ubp.user.id = :userId"
|
||||||
|
+ " AND ubp.readStatus <> org.booklore.model.enums.ReadStatus.UNSET"
|
||||||
|
+ " AND ubp.book.id IN ("
|
||||||
|
+ " SELECT b.id FROM BookEntity b"
|
||||||
|
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
|
||||||
|
+ " AND b.bookFiles IS NOT EMPTY"
|
||||||
|
+ scopeClause
|
||||||
|
+ " )"
|
||||||
|
+ " GROUP BY ubp.readStatus ORDER BY COUNT(DISTINCT ubp.book.id) DESC";
|
||||||
|
var q = entityManager.createQuery(jpql, Tuple.class);
|
||||||
|
q.setParameter("userId", userId);
|
||||||
|
setFilterQueryParams(q, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
|
||||||
|
return q.getResultList().stream()
|
||||||
|
.map(t -> new AppFilterOptions.CountedOption(
|
||||||
|
t.get(0, ReadStatus.class).name(),
|
||||||
|
t.get(1, Long.class)))
|
||||||
.toList();
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -624,16 +648,22 @@ public class AppBookService {
|
|||||||
specs.add(AppBookSpecification.inShelf(req.shelfId()));
|
specs.add(AppBookSpecification.inShelf(req.shelfId()));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (req.status() != null) {
|
if (req.status() != null && !req.status().isEmpty()) {
|
||||||
specs.add(AppBookSpecification.withReadStatus(req.status(), userId));
|
List<String> cleaned = BookListRequest.cleanValues(req.status());
|
||||||
|
if (!cleaned.isEmpty()) {
|
||||||
|
specs.add(AppBookSpecification.withReadStatuses(cleaned, userId, req.effectiveFilterMode()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (req.search() != null && !req.search().trim().isEmpty()) {
|
if (req.search() != null && !req.search().trim().isEmpty()) {
|
||||||
specs.add(AppBookSpecification.searchText(req.search()));
|
specs.add(AppBookSpecification.searchText(req.search()));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (req.fileType() != null) {
|
if (req.fileType() != null && !req.fileType().isEmpty()) {
|
||||||
specs.add(AppBookSpecification.withFileType(req.fileType()));
|
List<String> cleaned = BookListRequest.cleanValues(req.fileType());
|
||||||
|
if (!cleaned.isEmpty()) {
|
||||||
|
specs.add(AppBookSpecification.withFileTypes(cleaned, req.effectiveFilterMode()));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (req.minRating() != null) {
|
if (req.minRating() != null) {
|
||||||
|
|||||||
@@ -1,16 +1,19 @@
|
|||||||
package org.booklore.app.specification;
|
package org.booklore.app.specification;
|
||||||
|
|
||||||
|
import org.booklore.exception.APIException;
|
||||||
import org.booklore.model.entity.*;
|
import org.booklore.model.entity.*;
|
||||||
import org.booklore.model.enums.BookFileType;
|
import org.booklore.model.enums.BookFileType;
|
||||||
import org.booklore.model.enums.ReadStatus;
|
import org.booklore.model.enums.ReadStatus;
|
||||||
import jakarta.persistence.criteria.*;
|
import jakarta.persistence.criteria.*;
|
||||||
import org.springframework.data.jpa.domain.Specification;
|
import org.springframework.data.jpa.domain.Specification;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.time.temporal.ChronoUnit;
|
import java.time.temporal.ChronoUnit;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collection;
|
import java.util.Collection;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
public class AppBookSpecification {
|
public class AppBookSpecification {
|
||||||
|
|
||||||
@@ -172,6 +175,100 @@ public class AppBookSpecification {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Filter books by multiple file types with mode support.
|
||||||
|
* OR = books with at least one file of ANY listed type
|
||||||
|
* AND = books with files of ALL listed types
|
||||||
|
* NOT = books with NONE of the listed file types
|
||||||
|
*/
|
||||||
|
public static Specification<BookEntity> withFileTypes(List<String> fileTypes, String mode) {
|
||||||
|
return (root, query, cb) -> {
|
||||||
|
List<String> unknown = new ArrayList<>();
|
||||||
|
List<BookFileType> parsed = fileTypes.stream()
|
||||||
|
.filter(s -> s != null && !s.isBlank())
|
||||||
|
.map(s -> {
|
||||||
|
String trimmed = s.trim().toUpperCase();
|
||||||
|
try {
|
||||||
|
return BookFileType.valueOf(trimmed);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
unknown.add(s.trim());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.toList();
|
||||||
|
if (!unknown.isEmpty()) {
|
||||||
|
throw new APIException("Invalid fileType values: " + unknown + ". Valid values: " + List.of(BookFileType.values()), HttpStatus.BAD_REQUEST);
|
||||||
|
}
|
||||||
|
if (parsed.isEmpty()) return cb.conjunction();
|
||||||
|
|
||||||
|
if ("and".equals(mode)) {
|
||||||
|
List<Predicate> predicates = new ArrayList<>();
|
||||||
|
for (BookFileType ft : parsed) {
|
||||||
|
Subquery<Long> sub = query.subquery(Long.class);
|
||||||
|
Root<BookFileEntity> bfRoot = sub.from(BookFileEntity.class);
|
||||||
|
sub.select(bfRoot.get("book").get("id"))
|
||||||
|
.where(cb.equal(bfRoot.get("bookType"), ft));
|
||||||
|
predicates.add(root.get("id").in(sub));
|
||||||
|
}
|
||||||
|
return cb.and(predicates.toArray(new Predicate[0]));
|
||||||
|
}
|
||||||
|
|
||||||
|
Subquery<Long> sub = query.subquery(Long.class);
|
||||||
|
Root<BookFileEntity> bfRoot = sub.from(BookFileEntity.class);
|
||||||
|
sub.select(bfRoot.get("book").get("id"))
|
||||||
|
.where(bfRoot.get("bookType").in(parsed));
|
||||||
|
|
||||||
|
if ("not".equals(mode)) {
|
||||||
|
return cb.not(root.get("id").in(sub));
|
||||||
|
}
|
||||||
|
return root.get("id").in(sub);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Filter books by multiple read statuses with mode support (per-user).
|
||||||
|
* OR = books with ANY of the listed read statuses
|
||||||
|
* AND = impossible for a single-value field, treated as OR
|
||||||
|
* NOT = books with NONE of the listed read statuses
|
||||||
|
*/
|
||||||
|
public static Specification<BookEntity> withReadStatuses(List<String> statuses, Long userId, String mode) {
|
||||||
|
return (root, query, cb) -> {
|
||||||
|
if (userId == null) return cb.conjunction();
|
||||||
|
List<String> unknown = new ArrayList<>();
|
||||||
|
List<ReadStatus> parsed = statuses.stream()
|
||||||
|
.filter(s -> s != null && !s.isBlank())
|
||||||
|
.map(s -> {
|
||||||
|
String trimmed = s.trim().toUpperCase();
|
||||||
|
try {
|
||||||
|
return ReadStatus.valueOf(trimmed);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
unknown.add(s.trim());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.filter(Objects::nonNull)
|
||||||
|
.toList();
|
||||||
|
if (!unknown.isEmpty()) {
|
||||||
|
throw new APIException("Invalid status values: " + unknown + ". Valid values: " + List.of(ReadStatus.values()), HttpStatus.BAD_REQUEST);
|
||||||
|
}
|
||||||
|
if (parsed.isEmpty()) return cb.conjunction();
|
||||||
|
|
||||||
|
Subquery<Long> sub = query.subquery(Long.class);
|
||||||
|
Root<UserBookProgressEntity> progressRoot = sub.from(UserBookProgressEntity.class);
|
||||||
|
sub.select(progressRoot.get("book").get("id"))
|
||||||
|
.where(
|
||||||
|
cb.equal(progressRoot.get("user").get("id"), userId),
|
||||||
|
progressRoot.get("readStatus").in(parsed)
|
||||||
|
);
|
||||||
|
|
||||||
|
if ("not".equals(mode)) {
|
||||||
|
return cb.not(root.get("id").in(sub));
|
||||||
|
}
|
||||||
|
return root.get("id").in(sub);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Filter books where the user's personal rating is >= minRating.
|
* Filter books where the user's personal rating is >= minRating.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -79,11 +79,17 @@ class AppFilterControllerTest {
|
|||||||
List<AppFilterOptions.LanguageOption> languages = langCodes.stream()
|
List<AppFilterOptions.LanguageOption> languages = langCodes.stream()
|
||||||
.map(code -> new AppFilterOptions.LanguageOption(code, code, 1L))
|
.map(code -> new AppFilterOptions.LanguageOption(code, code, 1L))
|
||||||
.toList();
|
.toList();
|
||||||
|
List<AppFilterOptions.CountedOption> fileTypeOptions = fileTypes.stream()
|
||||||
|
.map(ft -> new AppFilterOptions.CountedOption(ft, 1L))
|
||||||
|
.toList();
|
||||||
|
List<AppFilterOptions.CountedOption> readStatusOptions = List.of("READ", "READING", "UNREAD").stream()
|
||||||
|
.map(rs -> new AppFilterOptions.CountedOption(rs, 1L))
|
||||||
|
.toList();
|
||||||
return AppFilterOptions.builder()
|
return AppFilterOptions.builder()
|
||||||
.authors(authors)
|
.authors(authors)
|
||||||
.languages(languages)
|
.languages(languages)
|
||||||
.fileTypes(fileTypes)
|
.fileTypes(fileTypeOptions)
|
||||||
.readStatuses(List.of("READ", "READING", "UNREAD"))
|
.readStatuses(readStatusOptions)
|
||||||
.build();
|
.build();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-10
@@ -12,7 +12,6 @@ import org.booklore.model.dto.Library;
|
|||||||
import org.booklore.model.entity.BookLoreUserEntity;
|
import org.booklore.model.entity.BookLoreUserEntity;
|
||||||
import org.booklore.model.entity.BookEntity;
|
import org.booklore.model.entity.BookEntity;
|
||||||
import org.booklore.model.entity.ShelfEntity;
|
import org.booklore.model.entity.ShelfEntity;
|
||||||
import org.booklore.model.enums.BookFileType;
|
|
||||||
import org.booklore.repository.BookRepository;
|
import org.booklore.repository.BookRepository;
|
||||||
import org.booklore.repository.ShelfRepository;
|
import org.booklore.repository.ShelfRepository;
|
||||||
import org.booklore.repository.UserBookFileProgressRepository;
|
import org.booklore.repository.UserBookFileProgressRepository;
|
||||||
@@ -81,7 +80,7 @@ class AppBookServiceFilterOptionsTest {
|
|||||||
assertNotNull(result.authors());
|
assertNotNull(result.authors());
|
||||||
assertNotNull(result.languages());
|
assertNotNull(result.languages());
|
||||||
assertNotNull(result.fileTypes());
|
assertNotNull(result.fileTypes());
|
||||||
assertFalse(result.readStatuses().isEmpty());
|
assertNotNull(result.readStatuses());
|
||||||
}
|
}
|
||||||
|
|
||||||
// -------------------------------------------------------------------------
|
// -------------------------------------------------------------------------
|
||||||
@@ -96,7 +95,7 @@ class AppBookServiceFilterOptionsTest {
|
|||||||
AppFilterOptions result = service.getFilterOptions(5L, null, null);
|
AppFilterOptions result = service.getFilterOptions(5L, null, null);
|
||||||
|
|
||||||
assertNotNull(result);
|
assertNotNull(result);
|
||||||
verify(entityManager, times(9)).createQuery(anyString(), any(Class.class));
|
verify(entityManager, times(10)).createQuery(anyString(), any(Class.class));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -179,7 +178,7 @@ class AppBookServiceFilterOptionsTest {
|
|||||||
assertTrue(result.authors().isEmpty());
|
assertTrue(result.authors().isEmpty());
|
||||||
assertTrue(result.languages().isEmpty());
|
assertTrue(result.languages().isEmpty());
|
||||||
assertTrue(result.fileTypes().isEmpty());
|
assertTrue(result.fileTypes().isEmpty());
|
||||||
assertFalse(result.readStatuses().isEmpty());
|
assertTrue(result.readStatuses().isEmpty());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -263,13 +262,7 @@ class AppBookServiceFilterOptionsTest {
|
|||||||
when(tupleQuery.setMaxResults(anyInt())).thenReturn(tupleQuery);
|
when(tupleQuery.setMaxResults(anyInt())).thenReturn(tupleQuery);
|
||||||
when(tupleQuery.getResultList()).thenReturn(Collections.emptyList());
|
when(tupleQuery.getResultList()).thenReturn(Collections.emptyList());
|
||||||
|
|
||||||
TypedQuery<BookFileType> ftQuery = mock(TypedQuery.class);
|
|
||||||
when(ftQuery.setParameter(anyString(), any())).thenReturn(ftQuery);
|
|
||||||
when(ftQuery.getResultList()).thenReturn(Collections.emptyList());
|
|
||||||
|
|
||||||
when(entityManager.createQuery(anyString(), eq(Tuple.class)))
|
when(entityManager.createQuery(anyString(), eq(Tuple.class)))
|
||||||
.thenReturn(tupleQuery);
|
.thenReturn(tupleQuery);
|
||||||
when(entityManager.createQuery(anyString(), eq(BookFileType.class)))
|
|
||||||
.thenReturn(ftQuery);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -318,7 +318,11 @@
|
|||||||
></app-book-table>
|
></app-book-table>
|
||||||
}
|
}
|
||||||
@if (currentViewMode === 'grid') {
|
@if (currentViewMode === 'grid') {
|
||||||
<virtual-scroller class="virtual-scroller" #scroll [items]="books" [bufferAmount]="16" (vsEnd)="onScrollEnd()">
|
<virtual-scroller class="virtual-scroller" #scroll
|
||||||
|
[items]="books"
|
||||||
|
[bufferAmount]="16"
|
||||||
|
[compareItems]="compareBookItems"
|
||||||
|
(vsEnd)="onScrollEnd()">
|
||||||
<div
|
<div
|
||||||
class="grid"
|
class="grid"
|
||||||
#container
|
#container
|
||||||
@@ -326,7 +330,7 @@
|
|||||||
@for (book of scroll.viewPortItems; let i = $index; track book.id) {
|
@for (book of scroll.viewPortItems; let i = $index; track book.id) {
|
||||||
<div
|
<div
|
||||||
class="virtual-scroller-item"
|
class="virtual-scroller-item"
|
||||||
[ngStyle]="{width: currentCardSize.width + 'px', height: getCardHeight(book) + 'px'}">
|
[ngStyle]="{width: currentCardSize.width + 'px', height: currentCardSize.height + 'px'}">
|
||||||
<app-book-card
|
<app-book-card
|
||||||
[index]="bookIndexById().get(book.id) ?? i"
|
[index]="bookIndexById().get(book.id) ?? i"
|
||||||
[book]="book"
|
[book]="book"
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import {AfterViewInit, Component, HostListener, computed, effect, inject, OnDestroy, OnInit, signal, untracked, ViewChild} from '@angular/core';
|
import {AfterViewInit, ChangeDetectionStrategy, Component, HostListener, computed, effect, inject, OnDestroy, OnInit, signal, untracked, ViewChild} from '@angular/core';
|
||||||
import {toObservable, toSignal} from '@angular/core/rxjs-interop';
|
import {toObservable, toSignal} from '@angular/core/rxjs-interop';
|
||||||
import {ActivatedRoute, NavigationStart, Router} from '@angular/router';
|
import {ActivatedRoute, NavigationStart, Router} from '@angular/router';
|
||||||
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
|
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
|
||||||
@@ -72,6 +72,7 @@ export enum EntityType {
|
|||||||
standalone: true,
|
standalone: true,
|
||||||
templateUrl: './book-browser.component.html',
|
templateUrl: './book-browser.component.html',
|
||||||
styleUrls: ['./book-browser.component.scss'],
|
styleUrls: ['./book-browser.component.scss'],
|
||||||
|
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||||
imports: [
|
imports: [
|
||||||
Button, VirtualScrollerModule, BookCardComponent, Menu, InputText, FormsModule,
|
Button, VirtualScrollerModule, BookCardComponent, Menu, InputText, FormsModule,
|
||||||
BookTableComponent, BookFilterComponent, Tooltip, NgClass, NgStyle, Popover,
|
BookTableComponent, BookFilterComponent, Tooltip, NgClass, NgStyle, Popover,
|
||||||
@@ -226,8 +227,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
case 'mood': scopeFilters.mood = strValues; break;
|
case 'mood': scopeFilters.mood = strValues; break;
|
||||||
case 'narrator': scopeFilters.narrator = strValues; break;
|
case 'narrator': scopeFilters.narrator = strValues; break;
|
||||||
case 'language': scopeFilters.language = strValues; break;
|
case 'language': scopeFilters.language = strValues; break;
|
||||||
case 'readStatus': scopeFilters.status = strValues[0]; break;
|
case 'readStatus': scopeFilters.status = strValues; break;
|
||||||
case 'bookType': scopeFilters.fileType = strValues[0]; break;
|
case 'bookType': scopeFilters.fileType = strValues; break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const mode = this.selectedFilterMode();
|
const mode = this.selectedFilterMode();
|
||||||
@@ -256,34 +257,24 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
return Number.isNaN(entityId) ? entityType : `${entityType}:${entityId}`;
|
return Number.isNaN(entityId) ? entityType : `${entityType}:${entityId}`;
|
||||||
});
|
});
|
||||||
|
|
||||||
private readonly pipelineInputs = computed(() => ({
|
private readonly pipelineInputs = computed(() => this.appBooksApi.books());
|
||||||
books: this.appBooksApi.books(),
|
|
||||||
entity: this.entityInfo(),
|
|
||||||
search: this.debouncedSearchTerm(),
|
|
||||||
filter: this.selectedFilter(),
|
|
||||||
filterMode: this.selectedFilterMode(),
|
|
||||||
collapsed: this.seriesCollapsed(),
|
|
||||||
forceExpand: this.forceExpandSeries(),
|
|
||||||
sort: this.sortCriteria(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
private readonly renderBooksEffect = effect((onCleanup) => {
|
private readonly renderBooksEffect = effect((onCleanup) => {
|
||||||
const contextKey = this.booksContextKey();
|
const contextKey = this.booksContextKey();
|
||||||
this.pipelineInputs();
|
const books = this.pipelineInputs();
|
||||||
|
|
||||||
const shouldRefreshInPlace = untracked(() => this.hasRenderedBooks()) && contextKey === this.lastBooksContextKey;
|
const shouldRefreshInPlace = untracked(() => this.hasRenderedBooks()) && contextKey === this.lastBooksContextKey;
|
||||||
this.lastBooksContextKey = contextKey;
|
this.lastBooksContextKey = contextKey;
|
||||||
|
|
||||||
if (shouldRefreshInPlace) {
|
if (shouldRefreshInPlace) {
|
||||||
const requestId = this.booksRenderState.begin('refresh');
|
this.booksRenderState.update(books);
|
||||||
this.booksRenderState.commit(requestId, this.appBooksApi.books());
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const requestId = this.booksRenderState.begin('reset');
|
const requestId = this.booksRenderState.begin('reset');
|
||||||
|
|
||||||
const timeout = globalThis.setTimeout(() => {
|
const timeout = globalThis.setTimeout(() => {
|
||||||
this.booksRenderState.commit(requestId, this.appBooksApi.books());
|
this.booksRenderState.commit(requestId, books);
|
||||||
});
|
});
|
||||||
|
|
||||||
onCleanup(() => {
|
onCleanup(() => {
|
||||||
@@ -302,6 +293,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
return map;
|
return map;
|
||||||
});
|
});
|
||||||
|
readonly compareBookItems = (a: Book, b: Book): boolean => a?.id === b?.id;
|
||||||
protected resetFilterSubject = new Subject<void>();
|
protected resetFilterSubject = new Subject<void>();
|
||||||
|
|
||||||
readonly skeletonSlots = Array.from({length: 24}, (_, index) => index);
|
readonly skeletonSlots = Array.from({length: 24}, (_, index) => index);
|
||||||
|
|||||||
+2
-8
@@ -152,15 +152,9 @@ export class BookFilterService {
|
|||||||
bookCount: lang.count,
|
bookCount: lang.count,
|
||||||
}));
|
}));
|
||||||
case 'readStatus':
|
case 'readStatus':
|
||||||
return (options.readStatuses ?? []).map((status: string) => ({
|
return this.countedToFilters(options.readStatuses);
|
||||||
value: {id: status, name: status},
|
|
||||||
bookCount: 0,
|
|
||||||
}));
|
|
||||||
case 'bookType':
|
case 'bookType':
|
||||||
return (options.fileTypes ?? []).map((ft: string) => ({
|
return this.countedToFilters(options.fileTypes);
|
||||||
value: {id: ft, name: ft},
|
|
||||||
bookCount: 0,
|
|
||||||
}));
|
|
||||||
default:
|
default:
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,6 +26,12 @@ export class DeferredRenderState<T> {
|
|||||||
return this.activeRequestId;
|
return this.activeRequestId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Direct update without refresh animation used for in-place data swaps. */
|
||||||
|
update(value: T): void {
|
||||||
|
this._value.set(value);
|
||||||
|
this._isRefreshing.set(false);
|
||||||
|
}
|
||||||
|
|
||||||
commit(requestId: number, value: T): boolean {
|
commit(requestId: number, value: T): boolean {
|
||||||
if (requestId !== this.activeRequestId) {
|
if (requestId !== this.activeRequestId) {
|
||||||
return false;
|
return false;
|
||||||
|
|||||||
@@ -30,8 +30,8 @@ export interface AppBookSummary {
|
|||||||
export interface AppFilterOptions {
|
export interface AppFilterOptions {
|
||||||
authors: CountedOption[];
|
authors: CountedOption[];
|
||||||
languages: LanguageOption[];
|
languages: LanguageOption[];
|
||||||
readStatuses: string[];
|
readStatuses: CountedOption[];
|
||||||
fileTypes: string[];
|
fileTypes: CountedOption[];
|
||||||
categories: CountedOption[];
|
categories: CountedOption[];
|
||||||
publishers: CountedOption[];
|
publishers: CountedOption[];
|
||||||
series: CountedOption[];
|
series: CountedOption[];
|
||||||
@@ -56,9 +56,9 @@ export interface AppBookFilters {
|
|||||||
shelfId?: number;
|
shelfId?: number;
|
||||||
magicShelfId?: number;
|
magicShelfId?: number;
|
||||||
unshelved?: boolean;
|
unshelved?: boolean;
|
||||||
status?: string;
|
status?: string[];
|
||||||
search?: string;
|
search?: string;
|
||||||
fileType?: string;
|
fileType?: string[];
|
||||||
minRating?: number;
|
minRating?: number;
|
||||||
maxRating?: number;
|
maxRating?: number;
|
||||||
authors?: string[];
|
authors?: string[];
|
||||||
|
|||||||
@@ -62,6 +62,14 @@ export class AppBooksApiService {
|
|||||||
const data = this.booksQuery.data();
|
const data = this.booksQuery.data();
|
||||||
if (!data) return [];
|
if (!data) return [];
|
||||||
return data.pages.flatMap(page => page.content.map(summaryToBook));
|
return data.pages.flatMap(page => page.content.map(summaryToBook));
|
||||||
|
}, {
|
||||||
|
equal: (a, b) => {
|
||||||
|
if (a.length !== b.length) return false;
|
||||||
|
for (let i = 0; i < a.length; i++) {
|
||||||
|
if (a[i].id !== b[i].id) return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
readonly totalElements = computed(() => {
|
readonly totalElements = computed(() => {
|
||||||
@@ -126,8 +134,6 @@ export class AppBooksApiService {
|
|||||||
if (filters.shelfId) params = params.set('shelfId', filters.shelfId.toString());
|
if (filters.shelfId) params = params.set('shelfId', filters.shelfId.toString());
|
||||||
if (filters.magicShelfId) params = params.set('magicShelfId', filters.magicShelfId.toString());
|
if (filters.magicShelfId) params = params.set('magicShelfId', filters.magicShelfId.toString());
|
||||||
if (filters.unshelved) params = params.set('unshelved', 'true');
|
if (filters.unshelved) params = params.set('unshelved', 'true');
|
||||||
if (filters.status) params = params.set('status', filters.status);
|
|
||||||
if (filters.fileType) params = params.set('fileType', filters.fileType);
|
|
||||||
if (filters.minRating != null) params = params.set('minRating', filters.minRating.toString());
|
if (filters.minRating != null) params = params.set('minRating', filters.minRating.toString());
|
||||||
if (filters.maxRating != null) params = params.set('maxRating', filters.maxRating.toString());
|
if (filters.maxRating != null) params = params.set('maxRating', filters.maxRating.toString());
|
||||||
if (filters.filterMode) params = params.set('filterMode', filters.filterMode);
|
if (filters.filterMode) params = params.set('filterMode', filters.filterMode);
|
||||||
@@ -142,6 +148,8 @@ export class AppBooksApiService {
|
|||||||
['tag', filters.tag],
|
['tag', filters.tag],
|
||||||
['mood', filters.mood],
|
['mood', filters.mood],
|
||||||
['narrator', filters.narrator],
|
['narrator', filters.narrator],
|
||||||
|
['status', filters.status],
|
||||||
|
['fileType', filters.fileType],
|
||||||
];
|
];
|
||||||
for (const [key, values] of arrayFilters) {
|
for (const [key, values] of arrayFilters) {
|
||||||
if (values?.length) {
|
if (values?.length) {
|
||||||
@@ -178,7 +186,7 @@ function summaryToBook(summary: AppBookSummary): Book {
|
|||||||
audiobookCoverUpdatedOn: summary.audiobookCoverUpdatedOn,
|
audiobookCoverUpdatedOn: summary.audiobookCoverUpdatedOn,
|
||||||
},
|
},
|
||||||
primaryFile: summary.primaryFileType
|
primaryFile: summary.primaryFileType
|
||||||
? {bookType: summary.primaryFileType as BookType}
|
? {bookType: summary.primaryFileType as BookType, extension: summary.primaryFileType.toLowerCase()}
|
||||||
: null,
|
: null,
|
||||||
pdfProgress: summary.readProgress != null
|
pdfProgress: summary.readProgress != null
|
||||||
? {page: 0, percentage: summary.readProgress}
|
? {page: 0, percentage: summary.readProgress}
|
||||||
|
|||||||
Reference in New Issue
Block a user