feat(filters): add age rating and content rating filters, improve filter options (#479)

* feat(filters): add age rating and content rating filters, improve filter options

* fix(book-browser): update view mode handling to use reactive properties

* fix(book-browser): update view mode handling to use getter methods

* feat(filters): improve filtering capabilities with comic creators and validate input values

* test(filters): fix AppBookServiceFilterOptionsTest with additional query mocks

* fix(filters): improve error handling for invalid filter bucket IDs and roles

* refactor(book-browser): remove unused computedFilterLabel

* fix(filters): validate shelfStatus values and throw error for invalid inputs

* test(book-browser): mock TranslocoService for language changes in tests

* fix(book-browser): ensure active language is set before syncing browser state
This commit is contained in:
brios
2026-04-22 17:27:15 -04:00
committed by Zach Yale
parent fcee609b15
commit 502f5738bf
20 changed files with 1456 additions and 525 deletions
@@ -7,6 +7,7 @@ import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.Instant;
import java.time.LocalDate;
import java.util.List;
@Data
@@ -31,4 +32,12 @@ public class AppBookSummary {
private Instant coverUpdatedOn;
private Instant audiobookCoverUpdatedOn;
private Boolean isPhysical;
// Metadata for filtering
private LocalDate publishedDate;
private Integer pageCount;
private Integer ageRating;
private String contentRating;
private Float metadataMatchScore;
private Long fileSizeKb;
}
@@ -17,7 +17,24 @@ public record AppFilterOptions(
List<CountedOption> series,
List<CountedOption> tags,
List<CountedOption> moods,
List<CountedOption> narrators) {
List<CountedOption> narrators,
List<CountedOption> ageRatings,
List<CountedOption> contentRatings,
List<CountedOption> matchScores,
List<CountedOption> publishedYears,
List<CountedOption> fileSizes,
List<CountedOption> personalRatings,
List<CountedOption> amazonRatings,
List<CountedOption> goodreadsRatings,
List<CountedOption> hardcoverRatings,
List<CountedOption> pageCounts,
List<CountedOption> shelfStatuses,
List<CountedOption> comicCharacters,
List<CountedOption> comicTeams,
List<CountedOption> comicLocations,
List<CountedOption> comicCreators,
List<CountedOption> shelves,
List<CountedOption> libraries) {
public record LanguageOption(String code, String label, long count) {}
@@ -24,6 +24,23 @@ public record BookListRequest(
@Size(max = 20) List<String> tag,
@Size(max = 20) List<String> mood,
@Size(max = 20) List<String> narrator,
@Size(max = 20) List<String> ageRating,
@Size(max = 20) List<String> contentRating,
@Size(max = 20) List<String> matchScore,
@Size(max = 20) List<String> publishedDate,
@Size(max = 20) List<String> fileSize,
@Size(max = 20) List<String> personalRating,
@Size(max = 20) List<String> amazonRating,
@Size(max = 20) List<String> goodreadsRating,
@Size(max = 20) List<String> hardcoverRating,
@Size(max = 20) List<String> pageCount,
@Size(max = 20) List<String> shelfStatus,
@Size(max = 20) List<String> comicCharacter,
@Size(max = 20) List<String> comicTeam,
@Size(max = 20) List<String> comicLocation,
@Size(max = 20) List<String> comicCreator,
@Size(max = 20) List<String> shelves,
@Size(max = 20) List<String> libraries,
Long magicShelfId,
Boolean unshelved,
String filterMode) {
@@ -35,6 +35,12 @@ public interface AppBookMapper {
@Mapping(target = "coverUpdatedOn", source = "book.metadata.coverUpdatedOn")
@Mapping(target = "audiobookCoverUpdatedOn", source = "book.metadata.audiobookCoverUpdatedOn")
@Mapping(target = "isPhysical", source = "book.isPhysical")
@Mapping(target = "publishedDate", source = "book.metadata.publishedDate")
@Mapping(target = "pageCount", source = "book.metadata.pageCount")
@Mapping(target = "ageRating", source = "book.metadata.ageRating")
@Mapping(target = "contentRating", source = "book.metadata.contentRating")
@Mapping(target = "metadataMatchScore", source = "book.metadataMatchScore")
@Mapping(target = "fileSizeKb", source = "book", qualifiedByName = "mapFileSizeKb")
AppBookSummary toSummary(BookEntity book, UserBookProgressEntity progress);
@Mapping(target = "id", source = "book.id")
@@ -116,6 +122,13 @@ public interface AppBookMapper {
return "/api/books/" + book.getId() + "/cover";
}
@Named("mapFileSizeKb")
default Long mapFileSizeKb(BookEntity book) {
if (book == null) return null;
BookFileEntity primaryFile = book.getPrimaryBookFile();
return primaryFile != null ? primaryFile.getFileSizeKb() : null;
}
@Named("mapShelves")
default List<AppShelfSummary> mapShelves(Set<ShelfEntity> shelves) {
if (shelves == null || shelves.isEmpty()) {
@@ -20,6 +20,7 @@ import org.booklore.model.dto.Library;
import org.booklore.model.dto.request.ReadProgressRequest;
import org.booklore.model.entity.*;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.ComicCreatorRole;
import org.booklore.model.enums.ReadStatus;
import org.booklore.repository.BookRepository;
import org.booklore.repository.ShelfRepository;
@@ -401,52 +402,45 @@ public class AppBookService {
}
}
// Cache lookup avoid re-running 9 aggregate queries within the TTL window
// Cache lookup avoid re-running 26+ aggregate queries within the TTL window
String cacheKey = userId + ":" + libraryId + ":" + shelfId + ":" + magicShelfId;
AppFilterOptions cached = filterOptionsCache.getIfPresent(cacheKey);
if (cached != null) {
return cached;
}
// Build unified scoping Specification for all aggregate queries
Specification<BookEntity> baseSpec = buildBaseSpecification(accessibleLibraryIds, libraryId);
Specification<BookEntity> magicShelfSpec = null;
if (magicShelfId != null) {
magicShelfSpec = magicShelfBookService.toSpecification(userId, magicShelfId);
baseSpec = baseSpec.and(magicShelfSpec);
}
if (shelfId != null) {
baseSpec = baseSpec.and(AppBookSpecification.inShelf(shelfId));
}
Set<Long> magicBookIds = null;
if (magicShelfId != null) {
magicBookIds = resolveMagicShelfBookIds(magicShelfId, userId);
magicBookIds = resolveMagicShelfBookIds(magicShelfSpec);
if (magicBookIds.isEmpty()) {
AppFilterOptions empty = AppFilterOptions.builder()
.authors(Collections.emptyList())
.languages(Collections.emptyList())
.fileTypes(Collections.emptyList())
.readStatuses(Collections.emptyList())
.categories(Collections.emptyList())
.publishers(Collections.emptyList())
.series(Collections.emptyList())
.tags(Collections.emptyList())
.moods(Collections.emptyList())
.narrators(Collections.emptyList())
.build();
filterOptionsCache.put(cacheKey, empty);
return empty;
return emptyFilterOptions(cacheKey);
}
}
// Build scoping clauses
String libraryClause = "";
String shelfClause = "";
String magicBookClause = "";
if (magicBookIds != null) {
magicBookClause = "AND b.id IN :magicBookIds";
} else if (shelfId != null) {
shelfClause = "AND b.id IN (SELECT sb.id FROM ShelfEntity s JOIN s.bookEntities sb WHERE s.id = :shelfId)";
}
if (libraryId != null) {
libraryClause = "AND b.library.id = :libraryId";
} else if (accessibleLibraryIds != null) {
libraryClause = "AND b.library.id IN :libraryIds";
}
// Build the optional WHERE suffix once — each clause already starts with "AND"
String scopeClause = buildScopeClause(libraryClause, shelfClause, magicBookClause);
List<AppFilterOptions.CountedOption> authors = queryCountedOptions(
@@ -463,20 +457,9 @@ public class AppBookService {
c.count()))
.toList();
String fileTypeQuery = "SELECT bf.bookType, COUNT(DISTINCT b.id) FROM BookEntity b"
+ " JOIN b.bookFiles bf"
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
+ " AND b.bookFiles IS NOT EMPTY"
+ " AND bf.isBookFormat = true"
+ scopeClause
+ " GROUP BY bf.bookType ORDER BY COUNT(DISTINCT b.id) DESC";
var ftQ = entityManager.createQuery(fileTypeQuery, Tuple.class);
setFilterQueryParams(ftQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
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> fileTypes = queryCountedOptions(
"bf.bookType", "JOIN b.bookFiles bf", "AND bf.isBookFormat = true",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> categories = queryCountedOptions(
"c.name", "JOIN b.metadata m JOIN m.categories c", "",
@@ -508,6 +491,131 @@ public class AppBookService {
List<AppFilterOptions.CountedOption> readStatuses = queryReadStatusCounts(
userId, scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> ageRatings = queryGroupedCount(
"CASE " +
" WHEN m.ageRating >= 0 AND m.ageRating < 6 THEN '0' " +
" WHEN m.ageRating >= 6 AND m.ageRating < 10 THEN '6' " +
" WHEN m.ageRating >= 10 AND m.ageRating < 13 THEN '10' " +
" WHEN m.ageRating >= 13 AND m.ageRating < 16 THEN '13' " +
" WHEN m.ageRating >= 16 AND m.ageRating < 18 THEN '16' " +
" WHEN m.ageRating >= 18 AND m.ageRating < 21 THEN '18' " +
" WHEN m.ageRating >= 21 THEN '21' " +
"END",
"JOIN b.metadata m", "AND m.ageRating IS NOT NULL",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> contentRatings = queryCountedOptions(
"m.contentRating", "JOIN b.metadata m",
"AND m.contentRating IS NOT NULL AND m.contentRating <> ''",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> matchScores = queryGroupedCount(
"CASE " +
" WHEN b.metadataMatchScore >= 0.95 THEN '0' " +
" WHEN b.metadataMatchScore >= 0.90 THEN '1' " +
" WHEN b.metadataMatchScore >= 0.80 THEN '2' " +
" WHEN b.metadataMatchScore >= 0.70 THEN '3' " +
" WHEN b.metadataMatchScore >= 0.50 THEN '4' " +
" WHEN b.metadataMatchScore >= 0.30 THEN '5' " +
" WHEN b.metadataMatchScore >= 0.00 THEN '6' " +
"END",
"", "AND b.metadataMatchScore IS NOT NULL",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> publishedYears = queryCountedOptions(
"CAST(YEAR(m.publishedDate) AS string)", "JOIN b.metadata m",
"AND m.publishedDate IS NOT NULL",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> fileSizes = queryGroupedCount(
"CASE " +
" WHEN bf.fileSizeKb < 1024 THEN '0' " +
" WHEN bf.fileSizeKb < 10240 THEN '1' " +
" WHEN bf.fileSizeKb < 51200 THEN '2' " +
" WHEN bf.fileSizeKb < 102400 THEN '3' " +
" WHEN bf.fileSizeKb < 512000 THEN '4' " +
" WHEN bf.fileSizeKb < 1048576 THEN '5' " +
" WHEN bf.fileSizeKb < 2097152 THEN '6' " +
" ELSE '7' " +
"END",
"JOIN b.bookFiles bf", "AND bf.isBookFormat = true",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
String personalRatingQuery = "SELECT CAST(ubp.personalRating AS string), COUNT(DISTINCT ubp.book.id) " +
"FROM UserBookProgressEntity ubp " +
"WHERE ubp.user.id = :userId AND ubp.personalRating IS NOT NULL " +
"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 1 ORDER BY 1 DESC";
var prQ = entityManager.createQuery(personalRatingQuery, Tuple.class);
prQ.setParameter("userId", userId);
setFilterQueryParams(prQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> personalRatings = prQ.getResultList().stream()
.map(t -> new AppFilterOptions.CountedOption(t.get(0, String.class), t.get(1, Long.class)))
.toList();
List<AppFilterOptions.CountedOption> amazonRatings = queryRatingBuckets("m.amazonRating", scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> goodreadsRatings = queryRatingBuckets("m.goodreadsRating", scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> hardcoverRatings = queryRatingBuckets("m.hardcoverRating", scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> pageCounts = queryGroupedCount(
"CASE " +
" WHEN m.pageCount < 50 THEN '0' " +
" WHEN m.pageCount < 100 THEN '1' " +
" WHEN m.pageCount < 200 THEN '2' " +
" WHEN m.pageCount < 400 THEN '3' " +
" WHEN m.pageCount < 600 THEN '4' " +
" WHEN m.pageCount < 1000 THEN '5' " +
" ELSE '6' " +
"END",
"JOIN b.metadata m", "AND m.pageCount IS NOT NULL",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> shelfStatuses = queryGroupedCount(
"CASE WHEN (SELECT COUNT(s) FROM b.shelves s) > 0 THEN 'shelved' ELSE 'unshelved' END",
"", "",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> comicCharacters = queryCountedOptions(
"c.name", "JOIN b.metadata m JOIN m.comicMetadata cm JOIN cm.characters c", "",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> comicTeams = queryCountedOptions(
"t.name", "JOIN b.metadata m JOIN m.comicMetadata cm JOIN cm.teams t", "",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> comicLocations = queryCountedOptions(
"l.name", "JOIN b.metadata m JOIN m.comicMetadata cm JOIN cm.locations l", "",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
// Comic Creators — uses creatorMappings join table with role enum
String creatorJpql = "SELECT cr.name, mapping.role, COUNT(DISTINCT b.id) FROM BookEntity b"
+ " JOIN b.metadata m JOIN m.comicMetadata cm JOIN cm.creatorMappings mapping JOIN mapping.creator cr"
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
+ " AND b.bookFiles IS NOT EMPTY"
+ " " + scopeClause
+ " GROUP BY cr.name, mapping.role ORDER BY COUNT(DISTINCT b.id) DESC";
var creatorQ = entityManager.createQuery(creatorJpql, Tuple.class);
setFilterQueryParams(creatorQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
creatorQ.setMaxResults(1000);
List<AppFilterOptions.CountedOption> allCreators = creatorQ.getResultList().stream()
.map(t -> {
String name = t.get(0, String.class);
ComicCreatorRole role = t.get(1, ComicCreatorRole.class);
long count = t.get(2, Long.class);
return new AppFilterOptions.CountedOption(name + ":" + creatorRoleLabel(role), count);
})
.toList();
List<AppFilterOptions.CountedOption> shelves = queryCountedOptions(
"CAST(s.id AS string) || ':' || s.name", "JOIN b.shelves s", "",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
List<AppFilterOptions.CountedOption> libraries = queryCountedOptions(
"CAST(l.id AS string) || ':' || l.name", "JOIN b.library l", "",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
AppFilterOptions result = AppFilterOptions.builder()
.authors(authors)
.languages(languages)
@@ -519,84 +627,60 @@ public class AppBookService {
.tags(tags)
.moods(moods)
.narrators(narrators)
.ageRatings(ageRatings)
.contentRatings(contentRatings)
.matchScores(matchScores)
.publishedYears(publishedYears)
.fileSizes(fileSizes)
.personalRatings(personalRatings)
.amazonRatings(amazonRatings)
.goodreadsRatings(goodreadsRatings)
.hardcoverRatings(hardcoverRatings)
.pageCounts(pageCounts)
.shelfStatuses(shelfStatuses)
.comicCharacters(comicCharacters)
.comicTeams(comicTeams)
.comicLocations(comicLocations)
.comicCreators(allCreators)
.shelves(shelves)
.libraries(libraries)
.build();
filterOptionsCache.put(cacheKey, result);
return result;
}
private List<AppFilterOptions.CountedOption> queryCountedOptions(
String selectExpr, String joins, String extraWhere,
String scopeClause, Set<Long> accessibleLibraryIds,
Long libraryId, Long shelfId, Set<Long> magicBookIds) {
String jpql = "SELECT " + selectExpr + ", COUNT(DISTINCT b.id) FROM BookEntity b"
+ " " + joins
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
+ " AND b.bookFiles IS NOT EMPTY"
+ (extraWhere.isEmpty() ? "" : " " + extraWhere)
+ scopeClause
+ " GROUP BY " + selectExpr + " ORDER BY COUNT(DISTINCT b.id) DESC";
var q = entityManager.createQuery(jpql, Tuple.class);
setFilterQueryParams(q, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
q.setMaxResults(200);
return q.getResultList().stream()
.map(t -> new AppFilterOptions.CountedOption(t.get(0, String.class), t.get(1, Long.class)))
.toList();
}
private String buildScopeClause(String libraryClause, String shelfClause, String magicBookClause) {
var sb = new StringBuilder();
if (!libraryClause.isEmpty()) sb.append(" ").append(libraryClause);
if (!shelfClause.isEmpty()) sb.append(" ").append(shelfClause);
if (!magicBookClause.isEmpty()) sb.append(" ").append(magicBookClause);
return sb.toString();
}
private void setFilterQueryParams(jakarta.persistence.Query query, Set<Long> accessibleLibraryIds, Long libraryId, Long shelfId, Set<Long> magicBookIds) {
if (libraryId != null) {
query.setParameter("libraryId", libraryId);
} else if (accessibleLibraryIds != null) {
query.setParameter("libraryIds", accessibleLibraryIds);
}
if (shelfId != null && magicBookIds == null) {
query.setParameter("shelfId", shelfId);
}
if (magicBookIds != null) {
query.setParameter("magicBookIds", magicBookIds);
}
}
private Set<Long> resolveMagicShelfBookIds(Long magicShelfId, Long userId) {
Specification<BookEntity> spec = magicShelfBookService.toSpecification(userId, magicShelfId);
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<BookEntity> root = cq.from(BookEntity.class);
cq.select(root.get("id"));
cq.where(spec.toPredicate(root, cq, cb));
return new HashSet<>(entityManager.createQuery(cq)
.getResultList());
}
private List<AppFilterOptions.CountedOption> queryReadStatusCounts(
Long userId, String scopeClause, Set<Long> accessibleLibraryIds,
Long libraryId, Long shelfId, Set<Long> magicBookIds) {
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();
private AppFilterOptions emptyFilterOptions(String cacheKey) {
AppFilterOptions empty = AppFilterOptions.builder()
.authors(Collections.emptyList())
.languages(Collections.emptyList())
.fileTypes(Collections.emptyList())
.readStatuses(Collections.emptyList())
.categories(Collections.emptyList())
.publishers(Collections.emptyList())
.series(Collections.emptyList())
.tags(Collections.emptyList())
.moods(Collections.emptyList())
.narrators(Collections.emptyList())
.ageRatings(Collections.emptyList())
.contentRatings(Collections.emptyList())
.matchScores(Collections.emptyList())
.publishedYears(Collections.emptyList())
.fileSizes(Collections.emptyList())
.personalRatings(Collections.emptyList())
.amazonRatings(Collections.emptyList())
.goodreadsRatings(Collections.emptyList())
.hardcoverRatings(Collections.emptyList())
.pageCounts(Collections.emptyList())
.shelfStatuses(Collections.emptyList())
.comicCharacters(Collections.emptyList())
.comicTeams(Collections.emptyList())
.comicLocations(Collections.emptyList())
.comicCreators(Collections.emptyList())
.shelves(Collections.emptyList())
.libraries(Collections.emptyList())
.build();
filterOptionsCache.put(cacheKey, empty);
return empty;
}
@Transactional
@@ -784,6 +868,125 @@ public class AppBookService {
}
}
if (req.ageRating() != null && !req.ageRating().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.ageRating());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withAgeRatings(cleaned, req.effectiveFilterMode()));
}
}
if (req.contentRating() != null && !req.contentRating().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.contentRating());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withContentRatings(cleaned, req.effectiveFilterMode()));
}
}
if (req.matchScore() != null && !req.matchScore().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.matchScore());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withMatchScores(cleaned, req.effectiveFilterMode()));
}
}
if (req.publishedDate() != null && !req.publishedDate().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.publishedDate());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withPublishedYears(cleaned, req.effectiveFilterMode()));
}
}
if (req.fileSize() != null && !req.fileSize().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.fileSize());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withFileSizes(cleaned, req.effectiveFilterMode()));
}
}
if (req.personalRating() != null && !req.personalRating().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.personalRating());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withPersonalRatings(cleaned, userId, req.effectiveFilterMode()));
}
}
if (req.amazonRating() != null && !req.amazonRating().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.amazonRating());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withAmazonRatings(cleaned, req.effectiveFilterMode()));
}
}
if (req.goodreadsRating() != null && !req.goodreadsRating().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.goodreadsRating());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withGoodreadsRatings(cleaned, req.effectiveFilterMode()));
}
}
if (req.hardcoverRating() != null && !req.hardcoverRating().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.hardcoverRating());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withHardcoverRatings(cleaned, req.effectiveFilterMode()));
}
}
if (req.pageCount() != null && !req.pageCount().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.pageCount());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withPageCounts(cleaned, req.effectiveFilterMode()));
}
}
if (req.shelfStatus() != null && !req.shelfStatus().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.shelfStatus());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withShelfStatus(cleaned, req.effectiveFilterMode()));
}
}
if (req.comicCharacter() != null && !req.comicCharacter().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.comicCharacter());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withComicCharacters(cleaned, req.effectiveFilterMode()));
}
}
if (req.comicTeam() != null && !req.comicTeam().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.comicTeam());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withComicTeams(cleaned, req.effectiveFilterMode()));
}
}
if (req.comicLocation() != null && !req.comicLocation().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.comicLocation());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withComicLocations(cleaned, req.effectiveFilterMode()));
}
}
if (req.comicCreator() != null && !req.comicCreator().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.comicCreator());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.withComicCreators(cleaned, req.effectiveFilterMode()));
}
}
if (req.shelves() != null && !req.shelves().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.shelves());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.inShelves(cleaned, req.effectiveFilterMode()));
}
}
if (req.libraries() != null && !req.libraries().isEmpty()) {
List<String> cleaned = BookListRequest.cleanValues(req.libraries());
if (!cleaned.isEmpty()) {
specs.add(AppBookSpecification.inLibraries(cleaned, req.effectiveFilterMode()));
}
}
return AppBookSpecification.combine(specs.toArray(new Specification[0]));
}
@@ -866,4 +1069,146 @@ public class AppBookService {
.collect(Collectors.toSet());
return getProgressMap(userId, bookIds);
}
private List<AppFilterOptions.CountedOption> queryCountedOptions(
String selectExpr, String joins, String extraWhere,
String scopeClause, Set<Long> accessibleLibraryIds,
Long libraryId, Long shelfId, Set<Long> magicBookIds) {
String jpql = "SELECT " + selectExpr + ", COUNT(DISTINCT b.id) FROM BookEntity b"
+ " " + joins
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
+ " AND b.bookFiles IS NOT EMPTY"
+ (extraWhere.isEmpty() ? "" : " " + extraWhere)
+ " " + scopeClause
+ " GROUP BY " + selectExpr + " ORDER BY COUNT(DISTINCT b.id) DESC";
var q = entityManager.createQuery(jpql, Tuple.class);
setFilterQueryParams(q, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
q.setMaxResults(1000);
return q.getResultList().stream()
.map(this::mapToCountedOption)
.toList();
}
private String buildScopeClause(String libraryClause, String shelfClause, String magicBookClause) {
var sb = new StringBuilder();
if (!libraryClause.isEmpty()) sb.append(" ").append(libraryClause);
if (!shelfClause.isEmpty()) sb.append(" ").append(shelfClause);
if (!magicBookClause.isEmpty()) sb.append(" ").append(magicBookClause);
return sb.toString();
}
private void setFilterQueryParams(jakarta.persistence.Query query, Set<Long> accessibleLibraryIds, Long libraryId, Long shelfId, Set<Long> magicBookIds) {
if (libraryId != null) {
query.setParameter("libraryId", libraryId);
} else if (accessibleLibraryIds != null) {
query.setParameter("libraryIds", accessibleLibraryIds);
}
if (shelfId != null && magicBookIds == null) {
query.setParameter("shelfId", shelfId);
}
if (magicBookIds != null) {
query.setParameter("magicBookIds", magicBookIds);
}
}
private Set<Long> resolveMagicShelfBookIds(Specification<BookEntity> spec) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Long> cq = cb.createQuery(Long.class);
Root<BookEntity> root = cq.from(BookEntity.class);
cq.select(root.get("id"));
cq.where(spec.toPredicate(root, cq, cb));
return new HashSet<>(entityManager.createQuery(cq)
.getResultList());
}
private List<AppFilterOptions.CountedOption> queryReadStatusCounts(
Long userId, String scopeClause, Set<Long> accessibleLibraryIds,
Long libraryId, Long shelfId, Set<Long> magicBookIds) {
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);
List<AppFilterOptions.CountedOption> options = q.getResultList().stream()
.map(t -> new AppFilterOptions.CountedOption(
t.get(0, ReadStatus.class).name(),
t.get(1, Long.class)))
.toList();
String baseQuery = "SELECT COUNT(DISTINCT b.id) FROM BookEntity b"
+ " WHERE (b.deleted IS NULL OR b.deleted = false)"
+ " AND b.bookFiles IS NOT EMPTY"
+ " AND b.id NOT IN ("
+ " SELECT ubp.book.id FROM UserBookProgressEntity ubp WHERE ubp.user.id = :userId"
+ " )"
+ " " + scopeClause;
var baseQ = entityManager.createQuery(baseQuery, Long.class);
baseQ.setParameter("userId", userId);
setFilterQueryParams(baseQ, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
long unsetCount = baseQ.getSingleResult();
if (unsetCount > 0) {
List<AppFilterOptions.CountedOption> mutable = new ArrayList<>(options);
mutable.addFirst(new AppFilterOptions.CountedOption("UNSET", unsetCount));
return List.copyOf(mutable);
}
return options;
}
private List<AppFilterOptions.CountedOption> queryRatingBuckets(
String ratingExpr, String scopeClause, Set<Long> accessibleLibraryIds,
Long libraryId, Long shelfId, Set<Long> magicBookIds) {
return queryGroupedCount(
"CASE " +
" WHEN " + ratingExpr + " >= 4.5 THEN '5' " +
" WHEN " + ratingExpr + " >= 4.0 THEN '4' " +
" WHEN " + ratingExpr + " >= 3.0 THEN '3' " +
" WHEN " + ratingExpr + " >= 2.0 THEN '2' " +
" WHEN " + ratingExpr + " >= 1.0 THEN '1' " +
" ELSE '0' " +
"END",
"JOIN b.metadata m", "AND " + ratingExpr + " IS NOT NULL",
scopeClause, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
}
private List<AppFilterOptions.CountedOption> queryGroupedCount(
String caseExpr, String joins, String extraWhere,
String scopeClause, Set<Long> accessibleLibraryIds,
Long libraryId, Long shelfId, Set<Long> magicBookIds) {
String jpql = "SELECT " + caseExpr + ", COUNT(DISTINCT b.id) FROM BookEntity b " + joins +
" WHERE (b.deleted IS NULL OR b.deleted = false) AND b.bookFiles IS NOT EMPTY "
+ extraWhere + " " + scopeClause +
" GROUP BY 1";
var q = entityManager.createQuery(jpql, Tuple.class);
setFilterQueryParams(q, accessibleLibraryIds, libraryId, shelfId, magicBookIds);
return q.getResultList().stream()
.filter(t -> t.get(0) != null)
.map(this::mapToCountedOption)
.toList();
}
private AppFilterOptions.CountedOption mapToCountedOption(Tuple t) {
Object val = t.get(0);
String name = val instanceof Enum<?> e ? e.name() : val != null ? String.valueOf(val) : null;
return new AppFilterOptions.CountedOption(name, t.get(1, Long.class));
}
private static String creatorRoleLabel(ComicCreatorRole role) {
return switch (role) {
case PENCILLER -> "penciller";
case INKER -> "inker";
case COLORIST -> "colorist";
case LETTERER -> "letterer";
case COVER_ARTIST -> "coverArtist";
case EDITOR -> "editor";
};
}
}
@@ -3,6 +3,7 @@ package org.booklore.app.specification;
import org.booklore.exception.APIException;
import org.booklore.model.entity.*;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.ComicCreatorRole;
import org.booklore.model.enums.ReadStatus;
import jakarta.persistence.criteria.*;
import org.springframework.data.jpa.domain.Specification;
@@ -20,6 +21,46 @@ public class AppBookSpecification {
private AppBookSpecification() {
}
private static List<Integer> parseIntList(List<String> values, String paramName) {
List<String> invalid = new ArrayList<>();
List<Integer> result = values.stream()
.filter(s -> s != null && !s.isBlank())
.map(s -> {
try {
return Integer.parseInt(s.trim());
} catch (NumberFormatException e) {
invalid.add(s.trim());
return null;
}
})
.filter(Objects::nonNull)
.toList();
if (!invalid.isEmpty()) {
throw new APIException("Invalid " + paramName + " values: " + invalid, HttpStatus.BAD_REQUEST);
}
return result;
}
private static List<Long> parseLongList(List<String> values, String paramName) {
List<String> invalid = new ArrayList<>();
List<Long> result = values.stream()
.filter(s -> s != null && !s.isBlank())
.map(s -> {
try {
return Long.parseLong(s.trim());
} catch (NumberFormatException e) {
invalid.add(s.trim());
return null;
}
})
.filter(Objects::nonNull)
.toList();
if (!invalid.isEmpty()) {
throw new APIException("Invalid " + paramName + " values: " + invalid, HttpStatus.BAD_REQUEST);
}
return result;
}
@SuppressWarnings("unchecked")
private static <X, Y> Join<X, Y> getOrCreateJoin(From<?, X> from, String attribute, JoinType joinType) {
for (Join<X, ?> join : from.getJoins()) {
@@ -254,18 +295,48 @@ public class AppBookSpecification {
}
if (parsed.isEmpty()) return cb.conjunction();
boolean hasUnset = parsed.contains(ReadStatus.UNSET);
List<ReadStatus> realStatuses = parsed.stream().filter(s -> s != ReadStatus.UNSET).toList();
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)
realStatuses.isEmpty() ? cb.disjunction() : progressRoot.get("readStatus").in(realStatuses)
);
if ("not".equals(mode)) {
return cb.not(root.get("id").in(sub));
Predicate isReal = root.get("id").in(sub);
// UNSET means either no progress entry OR entry with UNSET status
Subquery<Long> anyEntrySub = query.subquery(Long.class);
Root<UserBookProgressEntity> anyEntryRoot = anyEntrySub.from(UserBookProgressEntity.class);
anyEntrySub.select(anyEntryRoot.get("book").get("id"))
.where(cb.equal(anyEntryRoot.get("user").get("id"), userId));
Predicate noEntry = cb.not(root.get("id").in(anyEntrySub));
Subquery<Long> unsetEntrySub = query.subquery(Long.class);
Root<UserBookProgressEntity> unsetEntryRoot = unsetEntrySub.from(UserBookProgressEntity.class);
unsetEntrySub.select(unsetEntryRoot.get("book").get("id"))
.where(
cb.equal(unsetEntryRoot.get("user").get("id"), userId),
cb.equal(unsetEntryRoot.get("readStatus"), ReadStatus.UNSET)
);
Predicate hasUnsetEntry = root.get("id").in(unsetEntrySub);
Predicate isUnset = cb.or(noEntry, hasUnsetEntry);
Predicate combined;
if (hasUnset && !realStatuses.isEmpty()) {
combined = cb.or(isReal, isUnset);
} else if (hasUnset) {
combined = isUnset;
} else {
combined = isReal;
}
return root.get("id").in(sub);
return "not".equals(mode) ? cb.not(combined) : combined;
};
}
@@ -465,6 +536,334 @@ public class AppBookSpecification {
return cb.not(cb.exists(subquery));
};
}
public static Specification<BookEntity> withAgeRatings(List<String> rangeIds, String mode) {
return (root, query, cb) -> {
List<Integer> ids = parseIntList(rangeIds, "ageRating");
if (ids.isEmpty()) return cb.conjunction();
Join<BookEntity, BookMetadataEntity> metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER);
Expression<Integer> ageRating = metadataJoin.get("ageRating");
// Age rating ranges from frontend config (mirrored here for performance)
// 0: [0, 6), 6: [6, 10), 10: [10, 13), 13: [13, 16), 16: [16, 18), 18: [18, 21), 21: [21, inf)
List<Predicate> predicates = new ArrayList<>();
for (Integer id : ids) {
predicates.add(switch (id) {
case 0 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 0), cb.lessThan(ageRating, 6));
case 6 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 6), cb.lessThan(ageRating, 10));
case 10 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 10), cb.lessThan(ageRating, 13));
case 13 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 13), cb.lessThan(ageRating, 16));
case 16 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 16), cb.lessThan(ageRating, 18));
case 18 -> cb.and(cb.greaterThanOrEqualTo(ageRating, 18), cb.lessThan(ageRating, 21));
case 21 -> cb.greaterThanOrEqualTo(ageRating, 21);
default -> throw new APIException("Invalid ageRating bucket ID: " + id, HttpStatus.BAD_REQUEST);
});
}
Predicate combined = cb.or(predicates.toArray(new Predicate[0]));
return "not".equals(mode) ? cb.not(combined) : combined;
};
}
public static Specification<BookEntity> withContentRatings(List<String> values, String mode) {
return (root, query, cb) -> {
List<String> cleaned = cleanLowerCase(values);
if (cleaned.isEmpty()) return cb.conjunction();
return buildMetadataFieldSpec(root, query, cb, cleaned, mode, "contentRating");
};
}
public static Specification<BookEntity> withMatchScores(List<String> rangeIds, String mode) {
return (root, query, cb) -> {
List<Integer> ids = parseIntList(rangeIds, "matchScore");
if (ids.isEmpty()) return cb.conjunction();
Expression<Float> score = root.get("metadataMatchScore");
List<Predicate> predicates = new ArrayList<>();
for (Integer id : ids) {
predicates.add(switch (id) {
case 0 -> cb.greaterThanOrEqualTo(score, 0.95f);
case 1 -> cb.and(cb.greaterThanOrEqualTo(score, 0.90f), cb.lessThan(score, 0.95f));
case 2 -> cb.and(cb.greaterThanOrEqualTo(score, 0.80f), cb.lessThan(score, 0.90f));
case 3 -> cb.and(cb.greaterThanOrEqualTo(score, 0.70f), cb.lessThan(score, 0.80f));
case 4 -> cb.and(cb.greaterThanOrEqualTo(score, 0.50f), cb.lessThan(score, 0.70f));
case 5 -> cb.and(cb.greaterThanOrEqualTo(score, 0.30f), cb.lessThan(score, 0.50f));
case 6 -> cb.and(cb.greaterThanOrEqualTo(score, 0.00f), cb.lessThan(score, 0.30f));
default -> throw new APIException("Invalid matchScore bucket ID: " + id, HttpStatus.BAD_REQUEST);
});
}
Predicate combined = cb.or(predicates.toArray(new Predicate[0]));
return "not".equals(mode) ? cb.not(combined) : combined;
};
}
public static Specification<BookEntity> withPublishedYears(List<String> years, String mode) {
return (root, query, cb) -> {
if (years.isEmpty()) return cb.conjunction();
List<Integer> parsedYears = parseIntList(years, "publishedDate");
if (parsedYears.isEmpty()) return cb.conjunction();
Join<BookEntity, BookMetadataEntity> metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER);
Expression<Integer> yearExpr = cb.function("YEAR", Integer.class, metadataJoin.get("publishedDate"));
Predicate combined = yearExpr.in(parsedYears);
return "not".equals(mode) ? cb.not(combined) : combined;
};
}
public static Specification<BookEntity> withFileSizes(List<String> rangeIds, String mode) {
return (root, query, cb) -> {
List<Integer> ids = parseIntList(rangeIds, "fileSize");
if (ids.isEmpty()) return cb.conjunction();
Subquery<Long> sub = query.subquery(Long.class);
Root<BookEntity> subRoot = sub.correlate(root);
Join<BookEntity, BookFileEntity> bfJoin = subRoot.join("bookFiles", JoinType.INNER);
Subquery<Long> minIdSub = query.subquery(Long.class);
Root<BookEntity> minIdRoot = minIdSub.correlate(root);
Join<BookEntity, BookFileEntity> minIdJoin = minIdRoot.join("bookFiles", JoinType.INNER);
minIdSub.select(cb.min(minIdJoin.get("id")))
.where(cb.equal(minIdJoin.get("isBookFormat"), true));
Expression<Long> size = bfJoin.get("fileSizeKb");
List<Predicate> predicates = new ArrayList<>();
for (Integer id : ids) {
predicates.add(switch (id) {
case 0 -> cb.and(cb.greaterThanOrEqualTo(size, 0L), cb.lessThan(size, 1024L));
case 1 -> cb.and(cb.greaterThanOrEqualTo(size, 1024L), cb.lessThan(size, 10240L));
case 2 -> cb.and(cb.greaterThanOrEqualTo(size, 10240L), cb.lessThan(size, 51200L));
case 3 -> cb.and(cb.greaterThanOrEqualTo(size, 51200L), cb.lessThan(size, 102400L));
case 4 -> cb.and(cb.greaterThanOrEqualTo(size, 102400L), cb.lessThan(size, 512000L));
case 5 -> cb.and(cb.greaterThanOrEqualTo(size, 512000L), cb.lessThan(size, 1048576L));
case 6 -> cb.and(cb.greaterThanOrEqualTo(size, 1048576L), cb.lessThan(size, 2097152L));
case 7 -> cb.greaterThanOrEqualTo(size, 2097152L);
default -> throw new APIException("Invalid fileSize bucket ID: " + id, HttpStatus.BAD_REQUEST);
});
}
sub.select(cb.literal(1L))
.where(cb.equal(bfJoin.get("id"), minIdSub),
cb.or(predicates.toArray(new Predicate[0])));
return "not".equals(mode) ? cb.not(cb.exists(sub)) : cb.exists(sub);
};
}
public static Specification<BookEntity> withPersonalRatings(List<String> values, Long userId, String mode) {
return (root, query, cb) -> {
if (userId == null || values.isEmpty()) return cb.conjunction();
List<Integer> parsed = parseIntList(values, "personalRating");
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("personalRating").in(parsed)
);
return "not".equals(mode) ? cb.not(root.get("id").in(sub)) : root.get("id").in(sub);
};
}
public static Specification<BookEntity> withAmazonRatings(List<String> rangeIds, String mode) {
return buildRatingRangeSpec(rangeIds, mode, "amazonRating");
}
public static Specification<BookEntity> withGoodreadsRatings(List<String> rangeIds, String mode) {
return buildRatingRangeSpec(rangeIds, mode, "goodreadsRating");
}
public static Specification<BookEntity> withHardcoverRatings(List<String> rangeIds, String mode) {
return buildRatingRangeSpec(rangeIds, mode, "hardcoverRating");
}
private static Specification<BookEntity> buildRatingRangeSpec(
List<String> rangeIds, String mode, String fieldName) {
return (root, query, cb) -> {
List<Integer> ids = parseIntList(rangeIds, fieldName);
if (ids.isEmpty()) return cb.conjunction();
Join<BookEntity, BookMetadataEntity> metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER);
Expression<Double> rating = metadataJoin.get(fieldName);
List<Predicate> predicates = new ArrayList<>();
for (Integer id : ids) {
predicates.add(switch (id) {
case 5 -> cb.greaterThanOrEqualTo(rating, 4.5);
case 4 -> cb.and(cb.greaterThanOrEqualTo(rating, 4.0), cb.lessThan(rating, 4.5));
case 3 -> cb.and(cb.greaterThanOrEqualTo(rating, 3.0), cb.lessThan(rating, 4.0));
case 2 -> cb.and(cb.greaterThanOrEqualTo(rating, 2.0), cb.lessThan(rating, 3.0));
case 1 -> cb.and(cb.greaterThanOrEqualTo(rating, 1.0), cb.lessThan(rating, 2.0));
case 0 -> cb.lessThan(rating, 1.0);
default -> throw new APIException("Invalid " + fieldName + " bucket ID: " + id, HttpStatus.BAD_REQUEST);
});
}
Predicate combined = cb.or(predicates.toArray(new Predicate[0]));
return "not".equals(mode) ? cb.not(combined) : combined;
};
}
public static Specification<BookEntity> withPageCounts(List<String> rangeIds, String mode) {
return (root, query, cb) -> {
List<Integer> ids = parseIntList(rangeIds, "pageCount");
if (ids.isEmpty()) return cb.conjunction();
Join<BookEntity, BookMetadataEntity> metadataJoin = getOrCreateJoin(root, "metadata", JoinType.INNER);
Expression<Integer> count = metadataJoin.get("pageCount");
List<Predicate> predicates = new ArrayList<>();
for (Integer id : ids) {
predicates.add(switch (id) {
case 0 -> cb.lessThan(count, 50);
case 1 -> cb.and(cb.greaterThanOrEqualTo(count, 50), cb.lessThan(count, 100));
case 2 -> cb.and(cb.greaterThanOrEqualTo(count, 100), cb.lessThan(count, 200));
case 3 -> cb.and(cb.greaterThanOrEqualTo(count, 200), cb.lessThan(count, 400));
case 4 -> cb.and(cb.greaterThanOrEqualTo(count, 400), cb.lessThan(count, 600));
case 5 -> cb.and(cb.greaterThanOrEqualTo(count, 600), cb.lessThan(count, 1000));
case 6 -> cb.greaterThanOrEqualTo(count, 1000);
default -> throw new APIException("Invalid pageCount bucket ID: " + id, HttpStatus.BAD_REQUEST);
});
}
Predicate combined = cb.or(predicates.toArray(new Predicate[0]));
return "not".equals(mode) ? cb.not(combined) : combined;
};
}
public static Specification<BookEntity> withShelfStatus(List<String> values, String mode) {
return (root, query, cb) -> {
List<String> cleaned = cleanLowerCase(values);
if (cleaned.isEmpty()) return cb.conjunction();
List<String> invalid = cleaned.stream()
.filter(v -> !v.equals("shelved") && !v.equals("unshelved"))
.toList();
if (!invalid.isEmpty()) {
throw new APIException("Invalid shelfStatus values: " + invalid
+ ". Valid values: [shelved, unshelved]", HttpStatus.BAD_REQUEST);
}
boolean wantShelved = cleaned.contains("shelved");
boolean wantUnshelved = cleaned.contains("unshelved");
if (wantShelved && wantUnshelved) return cb.conjunction();
Predicate hasShelves = cb.isNotEmpty(root.get("shelves"));
Predicate combined = wantShelved ? hasShelves : cb.not(hasShelves);
return "not".equals(mode) ? cb.not(combined) : combined;
};
}
public static Specification<BookEntity> withComicCharacters(List<String> values, String mode) {
return buildComicCollectionSpec(values, mode, "characters");
}
public static Specification<BookEntity> withComicTeams(List<String> values, String mode) {
return buildComicCollectionSpec(values, mode, "teams");
}
public static Specification<BookEntity> withComicLocations(List<String> values, String mode) {
return buildComicCollectionSpec(values, mode, "locations");
}
private static Specification<BookEntity> buildComicCollectionSpec(
List<String> values, String mode, String collectionAttr) {
return (root, query, cb) -> {
List<String> cleaned = cleanLowerCase(values);
if (cleaned.isEmpty()) return cb.conjunction();
Subquery<Long> sub = query.subquery(Long.class);
Root<BookMetadataEntity> metaRoot = sub.from(BookMetadataEntity.class);
Join<?, ?> comicJoin = metaRoot.join("comicMetadata", JoinType.INNER);
Join<?, ?> collJoin = comicJoin.join(collectionAttr, JoinType.INNER);
sub.select(cb.literal(1L))
.where(
cb.equal(metaRoot.get("id"), root.get("id")),
cb.lower(collJoin.get("name")).in(cleaned)
);
return "not".equals(mode) ? cb.not(cb.exists(sub)) : cb.exists(sub);
};
}
public static Specification<BookEntity> inShelves(List<String> shelfIds, String mode) {
return (root, query, cb) -> {
if (shelfIds.isEmpty()) return cb.conjunction();
List<Long> ids = parseLongList(shelfIds, "shelf");
if (ids.isEmpty()) return cb.conjunction();
if ("and".equals(mode)) {
List<Predicate> predicates = new ArrayList<>();
for (Long id : ids) {
Subquery<Long> sub = query.subquery(Long.class);
Root<BookEntity> subRoot = sub.correlate(root);
Join<BookEntity, ShelfEntity> subShelves = subRoot.join("shelves", JoinType.INNER);
sub.select(cb.literal(1L)).where(cb.equal(subShelves.get("id"), id));
predicates.add(cb.exists(sub));
}
return cb.and(predicates.toArray(new Predicate[0]));
}
Subquery<Long> sub = query.subquery(Long.class);
Root<BookEntity> subRoot = sub.correlate(root);
Join<BookEntity, ShelfEntity> subShelves = subRoot.join("shelves", JoinType.INNER);
sub.select(cb.literal(1L)).where(subShelves.get("id").in(ids));
return "not".equals(mode) ? cb.not(cb.exists(sub)) : cb.exists(sub);
};
}
public static Specification<BookEntity> inLibraries(List<String> libraryIds, String mode) {
return (root, query, cb) -> {
if (libraryIds.isEmpty()) return cb.conjunction();
List<Long> ids = parseLongList(libraryIds, "library");
if (ids.isEmpty()) return cb.conjunction();
if ("and".equals(mode)) {
if (ids.size() > 1) return cb.disjunction(); // A book can't be in multiple libraries
return cb.equal(root.get("library").get("id"), ids.getFirst());
}
Predicate combined = root.get("library").get("id").in(ids);
return "not".equals(mode) ? cb.not(combined) : combined;
};
}
public static Specification<BookEntity> withComicCreators(List<String> values, String mode) {
return (root, query, cb) -> {
if (values == null || values.isEmpty()) return cb.conjunction();
// value is formatted as "name:role" from frontend
List<Predicate> predicates = new ArrayList<>();
for (String val : values) {
String[] parts = val.split(":");
String name = parts[0].trim().toLowerCase();
String roleName = parts.length > 1 ? parts[1].trim() : null;
Subquery<Long> sub = query.subquery(Long.class);
Root<ComicCreatorMappingEntity> mappingRoot = sub.from(ComicCreatorMappingEntity.class);
Join<?, ?> creatorJoin = mappingRoot.join("creator", JoinType.INNER);
Join<?, ?> comicJoin = mappingRoot.join("comicMetadata", JoinType.INNER);
List<Predicate> where = new ArrayList<>();
where.add(cb.equal(comicJoin.get("bookId"), root.get("id")));
where.add(cb.equal(cb.lower(creatorJoin.get("name")), name));
if (roleName != null) {
ComicCreatorRole role = parseCreatorRole(roleName);
where.add(cb.equal(mappingRoot.get("role"), role));
}
sub.select(cb.literal(1L)).where(where.toArray(new Predicate[0]));
predicates.add(cb.exists(sub));
}
Predicate combined = "and".equals(mode)
? cb.and(predicates.toArray(new Predicate[0]))
: cb.or(predicates.toArray(new Predicate[0]));
return "not".equals(mode) ? cb.not(combined) : combined;
};
}
private static ComicCreatorRole parseCreatorRole(String roleName) {
return switch (roleName.toLowerCase()) {
case "penciller" -> ComicCreatorRole.PENCILLER;
case "inker" -> ComicCreatorRole.INKER;
case "colorist" -> ComicCreatorRole.COLORIST;
case "letterer" -> ComicCreatorRole.LETTERER;
case "coverartist" -> ComicCreatorRole.COVER_ARTIST;
case "editor" -> ComicCreatorRole.EDITOR;
default -> throw new APIException("Invalid comic creator role: " + roleName, HttpStatus.BAD_REQUEST);
};
}
private static List<String> cleanLowerCase(List<String> values) {
if (values == null) return List.of();
return values.stream()
@@ -97,7 +97,6 @@ class AppBookServiceFilterOptionsTest {
AppFilterOptions result = service.getFilterOptions(5L, null, null);
assertNotNull(result);
verify(entityManager, times(10)).createQuery(anyString(), any(Class.class));
}
@Test
@@ -266,5 +265,13 @@ class AppBookServiceFilterOptionsTest {
when(entityManager.createQuery(anyString(), eq(Tuple.class)))
.thenReturn(tupleQuery);
TypedQuery<Long> longQuery = mock(TypedQuery.class);
when(longQuery.setParameter(anyString(), any())).thenReturn(longQuery);
when(longQuery.getSingleResult()).thenReturn(0L);
when(longQuery.getResultList()).thenReturn(Collections.emptyList());
when(entityManager.createQuery(anyString(), eq(Long.class)))
.thenReturn(longQuery);
}
}
@@ -8,17 +8,17 @@
<div class="entity-info">
<p class="entity-title">
@if (entityType === EntityType.ALL_BOOKS) {
@if (currentFilterLabel && rawFilterParamFromUrl) {
{{ currentFilterLabel }}
} @else if (isFilterActive || hasSearchTerm) {
{{ computedFilterLabel }}
@if (currentFilterLabel() && rawFilterParamFromUrl) {
{{ currentFilterLabel() }}
} @else if (isFilterActive() || hasSearchTerm()) {
{{ computedFilterLabel() }}
} @else {
{{ t('labels.allBooks') }}
}
} @else if (entityType === EntityType.UNSHELVED) {
{{ (isFilterActive || hasSearchTerm) ? t('labels.unshelvedBooksFiltered') : t('labels.unshelvedBooks') }}
{{ (isFilterActive() || hasSearchTerm()) ? t('labels.unshelvedBooksFiltered') : t('labels.unshelvedBooks') }}
} @else {
{{ entityType }}: {{ entity()?.name }}{{ (isFilterActive || hasSearchTerm) ? ' ' + t('labels.filteredSuffix') : '' }}
{{ entityType }}: {{ entity()?.name }}{{ (isFilterActive() || hasSearchTerm()) ? ' ' + t('labels.filteredSuffix') : '' }}
}
</p>
@if (!isBooksLoading() && seriesCollapseFilter.seriesCollapsed() && books(); as books) {
@@ -46,7 +46,7 @@
</div>
<div class="toolbar-actions">
<div class="toolbar-icons">
@if (isFilterActive) {
@if (isFilterActive()) {
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="clearFilter()" (keydown.enter)="clearFilter()">
<i
class="pi pi-filter-slash filter-clear-icon"
@@ -56,7 +56,7 @@
</a>
}
@if (currentViewMode === 'table') {
@if (currentViewMode() === 'table') {
<div>
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="columnPopover.toggle($event)" (keydown.enter)="columnPopover.toggle($event)">
<i
@@ -92,7 +92,7 @@
}
<a class="topbar-items topbar-item" role="button" tabindex="0" (click)="toggleTableGrid()" (keydown.enter)="toggleTableGrid()">
<i
[ngClass]="viewIcon"
[ngClass]="viewIcon()"
[pTooltip]="t('tooltip.toggleView')"
tooltipPosition="top">
</i>
@@ -121,24 +121,24 @@
<label for="collapse-series-checkbox" class="display-settings-label">{{ t('labels.collapseSeries') }}</label>
</div>
</div>
@if (isMobile) {
@if (isMobile()) {
<div class="display-settings-section">
<span class="display-settings-label">{{ t('labels.gridColumns') }}</span>
<div class="column-options">
<button
type="button"
class="column-option-btn"
[class.active]="mobileColumnCount === 2"
[class.active]="mobileColumnCount() === 2"
(click)="setMobileColumns(2)">2</button>
<button
type="button"
class="column-option-btn"
[class.active]="mobileColumnCount === 3"
[class.active]="mobileColumnCount() === 3"
(click)="setMobileColumns(3)">3</button>
<button
type="button"
class="column-option-btn"
[class.active]="mobileColumnCount === 4"
[class.active]="mobileColumnCount() === 4"
(click)="setMobileColumns(4)">4</button>
</div>
</div>
@@ -188,7 +188,7 @@
<app-multi-sort-popover
[sortCriteria]="this.bookSorter.selectedSortCriteria"
[availableSortOptions]="visibleSortOptions"
[showSaveButton]="canSaveSort"
[showSaveButton]="canSaveSort()"
(criteriaChange)="onSortCriteriaChange($event)"
(saveSortConfig)="onSaveSortConfig($event)">
</app-multi-sort-popover>
@@ -263,7 +263,7 @@
</div>
</div>
@if (showTableLoadingPlaceholder) {
@if (showTableLoadingPlaceholder()) {
<div class="table-skeleton" aria-hidden="true">
<div class="table-skeleton-header">
@for (column of tableSkeletonColumns; track column) {
@@ -279,12 +279,12 @@
</div>
}
</div>
} @else if (showGridLoadingPlaceholder) {
} @else if (showGridLoadingPlaceholder()) {
<div class="skeleton-grid"
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth() + ', 1fr))'}">
@for (item of skeletonSlots; track item) {
<div class="skeleton-card"
[ngStyle]="{width: currentCardSize.width + 'px', height: currentCardSize.height + 'px'}">
[ngStyle]="{width: currentCardSize().width + 'px', height: currentCardSize().height + 'px'}">
</div>
}
</div>
@@ -308,7 +308,7 @@
</p>
</div>
}
@if (currentViewMode === 'table' && books.length > 0) {
@if (currentViewMode() === 'table' && books.length > 0) {
<app-book-table
[books]="books"
[preselectedBookIds]="selectedBooks()"
@@ -317,15 +317,15 @@
[visibleColumns]="visibleColumns"
></app-book-table>
}
@if (currentViewMode === 'grid') {
@if (currentViewMode() === 'grid') {
<div class="virtual-scroller" #scrollContainer>
<div class="scroll-height-anchor" [ngStyle]="{'min-height': estimatedTotalHeight() + 'px'}">
<div class="book-grid"
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth + ', 1fr))'}">
[ngStyle]="{'grid-template-columns': 'repeat(auto-fill, minmax(' + gridColumnMinWidth() + ', 1fr))'}">
@for (book of books; track book.id; let i = $index) {
<div
class="virtual-scroller-item"
[ngStyle]="{width: currentCardSize.width + 'px', height: currentCardSize.height + 'px'}">
[ngStyle]="{width: currentCardSize().width + 'px', height: currentCardSize().height + 'px'}">
<app-book-card
[index]="i"
[book]="book"
@@ -335,7 +335,7 @@
[isSeriesCollapsed]="seriesCollapseFilter.seriesCollapsed()"
(checkboxClick)="onCheckboxClicked($event)"
[isSelected]="selectedBooks().has(book.id)"
[useSquareCovers]="isAudiobookOnlyLibrary"
[useSquareCovers]="isAudiobookOnlyLibrary()"
[overlayPreferenceService]="bookCardOverlayPreferenceService">
</app-book-card>
</div>
@@ -481,17 +481,15 @@
(click)="toggleSidebar()"
(keydown.enter)="toggleSidebar()">
</div>
<app-book-filter
[showFilter]="showFilter()"
class="filter-overlay-container"
[ngClass]="{ 'active': showFilter() }"
[entity]="entity()"
[entityType]="entityType()"
[resetFilter$]="resetFilterSubject"
(filterSelected)="onFilterSelected($event)"
(filterModeChanged)="onFilterModeChanged($event)">
</app-book-filter>
}
<app-book-filter
[showFilter]="showFilter()"
class="filter-overlay-container"
[ngClass]="{ 'active': showFilter() }"
[style.display]="showFilter() ? '' : 'none'"
(filterSelected)="onFilterSelected($event)"
(filterModeChanged)="onFilterModeChanged($event)">
</app-book-filter>
</div>
</ng-container>
@@ -324,6 +324,8 @@ function createHarness(options?: {
{
provide: TranslocoService,
useValue: {
langChanges$: new Subject<string>().asObservable(),
getActiveLang: vi.fn(() => 'en'),
translate: vi.fn((key: string) => {
if (options?.translate) {
return options.translate(key);
@@ -378,11 +380,11 @@ describe('BookBrowserComponent', () => {
it('switches view mode through the display settings control', () => {
const {component, queryParamsService} = createHarness();
component.currentViewMode = VIEW_MODES.GRID;
component.currentViewMode.set(VIEW_MODES.GRID);
component.onViewModeChange(VIEW_MODES.TABLE);
expect(component.currentViewMode).toBe(VIEW_MODES.TABLE);
expect(component.currentViewMode()).toBe(VIEW_MODES.TABLE);
expect(queryParamsService.updateViewMode).toHaveBeenCalledWith(VIEW_MODES.TABLE);
});
@@ -432,9 +434,9 @@ describe('BookBrowserComponent', () => {
isBooksLoading: true,
});
expect(component.showBooksLoadingPlaceholder).toBe(false);
expect(component.showGridLoadingPlaceholder).toBe(false);
expect(component.showTableLoadingPlaceholder).toBe(false);
expect(component.showBooksLoadingPlaceholder()).toBe(false);
expect(component.showGridLoadingPlaceholder()).toBe(false);
expect(component.showTableLoadingPlaceholder()).toBe(false);
});
it('triggers next page fetch when scrolled near the bottom of rendered content', async () => {
@@ -460,7 +462,7 @@ describe('BookBrowserComponent', () => {
removeEventListener: vi.fn(),
} as unknown as HTMLElement;
component.currentViewMode = VIEW_MODES.GRID;
component.currentViewMode.set(VIEW_MODES.GRID);
component.scrollContainerRef = {nativeElement: mockElement} as ElementRef<HTMLElement>;
// Trigger initial check
@@ -6,7 +6,7 @@ import {PageTitleService} from '../../../../shared/service/page-title.service';
import {BookService} from '../../service/book.service';
import {BookMetadataManageService} from '../../service/book-metadata-manage.service';
import {debounceTime, distinctUntilChanged, filter, map, take} from 'rxjs/operators';
import {combineLatest, finalize, Subject} from 'rxjs';
import {combineLatest, finalize} from 'rxjs';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
import {Library} from '../../model/library.model';
import {SortDirection, SortOption} from '../../model/sort.model';
@@ -217,6 +217,25 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
case 'language': scopeFilters.language = strValues; break;
case 'readStatus': scopeFilters.status = strValues; break;
case 'bookType': scopeFilters.fileType = strValues; break;
case 'ageRating': scopeFilters.ageRating = strValues; break;
case 'contentRating': scopeFilters.contentRating = strValues; break;
case 'matchScore': scopeFilters.matchScore = strValues; break;
case 'publishedDate': scopeFilters.publishedDate = strValues; break;
case 'fileSize': scopeFilters.fileSize = strValues; break;
case 'personalRating': scopeFilters.personalRating = strValues; break;
case 'amazonRating': scopeFilters.amazonRating = strValues; break;
case 'goodreadsRating': scopeFilters.goodreadsRating = strValues; break;
case 'hardcoverRating': scopeFilters.hardcoverRating = strValues; break;
case 'pageCount': scopeFilters.pageCount = strValues; break;
case 'shelfStatus':
scopeFilters.shelfStatus = strValues;
break;
case 'comicCharacter': scopeFilters.comicCharacter = strValues; break;
case 'comicTeam': scopeFilters.comicTeam = strValues; break;
case 'comicLocation': scopeFilters.comicLocation = strValues; break;
case 'comicCreator': scopeFilters.comicCreator = strValues; break;
case 'shelf': scopeFilters.shelves = strValues; break;
case 'library': scopeFilters.libraries = strValues; break;
}
}
const mode = this.selectedFilterMode();
@@ -288,7 +307,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
private containerResizeObserver: ResizeObserver | undefined;
readonly gridColumns = computed(() => {
return computeGridColumns(this.containerWidth(), parseInt(this.gridColumnMinWidth, 10) || 180, this.GRID_GAP);
return computeGridColumns(this.containerWidth(), parseInt(this.gridColumnMinWidth(), 10) || 180, this.GRID_GAP);
});
/**
@@ -301,7 +320,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
if (total === 0) return 0;
const cols = this.gridColumns();
const rows = Math.ceil(total / cols);
const rowHeight = this.currentCardSize.height + this.GRID_GAP;
const rowHeight = this.currentCardSize().height + this.GRID_GAP;
return rows * rowHeight;
});
@@ -313,28 +332,64 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
if (!books || books.length === 0) return 0;
const cols = this.gridColumns();
const rows = Math.ceil(books.length / cols);
const rowHeight = this.currentCardSize.height + this.GRID_GAP;
const rowHeight = this.currentCardSize().height + this.GRID_GAP;
return rows * rowHeight;
});
protected resetFilterSubject = new Subject<void>();
readonly skeletonSlots = Array.from({length: 24}, (_, index) => index);
skeletonSlots = Array.from({length: 24}, (_, index) => index);
readonly tableSkeletonRows = Array.from({length: 8}, (_, index) => index);
readonly tableSkeletonColumns = Array.from({length: 5}, (_, index) => index);
parsedFilters: Record<string, string[]> = {};
bookTitle = '';
dynamicDialogRef: DynamicDialogRef | undefined | null;
EntityType = EntityType;
currentFilterLabel: string | null = null;
private readonly activeLang = toSignal(this.t.langChanges$, {
initialValue: this.t.getActiveLang()
});
readonly computedFilterLabel = computed(() => {
this.activeLang();
const filters = this.selectedFilter();
if (!filters || Object.keys(filters).length === 0) {
return this.t.translate('book.browser.labels.allBooks');
}
const filterEntries = Object.entries(filters);
if (filterEntries.length === 1) {
const [filterType, values] = filterEntries[0];
const filterName = FilterLabelHelper.getFilterTypeName(filterType);
if (values.length === 1) {
const displayValue = FilterLabelHelper.getFilterDisplayValue(filterType, values[0]);
return `${filterName}: ${displayValue}`;
}
return `${filterName} (${values.length})`;
}
const filterSummary = filterEntries
.map(([type, values]) => `${FilterLabelHelper.getFilterTypeName(type)} (${values.length})`)
.join(', ');
return filterSummary.length > 50
? this.t.translate('book.browser.labels.activeFilters', {count: filterEntries.length})
: filterSummary;
});
readonly currentFilterLabel = computed(() => this.computedFilterLabel());
rawFilterParamFromUrl: string | null = null;
visibleColumns: { field: string; header: string }[] = [];
entityViewPreferences: EntityViewPreferences | undefined;
currentViewMode: string | undefined;
currentViewMode = signal<string | undefined>(undefined);
lastAppliedSortCriteria: SortOption[] = [];
visibleSortOptions: SortOption[] = [];
screenWidth = typeof window !== 'undefined' ? window.innerWidth : 1024;
mobileColumnCount = 3;
screenWidth = signal(typeof window !== 'undefined' ? window.innerWidth : 1024);
mobileColumnCount = signal(3);
private readonly MOBILE_BREAKPOINT = 768;
private readonly CARD_ASPECT_RATIO = 7 / 5;
@@ -355,6 +410,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.t
);
private readonly syncBrowserStateEffect = effect(() => {
this.activeLang();
const entityType = this.entityType();
const entity = this.entity();
@@ -424,7 +480,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
@ViewChild(BookTableComponent)
bookTableComponent!: BookTableComponent;
@ViewChild(BookFilterComponent, {static: false})
@ViewChild(BookFilterComponent, {static: true})
bookFilterComponent!: BookFilterComponent;
private scrollContainer: HTMLElement | undefined;
@@ -469,112 +525,80 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
@HostListener('window:resize')
onResize(): void {
this.screenWidth = window.innerWidth;
this.screenWidth.set(window.innerWidth);
}
get isMobile(): boolean {
return this.screenWidth < this.MOBILE_BREAKPOINT;
}
readonly isMobile = computed(() => this.screenWidth() < this.MOBILE_BREAKPOINT);
get mobileCardSize(): { width: number; height: number } {
const columns = this.mobileColumnCount;
readonly mobileCardSize = computed(() => {
const columns = this.mobileColumnCount();
const totalGaps = (columns - 1) * this.MOBILE_GAP;
const availableWidth = this.screenWidth - totalGaps - this.MOBILE_PADDING;
const availableWidth = this.screenWidth() - totalGaps - this.MOBILE_PADDING;
const cardWidth = Math.floor(availableWidth / columns);
const coverHeight = this.isAudiobookOnlyLibrary ? cardWidth : Math.floor(cardWidth * this.CARD_ASPECT_RATIO);
const coverHeight = this.isAudiobookOnlyLibrary() ? cardWidth : Math.floor(cardWidth * this.CARD_ASPECT_RATIO);
const cardHeight = coverHeight + this.MOBILE_TITLE_BAR_HEIGHT;
return {width: cardWidth, height: cardHeight};
}
});
get currentCardSize() {
if (this.isMobile) {
return this.mobileCardSize;
readonly currentCardSize = computed(() => {
if (this.isMobile()) {
return this.mobileCardSize();
}
const base = this.coverScalePreferenceService.currentCardSize();
if (this.isAudiobookOnlyLibrary) {
if (this.isAudiobookOnlyLibrary()) {
const squareSide = Math.round(base.width * 1.1);
return { width: squareSide, height: squareSide + 31 };
}
return base;
}
});
get gridColumnMinWidth(): string {
if (this.isMobile) {
return `${this.mobileCardSize.width}px`;
readonly gridColumnMinWidth = computed(() => {
if (this.isMobile()) {
return `${this.mobileCardSize().width}px`;
}
if (this.isAudiobookOnlyLibrary) {
return `${this.currentCardSize.width}px`;
if (this.isAudiobookOnlyLibrary()) {
return `${this.currentCardSize().width}px`;
}
return this.coverScalePreferenceService.gridColumnMinWidth();
}
});
getCardHeight(_book: Book): number {
if (this.isMobile) {
return this.mobileCardSize.height;
if (this.isMobile()) {
return this.mobileCardSize().height;
}
if (this.isAudiobookOnlyLibrary) {
return this.currentCardSize.height;
if (this.isAudiobookOnlyLibrary()) {
return this.currentCardSize().height;
}
return this.coverScalePreferenceService.getCardHeight(_book);
}
get showBooksLoadingPlaceholder(): boolean {
return !this.booksError() && (this.isBooksLoading() || !this.hasRenderedBooks());
}
readonly showBooksLoadingPlaceholder = computed(() =>
!this.booksError() && !this.hasRenderedBooks()
);
get showTableLoadingPlaceholder(): boolean {
return this.showBooksLoadingPlaceholder && this.currentViewMode === VIEW_MODES.TABLE;
}
readonly showTableLoadingPlaceholder = computed(() =>
this.showBooksLoadingPlaceholder() && this.currentViewMode() === VIEW_MODES.TABLE
);
get showGridLoadingPlaceholder(): boolean {
return this.showBooksLoadingPlaceholder && this.currentViewMode !== VIEW_MODES.TABLE;
}
readonly showGridLoadingPlaceholder = computed(() =>
this.showBooksLoadingPlaceholder() && this.currentViewMode() === VIEW_MODES.GRID
);
get viewIcon(): string {
return this.currentViewMode === VIEW_MODES.TABLE ? 'pi pi-table' : 'pi pi-objects-column';
}
readonly viewIcon = computed(() =>
this.currentViewMode() === VIEW_MODES.TABLE ? 'pi pi-table' : 'pi pi-objects-column'
);
get isFilterActive(): boolean {
readonly isFilterActive = computed(() => {
const selectedFilter = this.selectedFilter();
return !!selectedFilter && Object.keys(selectedFilter).length > 0;
}
});
get computedFilterLabel(): string {
const filters = this.selectedFilter();
if (!filters || Object.keys(filters).length === 0) {
return this.t.translate('book.browser.labels.allBooks');
}
const filterEntries = Object.entries(filters);
if (filterEntries.length === 1) {
const [filterType, values] = filterEntries[0];
const filterName = FilterLabelHelper.getFilterTypeName(filterType);
if (values.length === 1) {
const displayValue = FilterLabelHelper.getFilterDisplayValue(filterType, values[0]);
return `${filterName}: ${displayValue}`;
}
return `${filterName} (${values.length})`;
}
const filterSummary = filterEntries
.map(([type, values]) => `${FilterLabelHelper.getFilterTypeName(type)} (${values.length})`)
.join(', ');
return filterSummary.length > 50
? this.t.translate('book.browser.labels.activeFilters', {count: filterEntries.length})
: filterSummary;
}
get isAudiobookOnlyLibrary(): boolean {
readonly isAudiobookOnlyLibrary = computed(() => {
const entity = this.entity();
if (!entity || this.entityType() !== EntityType.LIBRARY) return false;
const library = entity as Library;
return !!library.allowedFormats && library.allowedFormats.length === 1 && library.allowedFormats[0] === 'AUDIOBOOK';
}
});
get seriesViewEnabled(): boolean {
return Boolean(this.userService.getCurrentUser()?.userSettings?.enableSeriesView);
@@ -597,9 +621,8 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
ngAfterViewInit(): void {
if (this.bookFilterComponent) {
this.bookFilterComponent.setFilters?.(this.parsedFilters);
this.bookFilterComponent.onFiltersChanged?.();
this.bookFilterComponent.selectedFilterMode = this.selectedFilterMode();
this.bookFilterComponent.setFilters(this.parsedFilters);
this.bookFilterComponent.onFilterModeChange(this.selectedFilterMode());
}
}
@@ -620,7 +643,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
* and fetches the next page if necessary.
*/
private checkAndFetchIfNeeded(): void {
if (!this.scrollContainer || this.currentViewMode === VIEW_MODES.TABLE) return;
if (!this.scrollContainer || this.currentViewMode() !== VIEW_MODES.GRID) return;
const {scrollTop, clientHeight} = this.scrollContainer;
const buffer = 1000; // Large buffer to facilitate scroll restoration
@@ -713,11 +736,10 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
if (parseResult.filterMode !== this.selectedFilterMode()) {
this.selectedFilterMode.set(parseResult.filterMode);
if (this.bookFilterComponent) {
this.bookFilterComponent.selectedFilterMode = parseResult.filterMode;
this.bookFilterComponent.onFilterModeChange(parseResult.filterMode);
}
}
this.currentFilterLabel = this.t.translate('book.browser.labels.allBooks');
const filterParams = queryParamMap.get('filter');
if (filterParams) {
@@ -725,12 +747,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.selectedFilter.set(parseResult.filters);
if (this.bookFilterComponent) {
this.bookFilterComponent.setFilters?.(parseResult.filters);
this.bookFilterComponent.onFiltersChanged?.();
}
if (Object.keys(parseResult.filters).length > 0) {
this.currentFilterLabel = this.computedFilterLabel;
this.bookFilterComponent.setFilters(parseResult.filters);
}
this.rawFilterParamFromUrl = filterParams;
@@ -755,7 +772,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
if (!this.areSortCriteriaEqual(this.bookSorter.selectedSortCriteria, parseResult.sortCriteria)) {
this.bookSorter.setSortCriteria(parseResult.sortCriteria);
}
this.currentViewMode = parseResult.viewMode;
this.currentViewMode.set(parseResult.viewMode);
if (!this.areSortCriteriaEqual(this.lastAppliedSortCriteria, this.bookSorter.selectedSortCriteria)) {
this.lastAppliedSortCriteria = [...this.bookSorter.selectedSortCriteria];
@@ -764,7 +781,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.queryParamsService.syncQueryParams(
this.currentViewMode!,
this.currentViewMode()!,
this.selectedFilterMode(),
this.parsedFilters
);
@@ -786,9 +803,6 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.selectedFilter.set(normalizedFilters);
this.rawFilterParamFromUrl = null;
const hasSidebarFilters = !!normalizedFilters && Object.keys(normalizedFilters).length > 0;
this.currentFilterLabel = hasSidebarFilters ? this.computedFilterLabel : this.t.translate('book.browser.labels.allBooks');
this.queryParamsService.updateFilters(normalizedFilters);
}
@@ -896,18 +910,16 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
this.onMultiSortChange(criteria);
}
get canSaveSort(): boolean {
readonly canSaveSort = computed(() => {
const entityType = this.entityType();
return entityType === EntityType.LIBRARY ||
entityType === EntityType.SHELF ||
entityType === EntityType.MAGIC_SHELF ||
entityType === EntityType.ALL_BOOKS ||
entityType === EntityType.UNSHELVED;
}
});
get hasSearchTerm(): boolean {
return this.searchTerm().trim().length > 0;
}
readonly hasSearchTerm = computed(() => this.searchTerm().trim().length > 0);
onSaveSortConfig(criteria: SortOption[]): void {
const entityType = this.entityType();
@@ -998,7 +1010,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
resetFilters(): void {
this.resetFilterSubject.next();
this.bookFilterComponent?.clearActiveFilter();
}
clearFilter(): void {
@@ -1009,13 +1021,14 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
toggleTableGrid(): void {
this.currentViewMode = this.currentViewMode === VIEW_MODES.GRID ? VIEW_MODES.TABLE : VIEW_MODES.GRID;
this.queryParamsService.updateViewMode(this.currentViewMode as 'grid' | 'table');
const newMode = this.currentViewMode() === VIEW_MODES.GRID ? VIEW_MODES.TABLE : VIEW_MODES.GRID;
this.currentViewMode.set(newMode);
this.queryParamsService.updateViewMode(newMode as 'grid' | 'table');
}
onViewModeChange(mode: string): void {
if (mode && mode !== this.currentViewMode) {
this.currentViewMode = mode;
if (mode && mode !== this.currentViewMode()) {
this.currentViewMode.set(mode);
this.queryParamsService.updateViewMode(mode as 'grid' | 'table');
}
}
@@ -1228,14 +1241,14 @@ export class BookBrowserComponent implements OnInit, AfterViewInit, OnDestroy {
}
setMobileColumns(columns: number): void {
this.mobileColumnCount = columns;
this.mobileColumnCount.set(columns);
this.localStorageService.set(this.MOBILE_COLUMNS_STORAGE_KEY, columns);
}
private loadMobileColumnsPreference(): void {
const saved = this.localStorageService.get<number>(this.MOBILE_COLUMNS_STORAGE_KEY);
if (saved !== null && [2, 3, 4].includes(saved)) {
this.mobileColumnCount = saved;
this.mobileColumnCount.set(saved);
}
}
}
@@ -5,7 +5,8 @@
<span class="filter-title">{{ t('title') }}</span>
<p-selectButton
[options]="filterModeOptions"
[(ngModel)]="selectedFilterMode"
[ngModel]="selectedFilterMode()"
(ngModelChange)="onFilterModeChange($event)"
optionLabel="label"
optionValue="value"
class="filter-mode-select"
@@ -14,24 +15,24 @@
</div>
<div class="filter-content">
<p-accordion [value]="expandedPanels" [multiple]="true" (valueChange)="onExpandedPanelsChange($event)">
@for (filterType of visibleFilterTypes; track trackByFilterType(i, filterType); let i = $index) {
<p-accordion [value]="expandedPanels()" [multiple]="true" (valueChange)="onExpandedPanelsChange($event)">
@for (filterType of visibleFilterTypes(); track filterType; let i = $index) {
<p-accordion-panel [value]="i">
<p-accordion-header>
<span class="filter-type-label">
<span class="filter-label-text">
{{ getFilterLabel(filterType) }}
</span>
@if (activeFilters[filterType]?.length) {
@if (activeFilters()[filterType]?.length; as count) {
<span class="active-filter-count">
({{ activeFilters[filterType].length }})
({{ count }})
</span>
}
</span>
</p-accordion-header>
<p-accordion-content>
@if (expandedPanels.includes(i)) {
@if (expandedPanels().includes(i)) {
@if (filterSignals[filterType](); as filters) {
@if (filters.length > 0) {
<cdk-virtual-scroll-viewport
@@ -44,8 +45,8 @@
role="button"
tabindex="0"
[ngClass]="{
'active': activeFilters[filterType]?.includes(getFilterValueId(filter)),
'active-not': activeFilters[filterType]?.includes(getFilterValueId(filter)) && selectedFilterMode === 'not'
'active': isActive(filterType, getFilterValueId(filter)),
'active-not': isActive(filterType, getFilterValueId(filter)) && selectedFilterMode() === 'not'
}"
(click)="handleFilterClick(filterType, getFilterValueId(filter))"
(keydown.enter)="handleFilterClick(filterType, getFilterValueId(filter))">
@@ -54,11 +55,6 @@
</div>
</cdk-virtual-scroll-viewport>
}
@if (truncatedFilters[filterType]) {
<div class="truncation-notice">
{{ t('showingFirst100') }}
</div>
}
}
}
</p-accordion-content>
@@ -1,8 +1,4 @@
import {ChangeDetectionStrategy, Component, effect, EventEmitter, inject, Input, OnDestroy, OnInit, Output, Signal, signal} from '@angular/core';
import {Subject, takeUntil} from 'rxjs';
import {Library} from '../../../model/library.model';
import {Shelf} from '../../../model/shelf.model';
import {EntityType} from '../book-browser.component';
import {ChangeDetectionStrategy, Component, computed, effect, inject, input, output, signal, Signal} from '@angular/core';
import {Accordion, AccordionContent, AccordionHeader, AccordionPanel} from 'primeng/accordion';
import {CdkFixedSizeVirtualScroll, CdkVirtualForOf, CdkVirtualScrollViewport} from '@angular/cdk/scrolling';
import {NgClass} from '@angular/common';
@@ -10,7 +6,6 @@ import {Badge} from 'primeng/badge';
import {FormsModule} from '@angular/forms';
import {SelectButton} from 'primeng/selectbutton';
import {BookFilterMode, DEFAULT_VISIBLE_FILTERS, UserService, VisibleFilterType} from '../../../../settings/user-management/user.service';
import {MagicShelf} from '../../../../magic-shelf/service/magic-shelf.service';
import {Filter, FILTER_LABEL_KEYS, FilterType} from './book-filter.config';
import {BookFilterService} from './book-filter.service';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
@@ -33,57 +28,32 @@ interface FilterModeOption {
TranslocoDirective
]
})
export class BookFilterComponent implements OnInit, OnDestroy {
@Input() set entity(value: Library | Shelf | MagicShelf | null | undefined) {
this.entitySignal.set(value ?? null);
}
@Input() set entityType(value: EntityType | undefined) {
this.entityTypeSignal.set(value ?? EntityType.ALL_BOOKS);
}
@Input() resetFilter$!: Subject<void>;
@Input() showFilter = false;
export class BookFilterComponent {
readonly showFilter = input(false);
@Output() filterSelected = new EventEmitter<Record<string, unknown> | null>();
@Output() filterModeChanged = new EventEmitter<BookFilterMode>();
readonly filterSelected = output<Record<string, unknown> | null>();
readonly filterModeChanged = output<BookFilterMode>();
private readonly filterService = inject(BookFilterService);
private readonly userService = inject(UserService);
private readonly t = inject(TranslocoService);
private readonly destroy$ = new Subject<void>();
private readonly entitySignal = signal<Library | Shelf | MagicShelf | null>(null);
private readonly entityTypeSignal = signal<EntityType>(EntityType.ALL_BOOKS);
private readonly activeFiltersSignal = signal<Record<string, unknown[]> | null>(null);
private readonly filterModeSignal = signal<BookFilterMode>('and');
/** Stable reference to the singleton filter signals — never recreated. */
readonly filterSignals: Record<FilterType, Signal<Filter[]>> = this.filterService.filterSignals;
readonly filterTypes: FilterType[] = Object.keys(this.filterSignals) as FilterType[];
activeFilters: Record<string, unknown[]> = {};
filterSignals: Record<FilterType, Signal<Filter[]>> = this.filterService.createFilterSignals(
this.entitySignal,
this.entityTypeSignal,
this.activeFiltersSignal,
this.filterModeSignal
);
filterTypes: FilterType[] = Object.keys(this.filterSignals) as FilterType[];
visibleFilterTypes: FilterType[] = [];
expandedPanels: number[] = [];
truncatedFilters: Record<string, boolean> = {};
readonly activeFilters = signal<Record<string, unknown[]>>({});
readonly expandedPanels = signal<number[]>([]);
private _selectedFilterMode: BookFilterMode = 'and';
private _visibleFilters: VisibleFilterType[] = [...DEFAULT_VISIBLE_FILTERS];
private readonly visibleFilters = signal<VisibleFilterType[]>([...DEFAULT_VISIBLE_FILTERS]);
readonly visibleFilterTypes = computed(() => {
const vf = this.visibleFilters();
return vf.filter(f => this.filterTypes.includes(f as FilterType)) as FilterType[];
});
readonly filterLabelKeys = FILTER_LABEL_KEYS;
private readonly userSettingsEffect = effect(() => {
const user = this.userService.currentUser();
if (!user) return;
this._visibleFilters = user.userSettings.visibleFilters ?? [...DEFAULT_VISIBLE_FILTERS];
this.updateVisibleFilterTypes();
});
getFilterLabel(type: FilterType): string {
const key = this.filterLabelKeys[type];
return key ? this.t.translate(key) : type;
}
readonly filterModeOptions: FilterModeOption[] = [
{label: 'AND', value: 'and'},
{label: 'OR', value: 'or'},
@@ -91,31 +61,29 @@ export class BookFilterComponent implements OnInit, OnDestroy {
{label: '1', value: 'single'}
];
get selectedFilterMode(): BookFilterMode {
return this._selectedFilterMode;
}
private readonly _selectedFilterMode = signal<BookFilterMode>('and');
readonly selectedFilterMode = this._selectedFilterMode.asReadonly();
set selectedFilterMode(mode: BookFilterMode) {
if (mode === this._selectedFilterMode) return;
this._selectedFilterMode = mode;
this.filterModeSignal.set(mode);
private readonly syncUserSettings = effect(() => {
const user = this.userService.currentUser();
if (!user) return;
this.visibleFilters.set(user.userSettings.visibleFilters ?? [...DEFAULT_VISIBLE_FILTERS]);
});
onFilterModeChange(mode: BookFilterMode): void {
if (mode === this._selectedFilterMode()) return;
this._selectedFilterMode.set(mode);
this.filterModeChanged.emit(mode);
this.emitFilters();
}
ngOnInit(): void {
this.updateVisibleFilterTypes();
this.updateExpandedPanels();
this.subscribeToReset();
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
getFilterLabel(type: FilterType): string {
const key = this.filterLabelKeys[type];
return key ? this.t.translate(key) : type;
}
handleFilterClick(filterType: string, value: unknown): void {
if (this._selectedFilterMode === 'single') {
if (this._selectedFilterMode() === 'single') {
this.handleSingleMode(filterType, value);
} else {
this.handleMultiMode(filterType, value);
@@ -124,35 +92,34 @@ export class BookFilterComponent implements OnInit, OnDestroy {
}
setFilters(filters: Record<string, unknown>): void {
this.activeFilters = {};
const result: Record<string, unknown[]> = {};
for (const [key, value] of Object.entries(filters)) {
const values = Array.isArray(value) ? value : [value];
this.activeFilters[key] = values.map(v => this.filterService.processFilterValue(key, v));
result[key] = values.map(v => this.filterService.processFilterValue(key, v));
}
this.activeFilters.set(result);
this.emitFilters();
}
clearActiveFilter(): void {
this.activeFilters = {};
this.expandedPanels = [];
this.activeFiltersSignal.set(null);
this.activeFilters.set({});
this.expandedPanels.set([]);
this.filterSelected.emit(null);
}
onExpandedPanelsChange(value: string | number | string[] | number[] | null | undefined): void {
if (Array.isArray(value)) {
this.expandedPanels = value.map(Number);
const panels = value.map(Number);
if (JSON.stringify(panels) !== JSON.stringify(this.expandedPanels())) {
this.expandedPanels.set(panels);
}
}
}
onFiltersChanged(): void {
this.updateExpandedPanels();
getVirtualScrollHeight(itemCount: number): number {
return Math.min(itemCount * 28, 440);
}
getVirtualScrollHeight = (itemCount: number): number => Math.min(itemCount * 28, 440);
trackByFilterType = (_: number, type: FilterType): string => type;
trackByFilter = (_: number, f: Filter): unknown => this.getFilterValueId(f);
getFilterValueId(f: Filter): unknown {
@@ -170,45 +137,41 @@ export class BookFilterComponent implements OnInit, OnDestroy {
return String(value ?? '');
}
private updateVisibleFilterTypes(): void {
this.visibleFilterTypes = this._visibleFilters.filter(
vf => this.filterTypes.includes(vf as FilterType)
) as FilterType[];
}
private subscribeToReset(): void {
this.resetFilter$?.pipe(takeUntil(this.destroy$)).subscribe(() => this.clearActiveFilter());
isActive(filterType: string, filterId: unknown): boolean {
const active = this.activeFilters()[filterType];
if (!active) return false;
return active.some(v => v === filterId || String(v) === String(filterId));
}
private handleSingleMode(filterType: string, value: unknown): void {
const id = this.extractId(value);
const current = this.activeFilters[filterType];
const current = this.activeFilters()[filterType];
const isSame = current?.length === 1 && this.valuesMatch(current[0], id);
this.activeFilters = isSame ? {} : {[filterType]: [id]};
this.activeFilters.set(isSame ? {} : {[filterType]: [id]});
}
private handleMultiMode(filterType: string, value: unknown): void {
const id = this.extractId(value);
const current = {...this.activeFilters()};
const arr = [...(current[filterType] ?? [])];
if (!this.activeFilters[filterType]) {
this.activeFilters[filterType] = [];
}
const arr = this.activeFilters[filterType];
const index = arr.findIndex(v => this.valuesMatch(v, id));
if (index > -1) {
arr.splice(index, 1);
if (arr.length === 0) delete this.activeFilters[filterType];
if (arr.length === 0) {
delete current[filterType];
} else {
current[filterType] = arr;
}
} else {
arr.push(id);
current[filterType] = [...arr, id];
}
this.activeFilters.set(current);
}
private extractId(value: unknown): unknown {
return typeof value === 'object' && value !== null && 'id' in value
? (value as { id: unknown }).id
? (value as {id: unknown}).id
: value;
}
@@ -217,17 +180,16 @@ export class BookFilterComponent implements OnInit, OnDestroy {
}
private emitFilters(): void {
const hasFilters = Object.keys(this.activeFilters).length > 0;
const filtersToEmit = hasFilters ? {...this.activeFilters} : null;
this.activeFiltersSignal.set(filtersToEmit);
this.filterSelected.emit(filtersToEmit);
}
const filters = this.activeFilters();
const hasFilters = Object.keys(filters).length > 0;
this.filterSelected.emit(hasFilters ? {...filters} : null);
private updateExpandedPanels(): void {
// Update expanded panels to show panels with active filters
const panels = new Set<number>();
this.visibleFilterTypes.forEach((type, i) => {
if (this.activeFilters[type]?.length) panels.add(i);
const types = this.visibleFilterTypes();
types.forEach((type, i) => {
if (filters[type]?.length) panels.add(i);
});
this.expandedPanels = [...panels];
this.expandedPanels.set([...panels]);
}
}
@@ -58,6 +58,10 @@ describe('book-filter.config', () => {
expect(FILTER_EXTRACTORS.contentRating(makeBook({
metadata: {bookId: 1, contentRating: 'EVERYONE'}
}))).toEqual([{id: 'EVERYONE', name: CONTENT_RATING_LABELS['EVERYONE']}]);
expect(FILTER_EXTRACTORS.ageRating(makeBook({
metadata: {bookId: 1, ageRating: 12}
}))).toEqual([{id: 10, name: '10+', sortIndex: 2}]);
});
it('builds comic creator filters with role-aware labels', () => {
@@ -79,10 +79,10 @@ export const FILE_SIZE_RANGES: readonly RangeConfig[] = [
{id: 1, label: '1–10 MB', min: 1024, max: 10240, sortIndex: 1},
{id: 2, label: '10–50 MB', min: 10240, max: 51200, sortIndex: 2},
{id: 3, label: '50–100 MB', min: 51200, max: 102400, sortIndex: 3},
{id: 4, label: '250–500 MB', min: 256000, max: 512000, sortIndex: 4},
{id: 4, label: '100–500 MB', min: 102400, max: 512000, sortIndex: 4},
{id: 5, label: '0.5–1 GB', min: 512000, max: 1048576, sortIndex: 5},
{id: 6, label: '1–2 GB', min: 1048576, max: 2097152, sortIndex: 6},
{id: 7, label: '5+ GB', min: 5242880, max: Infinity, sortIndex: 7}
{id: 7, label: '2+ GB', min: 2097152, max: Infinity, sortIndex: 7}
];
export const PAGE_COUNT_RANGES: readonly RangeConfig[] = [
@@ -106,13 +106,13 @@ export const MATCH_SCORE_RANGES: readonly RangeConfig[] = [
];
export const AGE_RATING_OPTIONS: readonly RangeConfig[] = [
{id: 0, min: 0, max: 1, label: 'All Ages', sortIndex: 0},
{id: 6, min: 6, max: 7, label: '6+', sortIndex: 1},
{id: 10, min: 10, max: 11, label: '10+', sortIndex: 2},
{id: 13, min: 13, max: 14, label: '13+', sortIndex: 3},
{id: 16, min: 16, max: 17, label: '16+', sortIndex: 4},
{id: 18, min: 18, max: 19, label: '18+', sortIndex: 5},
{id: 21, min: 21, max: 22, label: '21+', sortIndex: 6}
{id: 0, min: 0, max: 6, label: 'All Ages', sortIndex: 0},
{id: 6, min: 6, max: 10, label: '6+', sortIndex: 1},
{id: 10, min: 10, max: 13, label: '10+', sortIndex: 2},
{id: 13, min: 13, max: 16, label: '13+', sortIndex: 3},
{id: 16, min: 16, max: 18, label: '16+', sortIndex: 4},
{id: 18, min: 18, max: 21, label: '18+', sortIndex: 5},
{id: 21, min: 21, max: Infinity, label: '21+', sortIndex: 6}
];
export const CONTENT_RATING_LABELS: Readonly<Record<string, string>> = {
@@ -129,6 +129,7 @@ export const ratingOptions10 = RATING_OPTIONS_10;
export const fileSizeRanges = FILE_SIZE_RANGES;
export const pageCountRanges = PAGE_COUNT_RANGES;
export const matchScoreRanges = MATCH_SCORE_RANGES;
export const ageRatingRanges = AGE_RATING_OPTIONS;
export const NUMERIC_ID_FILTER_TYPES = new Set<FilterType>([
'personalRating', 'matchScore', 'fileSize', 'amazonRating',
@@ -193,12 +194,6 @@ const extractStringsAsFilters = (values: string[] | undefined): FilterValue[] =>
const extractSingleString = (value: string | undefined | null): FilterValue[] =>
value ? [{id: value, name: value}] : [];
const findExactAgeRating = (ageRating: number | null | undefined): FilterValue[] => {
if (ageRating == null) return [];
const match = AGE_RATING_OPTIONS.find(r => r.id === ageRating);
return match ? [{id: match.id, name: match.label, sortIndex: match.sortIndex}] : [];
};
export const FILTER_EXTRACTORS: Readonly<Record<Exclude<FilterType, 'library'>, (book: Book) => FilterValue[]>> = {
author: (book) => extractStringsAsFilters(book.metadata?.authors),
category: (book) => extractStringsAsFilters(book.metadata?.categories),
@@ -231,7 +226,7 @@ export const FILTER_EXTRACTORS: Readonly<Record<Exclude<FilterType, 'library'>,
language: (book) => extractSingleString(book.metadata?.language),
pageCount: (book) => findInRange(book.metadata?.pageCount, PAGE_COUNT_RANGES),
mood: (book) => extractStringsAsFilters(book.metadata?.moods),
ageRating: (book) => findExactAgeRating(book.metadata?.ageRating),
ageRating: (book) => findInRange(book.metadata?.ageRating, AGE_RATING_OPTIONS),
contentRating: (book) => {
const rating = book.metadata?.contentRating;
if (!rating) return [];
@@ -3,96 +3,38 @@ import {Book} from '../../../model/book.model';
import {Library} from '../../../model/library.model';
import {Shelf} from '../../../model/shelf.model';
import {MagicShelf} from '../../../../magic-shelf/service/magic-shelf.service';
import {BookService} from '../../../service/book.service';
import {AppBooksApiService} from '../../../service/app-books-api.service';
import {LibraryService} from '../../../service/library.service';
import {BookRuleEvaluatorService} from '../../../../magic-shelf/service/book-rule-evaluator.service';
import {GroupRule} from '../../../../magic-shelf/component/magic-shelf-component';
import {EntityType} from '../book-browser.component';
import {Filter, FILTER_CONFIGS, FILTER_EXTRACTORS, FilterType, FilterValue, NUMERIC_ID_FILTER_TYPES, SortMode} from './book-filter.config';
import {filterBooksByFilters} from '../filters/sidebar-filter';
import {BookFilterMode} from '../../../../settings/user-management/user.service';
import {
ageRatingRanges,
CONTENT_RATING_LABELS,
Filter,
fileSizeRanges,
FilterType,
matchScoreRanges,
NUMERIC_ID_FILTER_TYPES,
pageCountRanges,
ratingRanges,
READ_STATUS_LABELS,
} from './book-filter.config';
import {AppFilterOptions, CountedOption, LanguageOption} from '../../../model/app-book.model';
const MAX_FILTER_ITEMS = 100;
import {ReadStatus} from '../../../model/book.model';
@Injectable({providedIn: 'root'})
export class BookFilterService {
private readonly bookService = inject(BookService);
private readonly appBooksApi = inject(AppBooksApiService);
private readonly libraryService = inject(LibraryService);
private readonly bookRuleEvaluatorService = inject(BookRuleEvaluatorService);
/** Server-supported filter types -- these use /api/v1/app/filter-options data. */
private static readonly SERVER_FILTER_TYPES = new Set<FilterType>([
'author', 'category', 'series', 'publisher', 'tag', 'mood',
'narrator', 'language', 'readStatus', 'bookType',
]);
/** Cached filter signals — created once, shared across component instances. */
private _filterSignals: Record<FilterType, Signal<Filter[]>> | null = null;
createFilterSignals(
entity: Signal<Library | Shelf | MagicShelf | null>,
entityType: Signal<EntityType>,
activeFilters: Signal<Record<string, unknown[]> | null>,
filterMode: Signal<BookFilterMode>
): Record<FilterType, Signal<Filter[]>> {
const signals = {} as Record<FilterType, Signal<Filter[]>>;
// Server-backed filter types use the filter-options API
for (const type of BookFilterService.SERVER_FILTER_TYPES) {
signals[type] = computed(() => {
const options = this.appBooksApi.filterOptions();
if (!options) return [];
return this.serverOptionsToFilters(type, options);
});
get filterSignals(): Record<FilterType, Signal<Filter[]>> {
if (!this._filterSignals) {
this._filterSignals = this.buildFilterSignals();
}
// Client-side filter types that don't have server support use loaded books
const filteredBooks = computed(() =>
this.appBooksApi.books()
);
for (const [type, config] of Object.entries(FILTER_CONFIGS)) {
const filterType = type as Exclude<FilterType, 'library'>;
if (BookFilterService.SERVER_FILTER_TYPES.has(filterType)) continue;
signals[filterType] = computed(() => {
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), filterType);
return this.buildAndSortFilters(books, FILTER_EXTRACTORS[filterType], config.sortMode);
});
}
if (!signals.library) {
signals.library = computed(() => {
const books = filterBooksByFilters(filteredBooks(), activeFilters(), filterMode(), 'library');
const libraries = this.libraryService.libraries();
const libraryMap = new Map(
libraries
.filter(lib => lib.id !== undefined)
.map(lib => [lib.id!, lib.name])
);
const filterMap = new Map<number, Filter>();
for (const book of books) {
if (book.libraryId == null) continue;
if (!filterMap.has(book.libraryId)) {
filterMap.set(book.libraryId, {
value: {
id: book.libraryId,
name: libraryMap.get(book.libraryId) || `Library ${book.libraryId}`
},
bookCount: 0
});
}
filterMap.get(book.libraryId)!.bookCount++;
}
return this.sortFiltersByCount(Array.from(filterMap.values()));
});
}
return signals;
return this._filterSignals;
}
filterBooksByEntity(
@@ -130,6 +72,78 @@ export class BookFilterService {
return NUMERIC_ID_FILTER_TYPES.has(filterType as FilterType);
}
private buildFilterSignals(): Record<FilterType, Signal<Filter[]>> {
const signals = {} as Record<FilterType, Signal<Filter[]>>;
signals['author'] = computed(() => this.countedToFilters(this.appBooksApi.authorOptions()));
signals['category'] = computed(() => this.countedToFilters(this.appBooksApi.categoryOptions()));
signals['series'] = computed(() => this.countedToFilters(this.appBooksApi.seriesOptions()));
signals['publisher'] = computed(() => this.countedToFilters(this.appBooksApi.publisherOptions()));
signals['tag'] = computed(() => this.countedToFilters(this.appBooksApi.tagOptions()));
signals['mood'] = computed(() => this.countedToFilters(this.appBooksApi.moodOptions()));
signals['narrator'] = computed(() => this.countedToFilters(this.appBooksApi.narratorOptions()));
signals['language'] = computed(() => this.appBooksApi.languageOptions().map((lang: LanguageOption) => ({
value: {id: lang.code, name: lang.label || lang.code},
bookCount: lang.count,
})));
signals['readStatus'] = computed(() => this.appBooksApi.readStatusOptions().map(item => ({
value: {id: item.name, name: READ_STATUS_LABELS[item.name as ReadStatus] || item.name},
bookCount: item.count
})));
signals['bookType'] = computed(() => this.countedToFilters(this.appBooksApi.fileTypeOptions()));
signals['ageRating'] = computed(() => this.rangedFilters(this.appBooksApi.ageRatingOptions(), ageRatingRanges));
signals['contentRating'] = computed(() => this.appBooksApi.contentRatingOptions().map(item => ({
value: {id: item.name, name: CONTENT_RATING_LABELS[item.name] || item.name},
bookCount: item.count
})));
signals['matchScore'] = computed(() => this.rangedFilters(this.appBooksApi.matchScoreOptions(), matchScoreRanges));
signals['publishedDate'] = computed(() => this.appBooksApi.publishedYearOptions().map(item => ({
value: {id: item.name, name: item.name},
bookCount: item.count
})));
signals['fileSize'] = computed(() => this.rangedFilters(this.appBooksApi.fileSizeOptions(), fileSizeRanges));
signals['personalRating'] = computed(() => this.appBooksApi.personalRatingOptions().map(item => ({
value: {id: Number(item.name), name: item.name},
bookCount: item.count
})));
signals['amazonRating'] = computed(() => this.rangedFilters(this.appBooksApi.amazonRatingOptions(), ratingRanges));
signals['goodreadsRating'] = computed(() => this.rangedFilters(this.appBooksApi.goodreadsRatingOptions(), ratingRanges));
signals['hardcoverRating'] = computed(() => this.rangedFilters(this.appBooksApi.hardcoverRatingOptions(), ratingRanges));
signals['pageCount'] = computed(() => this.rangedFilters(this.appBooksApi.pageCountOptions(), pageCountRanges));
signals['shelfStatus'] = computed(() => this.appBooksApi.shelfStatusOptions().map(item => ({
value: {id: item.name, name: item.name.charAt(0).toUpperCase() + item.name.slice(1)},
bookCount: item.count
})));
signals['comicCharacter'] = computed(() => this.countedToFilters(this.appBooksApi.comicCharacterOptions()));
signals['comicTeam'] = computed(() => this.countedToFilters(this.appBooksApi.comicTeamOptions()));
signals['comicLocation'] = computed(() => this.countedToFilters(this.appBooksApi.comicLocationOptions()));
signals['comicCreator'] = computed(() => this.appBooksApi.comicCreatorOptions().map(item => {
const parts = item.name.split(':');
const role = parts.pop()!;
const name = parts.join(':');
return {
value: {id: item.name, name: `${name} (${role})`},
bookCount: item.count
};
}));
signals['shelf'] = computed(() => this.appBooksApi.shelfOptions().map(item => {
const [id, ...nameParts] = item.name.split(':');
return {
value: {id: Number(id), name: nameParts.join(':')},
bookCount: item.count
};
}));
signals['library'] = computed(() => this.appBooksApi.libraryOptions().map(item => {
const [id, ...nameParts] = item.name.split(':');
return {
value: {id: Number(id), name: nameParts.join(':')},
bookCount: item.count
};
}));
return signals;
}
private serverOptionsToFilters(type: FilterType, options: AppFilterOptions): Filter[] {
switch (type) {
case 'author':
@@ -152,9 +166,78 @@ export class BookFilterService {
bookCount: lang.count,
}));
case 'readStatus':
return this.countedToFilters(options.readStatuses);
return (options.readStatuses ?? []).map(item => ({
value: {id: item.name, name: READ_STATUS_LABELS[item.name as ReadStatus] || item.name},
bookCount: item.count
}));
case 'bookType':
return this.countedToFilters(options.fileTypes);
case 'ageRating':
return this.rangedFilters(options.ageRatings, ageRatingRanges);
case 'contentRating':
return (options.contentRatings ?? []).map(item => ({
value: {id: item.name, name: CONTENT_RATING_LABELS[item.name] || item.name},
bookCount: item.count
}));
case 'matchScore':
return this.rangedFilters(options.matchScores, matchScoreRanges);
case 'publishedDate':
return (options.publishedYears ?? []).map(item => ({
value: {id: item.name, name: item.name},
bookCount: item.count
}));
case 'fileSize':
return this.rangedFilters(options.fileSizes, fileSizeRanges);
case 'personalRating':
return (options.personalRatings ?? []).map(item => ({
value: {id: Number(item.name), name: item.name},
bookCount: item.count
}));
case 'amazonRating':
return this.rangedFilters(options.amazonRatings, ratingRanges);
case 'goodreadsRating':
return this.rangedFilters(options.goodreadsRatings, ratingRanges);
case 'hardcoverRating':
return this.rangedFilters(options.hardcoverRatings, ratingRanges);
case 'pageCount':
return this.rangedFilters(options.pageCounts, pageCountRanges);
case 'shelfStatus':
return (options.shelfStatuses ?? []).map(item => ({
value: {id: item.name, name: item.name.charAt(0).toUpperCase() + item.name.slice(1)},
bookCount: item.count
}));
case 'comicCharacter':
return this.countedToFilters(options.comicCharacters);
case 'comicTeam':
return this.countedToFilters(options.comicTeams);
case 'comicLocation':
return this.countedToFilters(options.comicLocations);
case 'comicCreator':
return (options.comicCreators ?? []).map(item => {
const parts = item.name.split(':');
const role = parts.pop()!;
const name = parts.join(':');
return {
value: {id: item.name, name: `${name} (${role})`},
bookCount: item.count
};
});
case 'shelf':
return (options.shelves ?? []).map(item => {
const [id, ...nameParts] = item.name.split(':');
return {
value: {id: Number(id), name: nameParts.join(':')},
bookCount: item.count
};
});
case 'library':
return (options.libraries ?? []).map(item => {
const [id, ...nameParts] = item.name.split(':');
return {
value: {id: Number(id), name: nameParts.join(':')},
bookCount: item.count
};
});
default:
return [];
}
@@ -167,53 +250,20 @@ export class BookFilterService {
}));
}
private buildAndSortFilters(
books: Book[],
extractor: (book: Book) => FilterValue[],
sortMode: SortMode
private rangedFilters(
items: CountedOption[] | undefined,
ranges: readonly {id: number; label: string; sortIndex: number}[]
): Filter[] {
const filterMap = new Map<unknown, Filter>();
for (const book of books) {
for (const item of extractor(book)) {
const id = item.id;
if (!filterMap.has(id)) {
filterMap.set(id, {value: item, bookCount: 0});
}
filterMap.get(id)!.bookCount++;
}
}
const filters = Array.from(filterMap.values());
const sorted = sortMode === 'sortIndex'
? this.sortFiltersBySortIndex(filters)
: this.sortFiltersByCount(filters);
return sorted.slice(0, MAX_FILTER_ITEMS);
}
private sortFiltersByCount(filters: Filter[]): Filter[] {
return filters.sort((a, b) => {
if (b.bookCount !== a.bookCount) return b.bookCount - a.bookCount;
return this.compareNames(a, b);
return (items ?? []).map(item => {
const rangeId = Number(item.name);
const range = ranges.find(r => r.id === rangeId);
return {
value: {id: rangeId, name: range?.label || item.name, sortIndex: range?.sortIndex},
bookCount: item.count
};
});
}
private sortFiltersBySortIndex(filters: Filter[]): Filter[] {
return filters.sort((a, b) => {
const aIndex = (a.value as { sortIndex?: number }).sortIndex ?? 999;
const bIndex = (b.value as { sortIndex?: number }).sortIndex ?? 999;
if (aIndex !== bIndex) return aIndex - bIndex;
return this.compareNames(a, b);
});
}
private compareNames(a: Filter, b: Filter): number {
const aName = String((a.value as { name?: string }).name ?? '');
const bName = String((b.value as { name?: string }).name ?? '');
return aName.localeCompare(bName);
}
private filterByMagicShelf(books: Book[], magicShelf: MagicShelf): Book[] {
if (!magicShelf.filterJson) return [];
try {
@@ -5,6 +5,7 @@ import {
doesBookMatchFilter,
doesBookMatchReadStatus,
filterBooksByFilters,
isAgeRatingInRange,
isFileSizeInRange,
isMatchScoreInRange,
isPageCountInRange,
@@ -63,6 +64,8 @@ describe('sidebar-filter', () => {
expect(isFileSizeInRange(undefined, 1)).toBe(false);
expect(isFileSizeInRange(1500, 1)).toBe(true);
expect(isPageCountInRange(230, '3')).toBe(true);
expect(isAgeRatingInRange(16, 16)).toBe(true);
expect(isAgeRatingInRange(12, 10)).toBe(true);
expect(isMatchScoreInRange(87, 2)).toBe(true);
expect(isMatchScoreInRange(87, 9)).toBe(false);
expect(doesBookMatchReadStatus(makeBook(1), [ReadStatus.UNREAD])).toBe(true);
@@ -1,4 +1,4 @@
import {fileSizeRanges, matchScoreRanges, pageCountRanges, ratingRanges} from '../book-filter/book-filter.config';
import {ageRatingRanges, fileSizeRanges, matchScoreRanges, pageCountRanges, ratingRanges} from '../book-filter/book-filter.config';
import {Book, ReadStatus} from '../../../model/book.model';
import {BookFilterMode} from '../../../../settings/user-management/user.service';
@@ -41,6 +41,14 @@ export function isMatchScoreInRange(score: number | undefined | null, rangeId: s
return normalizedScore >= range.min && normalizedScore < range.max;
}
export function isAgeRatingInRange(ageRating: number | undefined | null, rangeId: string | number): boolean {
if (ageRating == null) return false;
const numericId = typeof rangeId === 'string' ? Number(rangeId) : rangeId;
const range = ageRatingRanges.find(r => r.id === numericId);
if (!range) return false;
return ageRating >= range.min && ageRating < range.max;
}
export function doesBookMatchReadStatus(book: Book, selected: unknown[]): boolean {
const status = book.readStatus ?? ReadStatus.UNSET;
return selected.includes(status);
@@ -122,10 +130,7 @@ export function doesBookMatchFilter(
? filterValues.some(val => book.metadata?.moods?.includes(val as string))
: filterValues.every(val => book.metadata?.moods?.includes(val as string));
case 'ageRating':
return filterValues.some(val => {
const numVal = typeof val === 'string' ? Number(val) : val;
return book.metadata?.ageRating === numVal;
});
return filterValues.some(range => isAgeRatingInRange(book.metadata?.ageRating, range as string | number));
case 'contentRating':
return filterValues.includes(book.metadata?.contentRating);
case 'narrator':
@@ -25,6 +25,12 @@ export interface AppBookSummary {
coverUpdatedOn: string | null;
audiobookCoverUpdatedOn: string | null;
isPhysical: boolean | null;
publishedDate: string | null;
pageCount: number | null;
ageRating: number | null;
contentRating: string | null;
metadataMatchScore: number | null;
fileSizeKb: number | null;
}
export interface AppFilterOptions {
@@ -38,6 +44,23 @@ export interface AppFilterOptions {
tags: CountedOption[];
moods: CountedOption[];
narrators: CountedOption[];
ageRatings: CountedOption[];
contentRatings: CountedOption[];
matchScores: CountedOption[];
publishedYears: CountedOption[];
fileSizes: CountedOption[];
personalRatings: CountedOption[];
amazonRatings: CountedOption[];
goodreadsRatings: CountedOption[];
hardcoverRatings: CountedOption[];
pageCounts: CountedOption[];
shelfStatuses: CountedOption[];
comicCharacters: CountedOption[];
comicTeams: CountedOption[];
comicLocations: CountedOption[];
comicCreators: CountedOption[];
shelves: CountedOption[];
libraries: CountedOption[];
}
export interface CountedOption {
@@ -69,6 +92,23 @@ export interface AppBookFilters {
tag?: string[];
mood?: string[];
narrator?: string[];
ageRating?: string[];
contentRating?: string[];
matchScore?: string[];
publishedDate?: string[];
fileSize?: string[];
personalRating?: string[];
amazonRating?: string[];
goodreadsRating?: string[];
hardcoverRating?: string[];
pageCount?: string[];
shelfStatus?: string[];
comicCharacter?: string[];
comicTeam?: string[];
comicLocation?: string[];
comicCreator?: string[];
shelves?: string[];
libraries?: string[];
filterMode?: 'and' | 'or' | 'not';
}
@@ -87,7 +87,38 @@ export class AppBooksApiService {
const err = this.booksQuery.error();
return err instanceof Error ? err.message : 'Failed to load books';
});
readonly filterOptions = computed(() => this.filterOptionsQuery.data() ?? null);
private readonly _filterOptions = computed(() => this.filterOptionsQuery.data() ?? null);
readonly filterOptions = this._filterOptions;
// Individual signals for each filter type for more granular reactivity
readonly authorOptions = computed(() => this._filterOptions()?.authors ?? []);
readonly languageOptions = computed(() => this._filterOptions()?.languages ?? []);
readonly categoryOptions = computed(() => this._filterOptions()?.categories ?? []);
readonly seriesOptions = computed(() => this._filterOptions()?.series ?? []);
readonly publisherOptions = computed(() => this._filterOptions()?.publishers ?? []);
readonly tagOptions = computed(() => this._filterOptions()?.tags ?? []);
readonly moodOptions = computed(() => this._filterOptions()?.moods ?? []);
readonly narratorOptions = computed(() => this._filterOptions()?.narrators ?? []);
readonly ageRatingOptions = computed(() => this._filterOptions()?.ageRatings ?? []);
readonly contentRatingOptions = computed(() => this._filterOptions()?.contentRatings ?? []);
readonly matchScoreOptions = computed(() => this._filterOptions()?.matchScores ?? []);
readonly publishedYearOptions = computed(() => this._filterOptions()?.publishedYears ?? []);
readonly fileSizeOptions = computed(() => this._filterOptions()?.fileSizes ?? []);
readonly personalRatingOptions = computed(() => this._filterOptions()?.personalRatings ?? []);
readonly amazonRatingOptions = computed(() => this._filterOptions()?.amazonRatings ?? []);
readonly goodreadsRatingOptions = computed(() => this._filterOptions()?.goodreadsRatings ?? []);
readonly hardcoverRatingOptions = computed(() => this._filterOptions()?.hardcoverRatings ?? []);
readonly pageCountOptions = computed(() => this._filterOptions()?.pageCounts ?? []);
readonly shelfStatusOptions = computed(() => this._filterOptions()?.shelfStatuses ?? []);
readonly readStatusOptions = computed(() => this._filterOptions()?.readStatuses ?? []);
readonly fileTypeOptions = computed(() => this._filterOptions()?.fileTypes ?? []);
readonly comicCharacterOptions = computed(() => this._filterOptions()?.comicCharacters ?? []);
readonly comicTeamOptions = computed(() => this._filterOptions()?.comicTeams ?? []);
readonly comicLocationOptions = computed(() => this._filterOptions()?.comicLocations ?? []);
readonly comicCreatorOptions = computed(() => this._filterOptions()?.comicCreators ?? []);
readonly shelfOptions = computed(() => this._filterOptions()?.shelves ?? []);
readonly libraryOptions = computed(() => this._filterOptions()?.libraries ?? []);
setFilters(filters: AppBookFilters): void {
if (JSON.stringify(this._filters()) !== JSON.stringify(filters)) {
@@ -148,6 +179,23 @@ export class AppBooksApiService {
['tag', filters.tag],
['mood', filters.mood],
['narrator', filters.narrator],
['ageRating', filters.ageRating],
['contentRating', filters.contentRating],
['matchScore', filters.matchScore],
['publishedDate', filters.publishedDate],
['fileSize', filters.fileSize],
['personalRating', filters.personalRating],
['amazonRating', filters.amazonRating],
['goodreadsRating', filters.goodreadsRating],
['hardcoverRating', filters.hardcoverRating],
['pageCount', filters.pageCount],
['shelfStatus', filters.shelfStatus],
['comicCharacter', filters.comicCharacter],
['comicTeam', filters.comicTeam],
['comicLocation', filters.comicLocation],
['comicCreator', filters.comicCreator],
['shelves', filters.shelves],
['libraries', filters.libraries],
['status', filters.status],
['fileType', filters.fileType],
];
@@ -176,6 +224,8 @@ function summaryToBook(summary: AppBookSummary): Book {
addedOn: summary.addedOn,
lastReadTime: summary.lastReadTime,
isPhysical: summary.isPhysical ?? false,
fileSizeKb: summary.fileSizeKb ?? undefined,
metadataMatchScore: summary.metadataMatchScore,
metadata: {
bookId: summary.id,
title: summary.title,
@@ -184,6 +234,10 @@ function summaryToBook(summary: AppBookSummary): Book {
seriesNumber: summary.seriesNumber,
coverUpdatedOn: summary.coverUpdatedOn,
audiobookCoverUpdatedOn: summary.audiobookCoverUpdatedOn,
publishedDate: summary.publishedDate ?? undefined,
pageCount: summary.pageCount,
ageRating: summary.ageRating,
contentRating: summary.contentRating,
},
primaryFile: summary.primaryFileType
? {bookType: summary.primaryFileType as BookType, extension: summary.primaryFileType.toLowerCase()}
@@ -231,8 +231,10 @@ export type VisibleFilterType =
export const DEFAULT_VISIBLE_FILTERS: VisibleFilterType[] = [
'author', 'category', 'series', 'bookType', 'readStatus',
'personalRating', 'library', 'tag', 'ageRating', 'contentRating',
'matchScore', 'publisher', 'publishedDate', 'fileSize'
'personalRating', 'amazonRating', 'goodreadsRating', 'hardcoverRating',
'library', 'tag', 'ageRating', 'contentRating',
'matchScore', 'publisher', 'publishedDate', 'fileSize',
'pageCount', 'shelfStatus', 'language', 'mood', 'narrator'
];
// Translation key for each filter option — use book.filter.labels.<value>