refactor(covers): consolidate cover images into app-cover (#1928)

This commit is contained in:
Alex
2026-07-09 10:13:37 +01:00
committed by GitHub
parent 0d287a0291
commit b4570e3366
54 changed files with 354 additions and 593 deletions
@@ -1,24 +0,0 @@
package org.booklore.config.security;
import org.booklore.config.security.filter.ImageCachingFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
@Configuration
public class ImageCacheConfig {
@Bean
public FilterRegistrationBean<ImageCachingFilter> imageCachingFilterRegistration() {
FilterRegistrationBean<ImageCachingFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new ImageCachingFilter());
registrationBean.addUrlPatterns(
"/api/v1/media/book/*/cover",
"/api/v1/media/book/*/thumbnail",
"/api/v1/media/book/*/backup-cover"
);
registrationBean.setOrder(Ordered.LOWEST_PRECEDENCE);
return registrationBean;
}
}
@@ -1,27 +0,0 @@
package org.booklore.config.security.filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.http.HttpHeaders;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Component
public class ImageCachingFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String uri = request.getRequestURI();
if (uri.startsWith("/api/v1/media/book/") &&
(uri.contains("/cover") || uri.contains("/thumbnail") || uri.contains("/backup-cover") ||
uri.contains("/cbx/pages/"))) {
response.setHeader(HttpHeaders.CACHE_CONTROL, "public, max-age=3600");
response.setHeader(HttpHeaders.EXPIRES, String.valueOf(System.currentTimeMillis() + 3600_000));
}
filterChain.doFilter(request, response);
}
}
@@ -12,12 +12,15 @@ import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.core.io.Resource;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.time.Duration;
import java.util.Optional;
@Tag(name = "Book Media", description = "Endpoints for retrieving book media such as covers, thumbnails, and pages")
@AllArgsConstructor
@@ -25,6 +28,8 @@ import java.io.IOException;
@RequestMapping("/api/v1/media")
public class BookMediaController {
private static final CacheControl IMAGE_CACHE = CacheControl.maxAge(Duration.ofHours(1)).cachePrivate();
private final BookService bookService;
private final CbxReaderService cbxReaderService;
private final BookDropService bookDropService;
@@ -32,34 +37,44 @@ public class BookMediaController {
@Operation(summary = "Get book thumbnail", description = "Retrieve the thumbnail image for a specific book.")
@ApiResponse(responseCode = "200", description = "Book thumbnail returned successfully")
@ApiResponse(responseCode = "404", description = "No thumbnail exists for this book")
@GetMapping("/book/{bookId}/thumbnail")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<Resource> getBookThumbnail(@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookService.getBookThumbnail(bookId));
return toImageResponse(bookService.getBookThumbnailIfPresent(bookId));
}
@Operation(summary = "Get book cover", description = "Retrieve the cover image for a specific book.")
@ApiResponse(responseCode = "200", description = "Book cover returned successfully")
@ApiResponse(responseCode = "404", description = "No cover exists for this book")
@GetMapping("/book/{bookId}/cover")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<Resource> getBookCover(@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookService.getBookCover(bookId));
return toImageResponse(bookService.getBookCoverIfPresent(bookId));
}
@Operation(summary = "Get audiobook thumbnail", description = "Retrieve the audiobook thumbnail image for a specific book.")
@ApiResponse(responseCode = "200", description = "Audiobook thumbnail returned successfully")
@ApiResponse(responseCode = "404", description = "No audiobook thumbnail exists for this book")
@GetMapping("/book/{bookId}/audiobook-thumbnail")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<Resource> getAudiobookThumbnail(@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookService.getAudiobookThumbnail(bookId));
return toImageResponse(bookService.getAudiobookThumbnailIfPresent(bookId));
}
@Operation(summary = "Get audiobook cover", description = "Retrieve the audiobook cover image for a specific book.")
@ApiResponse(responseCode = "200", description = "Audiobook cover returned successfully")
@ApiResponse(responseCode = "404", description = "No audiobook cover exists for this book")
@GetMapping("/book/{bookId}/audiobook-cover")
@CheckBookAccess(bookIdParam = "bookId")
public ResponseEntity<Resource> getAudiobookCover(@Parameter(description = "ID of the book") @PathVariable long bookId) {
return ResponseEntity.ok(bookService.getAudiobookCover(bookId));
return toImageResponse(bookService.getAudiobookCoverIfPresent(bookId));
}
private ResponseEntity<Resource> toImageResponse(Optional<Resource> image) {
return image
.map(resource -> ResponseEntity.ok().cacheControl(IMAGE_CACHE).body(resource))
.orElseGet(() -> ResponseEntity.notFound().cacheControl(CacheControl.noStore()).build());
}
@Operation(summary = "Get CBX page as image", description = "Retrieve a specific page from a CBX book as an image.")
@@ -72,6 +87,7 @@ public class BookMediaController {
@Parameter(description = "Optional book type for alternative format (e.g., PDF, CBX)") @RequestParam(required = false) String bookType,
HttpServletResponse response) throws IOException {
response.setContentType(MediaType.IMAGE_JPEG_VALUE);
response.setHeader(HttpHeaders.CACHE_CONTROL, IMAGE_CACHE.getHeaderValue());
cbxReaderService.streamPageImage(bookId, bookType, pageNumber, response.getOutputStream());
}
@@ -110,4 +126,4 @@ public class BookMediaController {
.body(file)
: ResponseEntity.noContent().build();
}
}
}
@@ -280,30 +280,20 @@ public class BookService {
return bookUpdateService.assignShelvesToBooks(bookIds, shelfIdsToAssign, shelfIdsToUnassign);
}
public Optional<Resource> getBookThumbnailIfPresent(long bookId) {
return resolveImageResource(fileService.getThumbnailFile(bookId), bookId);
}
public Resource getBookThumbnail(long bookId) {
Path thumbnailPath = Paths.get(fileService.getThumbnailFile(bookId));
try {
if (Files.exists(thumbnailPath)) {
return new UrlResource(thumbnailPath.toUri());
} else {
return new ClassPathResource("static/images/missing-cover.jpg");
}
} catch (MalformedURLException e) {
throw new RuntimeException("Failed to load book cover for bookId=" + bookId, e);
}
return getBookThumbnailIfPresent(bookId).orElseGet(this::getMissingCoverResource);
}
public Optional<Resource> getBookCoverIfPresent(long bookId) {
return resolveImageResource(fileService.getCoverFile(bookId), bookId);
}
public Resource getBookCover(long bookId) {
Path coverPath = Paths.get(fileService.getCoverFile(bookId));
try {
if (Files.exists(coverPath)) {
return new UrlResource(coverPath.toUri());
} else {
return getMissingCoverResource();
}
} catch (MalformedURLException e) {
throw new RuntimeException("Failed to load book cover for bookId=" + bookId, e);
}
return getBookCoverIfPresent(bookId).orElseGet(this::getMissingCoverResource);
}
public Resource getBookCover(String coverHash) {
@@ -311,29 +301,32 @@ public class BookService {
return getBookCover(bookEntity.getId());
}
public Optional<Resource> getAudiobookThumbnailIfPresent(long bookId) {
return resolveImageResource(fileService.getAudiobookThumbnailFile(bookId), bookId);
}
public Resource getAudiobookThumbnail(long bookId) {
Path thumbnailPath = Paths.get(fileService.getAudiobookThumbnailFile(bookId));
try {
if (Files.exists(thumbnailPath)) {
return new UrlResource(thumbnailPath.toUri());
} else {
return getMissingCoverResource();
}
} catch (MalformedURLException e) {
throw new RuntimeException("Failed to load audiobook thumbnail for bookId=" + bookId, e);
}
return getAudiobookThumbnailIfPresent(bookId).orElseGet(this::getMissingCoverResource);
}
public Optional<Resource> getAudiobookCoverIfPresent(long bookId) {
return resolveImageResource(fileService.getAudiobookCoverFile(bookId), bookId);
}
public Resource getAudiobookCover(long bookId) {
Path coverPath = Paths.get(fileService.getAudiobookCoverFile(bookId));
return getAudiobookCoverIfPresent(bookId).orElseGet(this::getMissingCoverResource);
}
private Optional<Resource> resolveImageResource(String filePath, long bookId) {
Path path = Paths.get(filePath);
if (!Files.exists(path)) {
return Optional.empty();
}
try {
if (Files.exists(coverPath)) {
return new UrlResource(coverPath.toUri());
} else {
return getMissingCoverResource();
}
return Optional.of(new UrlResource(path.toUri()));
} catch (MalformedURLException e) {
throw new RuntimeException("Failed to load audiobook cover for bookId=" + bookId, e);
log.error("Failed to load image for bookId={} from path={}", bookId, filePath, e);
throw ApiError.INTERNAL_SERVER_ERROR.createException("Failed to load image for bookId=" + bookId);
}
}
@@ -6,20 +6,14 @@
(keydown.enter)="onCardClick($event)">
<div class="cover-container" [ngClass]="{ 'center-info-btn': isSeriesViewActive() || !hasDigitalFile(), 'audiobook-cover': isAudiobook(), 'square-library-cover': useSquareCovers() }">
@if (coverImageUrl(); as url) {
<img
[src]="url"
class="book-cover"
[class.square-cover]="isAudiobook() || useSquareCovers()"
[alt]="('book.card.alt.cover' | transloco: { title: displayTitle() })"
width="250"
[height]="(isAudiobook() || useSquareCovers()) ? 250 : 350"
loading="lazy"
decoding="async"
fetchpriority="low"/>
} @else {
<app-cover-placeholder class="book-cover" [class.square-cover]="isAudiobook() || useSquareCovers()" [title]="book().metadata?.title ?? ''" [author]="(book().metadata?.authors ?? []).join(', ')" />
}
<app-cover
class="book-cover"
[class.square-cover]="isAudiobook() || useSquareCovers()"
[src]="coverImageUrl()"
[title]="displayTitle()"
[authors]="book().metadata?.authors ?? []"
[fit]="(isAudiobook() || useSquareCovers()) ? 'contain' : 'cover'"
[alt]="('book.card.alt.cover' | transloco: { title: displayTitle() })"/>
<div class="top-left-overlay-stack">
@if (showBookTypePill() && displayFormat(); as fmt) {
@@ -47,10 +47,6 @@
border-radius: 8px 8px 0 0;
}
.book-cover.square-cover {
object-fit: contain;
}
.cover-container::after {
content: "";
position: absolute;
@@ -9,7 +9,7 @@ import {CheckboxChangeEvent, Checkbox} from 'primeng/checkbox';
import {FormsModule} from '@angular/forms';
import {MetadataRefreshType} from '../../../../metadata/model/request/metadata-refresh-type.enum';
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
import {CoverPlaceholderComponent} from '../../../../../shared/components/cover-generator/cover-generator.component';
import {CoverComponent} from '../../../../../shared/components/cover/cover.component';
import {NgClass} from '@angular/common';
import {UserService} from '../../../../settings/user-management/user.service';
import {EmailService} from '../../../../settings/email-v2/email.service';
@@ -31,7 +31,7 @@ import {ButtonDirective} from 'primeng/button';
selector: 'app-book-card',
templateUrl: './book-card.component.html',
styleUrls: ['./book-card.component.scss'],
imports: [ButtonDirective, Checkbox, FormsModule, NgClass, TieredMenu, Tooltip, RouterLink, TranslocoPipe, CoverPlaceholderComponent],
imports: [ButtonDirective, Checkbox, FormsModule, NgClass, TieredMenu, Tooltip, RouterLink, TranslocoPipe, CoverComponent],
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush
})
@@ -48,21 +48,14 @@
(mouseleave)="coverPreviewHide.emit(currentBook.id)"
(focusin)="showCoverPreview(coverOrigin)"
(focusout)="coverPreviewHide.emit(currentBook.id)">
@if (imageUrl) {
<img
[attr.src]="imageUrl"
alt=""
class="cover-thumbnail"
[class.square-cover]="squareCover" />
} @else {
<app-cover-placeholder
class="cover-thumbnail"
aria-hidden="true"
[class.square-cover]="squareCover"
[title]="currentMetadata.title ?? ''"
[author]="(currentMetadata.authors ?? []).join(', ')"
size="sm" />
}
<app-cover
class="cover-thumbnail"
aria-hidden="true"
[class.square-cover]="squareCover"
[src]="imageUrl"
[title]="currentMetadata.title || currentBook.fileName"
[authors]="currentMetadata.authors ?? []"
size="sm" />
</a>
}
@case ('readStatus') {
@@ -79,12 +79,13 @@
}
.cover-thumbnail {
width: calc(1.75rem * 5 / 7);
height: 1.75rem;
aspect-ratio: 5 / 7;
object-fit: cover;
border-radius: 4px;
&.square-cover {
width: 1.75rem;
aspect-ratio: 1 / 1;
}
}
@@ -98,12 +98,12 @@ describe('BookTableRowComponent', () => {
const host = fixture.nativeElement as HTMLElement;
const lockButton = host.querySelector<HTMLButtonElement>('.metadata-lock-button');
const coverLink = host.querySelector<HTMLAnchorElement>('.cover-link');
const placeholder = host.querySelector<HTMLElement>('app-cover-placeholder');
const cover = host.querySelector<HTMLElement>('app-cover');
expect(lockButton?.getAttribute('aria-label')).toBe('Unlocked');
expect(lockButton?.getAttribute('aria-pressed')).toBe('false');
expect(coverLink?.getAttribute('aria-label')).toBe('Alpha');
expect(placeholder?.getAttribute('aria-hidden')).toBe('true');
expect(cover?.getAttribute('aria-hidden')).toBe('true');
});
it('formats file sizes with the matching unit', () => {
@@ -9,7 +9,7 @@ import {Tooltip} from 'primeng/tooltip';
import {Book, BookMetadata} from '../../../model/book.model';
import {ReadStatusHelper} from '../../../helpers/read-status.helper';
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
import {CoverPlaceholderComponent} from '../../../../../shared/components/cover-generator/cover-generator.component';
import {CoverComponent} from '../../../../../shared/components/cover/cover.component';
import {AppRatingComponent} from '../../../../../shared/ui/rating/app-rating.component';
import {RATING_FIELDS, isMetadataFullyLocked} from './book-table.helpers';
@@ -86,7 +86,7 @@ const CLICKABLE_FILTER_KEYS: Record<string, string> = {
imports: [
CdkOverlayOrigin,
Checkbox,
CoverPlaceholderComponent,
CoverComponent,
FormsModule,
NgClass,
AppRatingComponent,
@@ -94,19 +94,13 @@
[cdkConnectedOverlayPush]="true"
[cdkConnectedOverlayFlexibleDimensions]="true">
<div class="cover-preview">
@if (preview.coverUrl; as coverUrl) {
<img
[attr.src]="coverUrl"
[alt]="t('book.table.bookCoverAlt')"
class="cover-preview-image"
[class.square-cover]="preview.useSquareCover" />
} @else {
<app-cover-placeholder
class="cover-preview-image"
[class.square-cover]="preview.useSquareCover"
[title]="preview.metadata.title ?? ''"
[author]="(preview.metadata.authors ?? []).join(', ')" />
}
<app-cover
class="cover-preview-image"
[class.square-cover]="preview.useSquareCover"
[src]="preview.coverUrl"
[title]="preview.metadata.title"
[authors]="preview.metadata.authors ?? []"
[alt]="preview.metadata.title || t('book.table.bookCoverAlt')" />
</div>
</ng-template>
}
@@ -144,7 +144,6 @@
width: 100%;
max-height: calc(100dvh - 5.25rem);
aspect-ratio: 5 / 7;
object-fit: cover;
border-radius: inherit;
&.square-cover {
@@ -11,7 +11,7 @@ import {injectVirtualizer} from '@tanstack/angular-virtual';
import {Checkbox} from 'primeng/checkbox';
import {Book, BookMetadata} from '../../../model/book.model';
import {RouteScrollPositionService} from '../../../../../shared/service/route-scroll-position.service';
import {CoverPlaceholderComponent} from '../../../../../shared/components/cover-generator/cover-generator.component';
import {CoverComponent} from '../../../../../shared/components/cover/cover.component';
import {BookMetadataManageService} from '../../../service/book-metadata-manage.service';
import {patchAppBooksMetadataLockInCache} from '../../../service/book-query-cache';
import {MessageService} from 'primeng/api';
@@ -70,7 +70,7 @@ const COVER_OVERLAY_POSITIONS: ConnectedPosition[] = [
Checkbox,
FormsModule,
TranslocoDirective,
CoverPlaceholderComponent
CoverComponent
],
styleUrls: ['./book-table.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
@@ -1,17 +1,11 @@
<div class="book-cover-wrapper" [class.audiobook-only]="isAudiobookOnly()" (mouseenter)="isHovered = true" (mouseleave)="isHovered = false">
@if (getThumbnailUrl(); as coverUrl) {
<img
[src]="coverUrl"
class="book-cover"
alt="Cover of {{ book.metadata?.title }}"
width="250"
height="350"
loading="lazy"
decoding="async"
fetchpriority="low"/>
} @else {
<app-cover-placeholder class="book-cover" [title]="book.metadata?.title ?? ''" [author]="(book.metadata?.authors ?? []).join(', ')" size="sm" />
}
<app-cover
class="book-cover"
[src]="getThumbnailUrl()"
[title]="book.metadata?.title || book.fileName"
[authors]="book.metadata?.authors ?? []"
[alt]="book.metadata?.title || book.fileName || ''"
size="sm" />
@if (showSeriesNumber && !book.seriesCount && book.metadata?.seriesNumber !== null && book.metadata?.seriesNumber !== undefined) {
<div class="series-number-overlay">
@@ -7,7 +7,6 @@
.book-cover {
width: 100%;
aspect-ratio: 5 / 7;
object-fit: cover;
display: block;
border-radius: 0.4375rem;
}
@@ -15,7 +14,6 @@
&.audiobook-only {
.book-cover {
aspect-ratio: 1 / 1;
object-fit: cover;
}
}
@@ -1,7 +1,7 @@
import {ChangeDetectionStrategy, Component, computed, inject, Input} from '@angular/core';
import {Book} from '../../model/book.model';
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
import {CoverPlaceholderComponent} from '../../../../shared/components/cover-generator/cover-generator.component';
import {CoverComponent} from '../../../../shared/components/cover/cover.component';
import {Button} from 'primeng/button';
import {UserService} from '../../../settings/user-management/user.service';
import {Router} from '@angular/router';
@@ -16,7 +16,7 @@ import {Tooltip} from 'primeng/tooltip';
Button,
NgClass,
Tooltip,
CoverPlaceholderComponent
CoverComponent
],
templateUrl: './book-card-lite-component.html',
styleUrl: './book-card-lite-component.scss'
@@ -186,14 +186,13 @@
class="delete-checkbox">
</p-checkbox>
}
@if (urlHelper.getThumbnailUrl(book.id, book.metadata?.coverUpdatedOn); as coverUrl) {
<img class="book-cover"
[src]="coverUrl"
[alt]="book.metadata?.title || ''"
loading="lazy"/>
} @else {
<app-cover-placeholder class="book-cover" [title]="book.metadata?.title ?? ''" [author]="(book.metadata?.authors ?? []).join(', ')" size="sm" />
}
<app-cover class="book-cover"
aria-hidden="true"
[src]="urlHelper.getThumbnailUrl(book.id, book.metadata?.coverUpdatedOn)"
[title]="book.metadata?.title"
[authors]="book.metadata?.authors ?? []"
size="sm"
loading="lazy" />
<div class="book-info">
<div class="book-title">{{ book.metadata?.title || ('book.fileAttacher.unknownTitle' | transloco) }}</div>
@if (book.metadata?.authors?.length) {
@@ -204,7 +204,6 @@
height: 52px;
flex-shrink: 0;
border-radius: 3px;
object-fit: cover;
background: var(--color-card);
}
@@ -14,8 +14,8 @@ import {BookService} from '../../service/book.service';
import {Book, DuplicateDetectionRequest, DuplicateGroup} from '../../model/book.model';
import {ConfirmationService, MessageService} from 'primeng/api';
import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco';
import {CoverComponent} from '../../../../shared/components/cover/cover.component';
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
import {CoverPlaceholderComponent} from '../../../../shared/components/cover-generator/cover-generator.component';
import {AppSettingsService} from '../../../../shared/service/app-settings.service';
type PresetMode = 'strict' | 'balanced' | 'aggressive' | 'custom';
@@ -40,7 +40,7 @@ interface DisplayGroup extends DuplicateGroup {
Paginator,
TranslocoDirective,
TranslocoPipe,
CoverPlaceholderComponent,
CoverComponent,
],
templateUrl: './duplicate-merger.component.html',
styleUrls: ['./duplicate-merger.component.scss']
@@ -32,16 +32,14 @@
<div class="series-hero">
@if (coverBook(); as coverBook) {
<div class="hero-cover-section">
@if (getBookCoverUrl(coverBook); as coverUrl) {
<img
[src]="coverUrl"
class="hero-cover-img"
[alt]="coverBook.metadata?.title || ''"
loading="lazy"
decoding="async"/>
} @else {
<app-cover-placeholder class="hero-cover-img" [title]="coverBook.metadata?.title ?? ''" [author]="(coverBook.metadata?.authors ?? []).join(', ')" size="lg" />
}
<app-cover
class="hero-cover-img"
[src]="getBookCoverUrl(coverBook)"
[title]="coverBook.metadata?.title"
[authors]="coverBook.metadata?.authors ?? []"
size="lg"
[alt]="coverBook.metadata?.title ?? ''"
loading="lazy" />
</div>
}
@@ -190,14 +188,14 @@
tabindex="0"
(click)="readBook(nextUp.book.id)"
(keydown.enter)="readBook(nextUp.book.id)">
@if (nextUp.thumbnailUrl) {
<img [src]="nextUp.thumbnailUrl"
[alt]="nextUp.book.metadata?.title || ''"
class="next-up-thumb"
loading="lazy"/>
} @else {
<app-cover-placeholder class="next-up-thumb" [title]="nextUp.book.metadata?.title ?? ''" [author]="(nextUp.book.metadata?.authors ?? []).join(', ')" size="sm" />
}
<app-cover
class="next-up-thumb"
aria-hidden="true"
[src]="nextUp.thumbnailUrl"
[title]="nextUp.book.metadata?.title"
[authors]="nextUp.book.metadata?.authors ?? []"
size="sm"
loading="lazy" />
<div class="next-up-info">
<span class="next-up-label">
<i class="pi pi-bookmark-fill"></i>
@@ -321,14 +319,14 @@
{{ book.metadata?.seriesNumber !== null && book.metadata?.seriesNumber !== undefined ? '#' + book.metadata?.seriesNumber : '-' }}
</span>
</div>
@if (getBookThumbnailUrl(book); as coverUrl) {
<img [src]="coverUrl"
[alt]="book.metadata?.title || ''"
class="list-thumb"
loading="lazy"/>
} @else {
<app-cover-placeholder class="list-thumb" [title]="book.metadata?.title ?? ''" [author]="(book.metadata?.authors ?? []).join(', ')" size="sm" />
}
<app-cover
class="list-thumb"
aria-hidden="true"
[src]="getBookThumbnailUrl(book)"
[title]="book.metadata?.title"
[authors]="book.metadata?.authors ?? []"
size="sm"
loading="lazy" />
<div class="list-book-info">
<span class="list-book-title">{{ book.metadata?.title || '' }}</span>
<div class="list-book-meta">
@@ -72,7 +72,6 @@
.hero-cover-img {
width: 240px;
height: 360px;
object-fit: cover;
border-radius: 12px;
box-shadow: 0 6px 24px rgb(0 0 0 / 40%);
@@ -460,7 +459,6 @@ $meta-card-colors: (
.next-up-thumb {
width: 2.4063rem;
height: 3.5rem;
object-fit: cover;
border-radius: 0.2188rem;
flex-shrink: 0;
box-shadow: 0 2px 6px rgb(0 0 0 / 25%);
@@ -618,7 +616,6 @@ $meta-card-colors: (
.list-thumb {
width: 2.4063rem;
height: 3.5rem;
object-fit: cover;
border-radius: 0.3281rem;
flex-shrink: 0;
box-shadow: 0 2px 6px rgb(0 0 0 / 20%);
@@ -28,7 +28,7 @@ import {TagComponent} from "../../../../shared/components/tag/tag.component";
import {AfterViewChecked, ChangeDetectionStrategy, Component, computed, effect, ElementRef, inject, signal, viewChild} from '@angular/core';
import {BookCardOverlayPreferenceService} from '../book-browser/book-card-overlay-preference.service';
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
import {CoverPlaceholderComponent} from '../../../../shared/components/cover-generator/cover-generator.component';
import {CoverComponent} from '../../../../shared/components/cover/cover.component';
import {injectQuery} from '@tanstack/angular-query-experimental';
import {AuthorService} from '../../../author-browser/service/author.service';
import {LayoutService} from '../../../../shared/layout/layout.service';
@@ -89,7 +89,7 @@ interface SeriesStats {
Divider,
TranslocoDirective,
TagComponent,
CoverPlaceholderComponent,
CoverComponent,
],
})
export class SeriesPageComponent implements AfterViewChecked {
@@ -60,15 +60,12 @@
@if (item.kind === 'book' && item.bookMeta; as bookMeta) {
<ng-container *transloco="let tb; prefix: 'book.searcher'">
<div class="command-palette-book-cover" [class.square-cover]="bookMeta.isAudiobook">
@if (bookMeta.thumbnailUrl) {
<img [src]="bookMeta.thumbnailUrl" alt="" />
} @else {
<app-cover-placeholder
[title]="item.title"
[author]="bookMeta.authors.join(', ')"
size="sm"
></app-cover-placeholder>
}
<app-cover
aria-hidden="true"
[src]="bookMeta.thumbnailUrl"
[title]="item.title"
[authors]="bookMeta.authors"
size="sm" />
</div>
<div class="command-palette-book-details">
<div class="command-palette-book-title">{{ item.title }}</div>
@@ -172,13 +172,6 @@
&.square-cover {
height: 32px;
}
img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
}
.command-palette-book-details {
@@ -9,7 +9,7 @@ import { TranslocoDirective, TranslocoPipe } from '@jsverse/transloco';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { LucideSearch, LucideX } from '@lucide/angular';
import { CoverPlaceholderComponent } from '../../shared/components/cover-generator/cover-generator.component';
import { CoverComponent } from '../../shared/components/cover/cover.component';
import { IconDisplayComponent } from '../../shared/components/icon-display/icon-display.component';
import { MOBILE_SHELL_ACTIVE_PROPERTY } from '../../shared/layout/layout.service';
import { PaletteItem } from './command-palette.model';
@@ -18,7 +18,7 @@ import { CommandPaletteService } from './command-palette.service';
@Component({
selector: 'app-command-palette',
standalone: true,
imports: [A11yModule, OverlayModule, FormsModule, TranslocoDirective, TranslocoPipe, IconDisplayComponent, CoverPlaceholderComponent, LucideSearch, LucideX],
imports: [A11yModule, OverlayModule, FormsModule, TranslocoDirective, TranslocoPipe, IconDisplayComponent, CoverComponent, LucideSearch, LucideX],
templateUrl: './command-palette.component.html',
styleUrl: './command-palette.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
@@ -17,18 +17,14 @@
<i class="pi pi-book"></i> {{ t('ebookCover') }}
</div>
}
@if (urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn); as coverUrl) {
<p-image
[src]="coverUrl"
alt="Cover Image"
width="200"
appendTo="body"
lazyLoad
[preview]="true">
</p-image>
} @else {
<app-cover-placeholder style="width: 200px; height: 280px;" [title]="book.metadata?.title ?? ''" [author]="(book.metadata?.authors ?? []).join(', ')" size="lg" />
}
<app-cover
style="width: 200px; height: 280px;"
[src]="urlHelper.getCoverUrl(book.id, book.metadata?.coverUpdatedOn)"
[title]="book.metadata?.title"
[authors]="book.metadata?.authors ?? []"
size="lg"
[preview]="true"
[alt]="t('ebookCover')" />
@if (isUploading) {
<p-progressSpinner class="upload-spinner"></p-progressSpinner>
}
@@ -97,19 +93,15 @@
<div class="cover-type-label audiobook">
<i class="pi pi-headphones"></i> {{ t('audiobookCover') }}
</div>
@if (urlHelper.getAudiobookCoverUrl(book.id, book.metadata?.audiobookCoverUpdatedOn); as coverUrl) {
<p-image
[src]="coverUrl"
alt="Audiobook Cover"
width="200"
appendTo="body"
lazyLoad
[preview]="true"
class="square-cover">
</p-image>
} @else {
<app-cover-placeholder style="width: 200px; height: 200px;" [title]="book.metadata?.title ?? ''" [author]="(book.metadata?.authors ?? []).join(', ')" size="lg" />
}
<app-cover
class="square-cover"
style="width: 200px; height: 200px;"
[src]="urlHelper.getAudiobookCoverUrl(book.id, book.metadata?.audiobookCoverUpdatedOn)"
[title]="book.metadata?.title"
[authors]="book.metadata?.authors ?? []"
size="lg"
[preview]="true"
[alt]="t('audiobookCover')" />
@if (isUploading) {
<p-progressSpinner class="upload-spinner"></p-progressSpinner>
}
@@ -6,14 +6,6 @@
}
}
::ng-deep .cover-item p-image {
width: 150px;
}
::ng-deep p-image img {
margin: 0 auto;
}
::ng-deep .p-autocomplete .p-chip .p-chip-label {
font-size: 12px;
}
@@ -142,12 +134,8 @@ label {
position: relative;
flex-shrink: 0;
&.audiobook-cover-section {
::ng-deep .square-cover img {
aspect-ratio: 1;
object-fit: cover;
border-radius: 0.4375rem;
}
.square-cover {
border-radius: 0.4375rem;
}
}
@@ -7,7 +7,7 @@ import {Observable, sample} from "rxjs";
import {MessageService} from "primeng/api";
import {Book, BookMetadata, ComicMetadata, MetadataClearFlags, MetadataUpdateWrapper,} from "../../../../book/model/book.model";
import {UrlHelperService} from "../../../../../shared/service/url-helper.service";
import {CoverPlaceholderComponent} from "../../../../../shared/components/cover-generator/cover-generator.component";
import {CoverComponent} from "../../../../../shared/components/cover/cover.component";
import {ALL_COMIC_METADATA_FIELDS, AUDIOBOOK_METADATA_FIELDS, COMIC_FORM_TO_MODEL_LOCK, COMIC_TEXT_METADATA_FIELDS, COMIC_ARRAY_METADATA_FIELDS, COMIC_TEXTAREA_METADATA_FIELDS, isFieldEmbeddable, hasMetadataWriter} from '../../../../../shared/metadata';
import {FileUpload, FileUploadErrorEvent, FileUploadEvent,} from "primeng/fileupload";
import {HttpResponse} from "@angular/common/http";
@@ -21,8 +21,6 @@ import {MetadataRefreshType} from "../../../model/request/metadata-refresh-type.
import {AutoComplete, AutoCompleteSelectEvent} from "primeng/autocomplete";
import {DatePicker} from "primeng/datepicker";
import {Textarea} from "primeng/textarea";
import {Image} from "primeng/image";
import {LazyLoadImageModule} from "ng-lazyload-image";
import {Select} from "primeng/select";
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
import {BookDialogHelperService} from "../../../../book/components/book-browser/book-dialog-helper.service";
@@ -52,13 +50,11 @@ import {CdkDragDrop, CdkDropList, CdkDrag, moveItemInArray} from '@angular/cdk/d
AutoComplete,
DatePicker,
Textarea,
Image,
LazyLoadImageModule,
Select,
TranslocoDirective,
CdkDropList,
CdkDrag,
CoverPlaceholderComponent,
CoverComponent,
],
})
export class MetadataEditorComponent implements OnInit {
@@ -53,34 +53,28 @@
<div class="cover-label">
<i class="pi pi-book"></i> {{ t('ebookCover') }}
</div>
@if (urlHelper.getCoverUrl(currentBook.id, currentBook.metadata?.coverUpdatedOn); as coverUrl) {
<p-image
[src]="coverUrl"
[alt]="t('ebookCover')"
width="200"
appendTo="body"
[preview]="true">
</p-image>
} @else {
<app-cover-placeholder style="width: 200px; height: 280px;" [title]="currentBook.metadata?.title ?? ''" [author]="(currentBook.metadata?.authors ?? []).join(', ')" size="lg" />
}
<app-cover
style="width: 200px; height: 280px;"
[src]="urlHelper.getCoverUrl(currentBook.id, currentBook.metadata?.coverUpdatedOn)"
[title]="currentBook.metadata?.title"
[authors]="currentBook.metadata?.authors ?? []"
size="lg"
[preview]="true"
[alt]="t('ebookCover')" />
</div>
<div class="cover-item">
<div class="cover-label audiobook">
<i class="pi pi-headphones"></i> {{ t('audiobookCover') }}
</div>
@if (urlHelper.getAudiobookCoverUrl(currentBook.id, currentBook.metadata?.audiobookCoverUpdatedOn); as coverUrl) {
<p-image
[src]="coverUrl"
[alt]="t('audiobookCover')"
width="200"
appendTo="body"
[preview]="true"
class="square-cover">
</p-image>
} @else {
<app-cover-placeholder style="width: 200px; height: 200px;" [title]="currentBook.metadata?.title ?? ''" [author]="(currentBook.metadata?.authors ?? []).join(', ')" size="lg" />
}
<app-cover
class="square-cover"
style="width: 200px; height: 200px;"
[src]="urlHelper.getAudiobookCoverUrl(currentBook.id, currentBook.metadata?.audiobookCoverUpdatedOn)"
[title]="currentBook.metadata?.title"
[authors]="currentBook.metadata?.authors ?? []"
size="lg"
[preview]="true"
[alt]="t('audiobookCover')" />
</div>
</div>
</div>
@@ -361,9 +361,7 @@
align-items: center;
gap: 0.6563rem;
::ng-deep .square-cover img {
aspect-ratio: 1;
object-fit: cover;
.square-cover {
border-radius: 0.4375rem;
}
}
@@ -10,9 +10,8 @@ import {BookNotesComponent} from '../../../../../book/components/book-notes/book
import {BookReadingSessionsComponent} from '../../book-reading-sessions/book-reading-sessions.component';
import {Button} from 'primeng/button';
import {Tooltip} from 'primeng/tooltip';
import {Image} from 'primeng/image';
import {UrlHelperService} from '../../../../../../shared/service/url-helper.service';
import {CoverPlaceholderComponent} from '../../../../../../shared/components/cover-generator/cover-generator.component';
import {CoverComponent} from '../../../../../../shared/components/cover/cover.component';
import {BookMetadataManageService} from '../../../../../book/service/book-metadata-manage.service';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {AudiobookService} from '../../../../../readers/audiobook-player/audiobook.service';
@@ -85,9 +84,8 @@ const metadataTab = (value: MetadataTabValue, icon: string, labelKey: string): M
Button,
Tooltip,
UpperCasePipe,
Image,
TranslocoDirective,
CoverPlaceholderComponent
CoverComponent
],
templateUrl: './metadata-tabs.component.html',
styleUrl: './metadata-tabs.component.scss'
@@ -5,17 +5,14 @@
<div class="cover-section">
<div class="cover-wrapper">
@if (getBookCoverUrl(book); as coverUrl) {
<p-image
[src]="coverUrl"
[alt]="book.metadata?.title ? ('Cover of ' + book.metadata?.title) : ''"
width="250"
appendTo="body"
[preview]="true">
</p-image>
} @else {
<app-cover-placeholder style="width: 250px; height: 350px;" [title]="book.metadata?.title ?? ''" [author]="(book.metadata?.authors ?? []).join(', ')" size="lg" />
}
<app-cover
[src]="getBookCoverUrl(book)"
[title]="book.metadata?.title"
[authors]="book.metadata?.authors ?? []"
[natural]="true"
[alt]="book.metadata?.title ?? ''"
[preview]="true"
size="lg" />
@if (book?.metadata!.seriesNumber !== null && book?.metadata!.seriesNumber !== undefined) {
<div class="series-badge">
@@ -65,11 +65,7 @@
}
.cover-progress-bar-container {
position: absolute;
bottom: 0;
left: 0;
right: 0;
z-index: 2;
margin-top: 0.4375rem;
border-radius: 9999px;
overflow: hidden;
display: flex;
@@ -78,6 +74,8 @@
}
.cover-progress-bar {
--p-progressbar-background: var(--color-surface-300);
z-index: 2;
pointer-events: none;
height: 6px;
@@ -7,7 +7,7 @@ import {Rating, RatingRateEvent} from 'primeng/rating';
import {FormsModule} from '@angular/forms';
import {Book, BookFile, BookMetadata, BookRecommendation, BookType, ComicMetadata, FileInfo, ReadStatus} from '../../../../book/model/book.model';
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
import {CoverPlaceholderComponent} from '../../../../../shared/components/cover-generator/cover-generator.component';
import {CoverComponent} from '../../../../../shared/components/cover/cover.component';
import {UserService} from '../../../../settings/user-management/user.service';
import {SplitButton} from 'primeng/splitbutton';
import {ConfirmationService, MenuItem, MessageService} from 'primeng/api';
@@ -25,7 +25,6 @@ import {ResetProgressType, ResetProgressTypes} from '../../../../../shared/const
import {DatePicker} from 'primeng/datepicker';
import {ProgressSpinner} from 'primeng/progressspinner';
import {TieredMenu} from 'primeng/tieredmenu';
import {Image} from 'primeng/image';
import {BookDialogHelperService} from '../../../../book/components/book-browser/book-dialog-helper.service';
import {LibraryService} from '../../../../book/service/library.service';
import {TagColor, TagComponent} from '../../../../../shared/components/tag/tag.component';
@@ -47,7 +46,7 @@ import DOMPurify from 'dompurify';
standalone: true,
templateUrl: './metadata-viewer.component.html',
styleUrl: './metadata-viewer.component.scss',
imports: [Button, Rating, FormsModule, SplitButton, NgClass, Tooltip, DecimalPipe, ProgressBar, Menu, DatePicker, ProgressSpinner, TieredMenu, Image, TagComponent, MetadataTabsComponent, TranslocoDirective, TranslocoPipe, Dialog, Checkbox, CoverPlaceholderComponent]
imports: [Button, Rating, FormsModule, SplitButton, NgClass, Tooltip, DecimalPipe, ProgressBar, Menu, DatePicker, ProgressSpinner, TieredMenu, TagComponent, MetadataTabsComponent, TranslocoDirective, TranslocoPipe, Dialog, Checkbox, CoverComponent]
})
export class MetadataViewerComponent implements OnInit, AfterViewChecked {
private bookService = inject(BookService);
@@ -429,7 +428,6 @@ export class MetadataViewerComponent implements OnInit, AfterViewChecked {
get bookInSeries(): Book[] {
return this.bookInSeriesSignal();
}
@ViewChild(Image) private coverImage?: Image;
@ViewChild('descriptionContent') descriptionContentRef?: ElementRef<HTMLElement>;
isExpanded = false;
isOverflowing = false;
@@ -472,12 +470,6 @@ export class MetadataViewerComponent implements OnInit, AfterViewChecked {
});
ngOnInit(): void {
this.destroyRef.onDestroy(() => this.coverImage?.closePreview());
const onPopState = () => this.coverImage?.closePreview();
window.addEventListener('popstate', onPopState);
this.destroyRef.onDestroy(() => window.removeEventListener('popstate', onPopState));
const user = this.userService.currentUser();
if (user) {
this.metadataCenterViewMode = user.userSettings.metadataCenterViewMode ?? 'route';
@@ -138,11 +138,12 @@
<div class="settings-card book-group-card">
<!-- Book Header -->
<div class="book-group-header" role="button" tabindex="0" (click)="toggleGroup(group.bookId)" (keydown.enter)="toggleGroup(group.bookId)">
@if (group.thumbnailUrl) {
<img [src]="group.thumbnailUrl" [alt]="group.bookTitle" class="book-thumbnail" />
} @else {
<app-cover-placeholder class="book-thumbnail" [title]="group.bookTitle" size="sm" />
}
<app-cover
class="book-thumbnail"
aria-hidden="true"
[src]="group.thumbnailUrl"
[title]="group.bookTitle"
size="sm" />
<div class="book-info">
<span class="book-title">{{ group.bookTitle }}</span>
<span class="book-entry-count">
@@ -205,7 +205,6 @@
.book-thumbnail {
width: 36px;
height: 50px;
object-fit: cover;
border-radius: 4px;
flex-shrink: 0;
border: 1px solid var(--p-content-border-color);
@@ -12,7 +12,7 @@ import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {NotebookService} from '../../service/notebook.service';
import {NotebookEntry, NotebookPage} from '../../model/notebook.model';
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
import {CoverPlaceholderComponent} from '../../../../shared/components/cover-generator/cover-generator.component';
import {CoverComponent} from '../../../../shared/components/cover/cover.component';
import {PageTitleService} from '../../../../shared/service/page-title.service';
import {DatePipe} from '@angular/common';
@@ -45,7 +45,7 @@ const EMPTY_PAGE: NotebookPage = {
Tooltip,
Paginator,
TranslocoDirective,
CoverPlaceholderComponent,
CoverComponent,
],
templateUrl: './notebook.component.html',
styleUrls: ['./notebook.component.scss'],
@@ -2,15 +2,13 @@
<div class="sidebar-overlay" role="button" tabindex="0" (click)="onOverlayClick()" (keydown.enter)="onOverlayClick()" [class.closing]="closing()">
<aside class="sidebar" role="button" tabindex="0" (click)="$event.stopPropagation()" (keydown.enter)="$event.stopPropagation()" [class.closing]="closing()">
<header class="sidebar-header">
@if (bookInfo().coverUrl) {
<img
[src]="bookInfo().coverUrl"
alt="Book cover"
class="book-cover"
/>
} @else {
<app-cover-placeholder class="book-cover" [title]="bookInfo().title" [author]="bookInfo().authors" size="sm" />
}
<app-cover
class="book-cover"
aria-hidden="true"
[src]="bookInfo().coverUrl"
[title]="bookInfo().title"
[authors]="bookInfo().authors"
size="sm" />
<div class="book-meta">
<h2 class="book-title">{{ bookInfo().title }}</h2>
@if (bookInfo().authors) {
@@ -48,7 +48,6 @@ $sidebar-width: 300px;
.book-cover {
width: 60px;
height: 90px;
object-fit: cover;
border-radius: 4px;
box-shadow: 0 4px 12px rgb(0 0 0 / 30%);
flex-shrink: 0;
@@ -5,14 +5,14 @@ import {TranslocoPipe} from '@jsverse/transloco';
import {CbxSidebarService, CbxSidebarTab} from './cbx-sidebar.service';
import {BookNoteV2} from '../../../../../shared/service/book-note-v2.service';
import {ReaderIconComponent} from '../../../ebook-reader';
import {CoverPlaceholderComponent} from '../../../../../shared/components/cover-generator/cover-generator.component';
import {CoverComponent} from '../../../../../shared/components/cover/cover.component';
@Component({
selector: 'app-cbx-sidebar',
standalone: true,
templateUrl: './cbx-sidebar.component.html',
styleUrls: ['./cbx-sidebar.component.scss'],
imports: [FormsModule, TranslocoPipe, ReaderIconComponent, DatePipe, CoverPlaceholderComponent]
imports: [FormsModule, TranslocoPipe, ReaderIconComponent, DatePipe, CoverComponent]
})
export class CbxSidebarComponent {
private readonly sidebarService = inject(CbxSidebarService);
@@ -9,11 +9,12 @@
<div class="dialog-body">
<div class="metadata-container">
<div class="cover-section">
@if (bookCoverUrl) {
<img [src]="bookCoverUrl" [alt]="metadata?.title || t('unknown')" class="book-cover">
} @else {
<app-cover-placeholder class="cover-placeholder" [title]="metadata?.title ?? ''" [author]="(metadata?.authors ?? []).join(', ')" />
}
<app-cover
class="book-cover"
[src]="bookCoverUrl"
[title]="metadata?.title"
[authors]="metadata?.authors ?? []"
[alt]="metadata?.title || t('unknown')" />
</div>
<div class="metadata-section">
@@ -131,29 +131,12 @@
border-radius: 8px;
box-shadow: 0 8px 24px rgb(0 0 0 / 40%);
max-height: 300px;
object-fit: cover;
@media (width <= 768px) {
max-height: 240px;
}
}
.cover-placeholder {
width: 100%;
aspect-ratio: 2/3;
background: linear-gradient(135deg, color-mix(in srgb, var(--color-white) 4%, transparent) 0%, color-mix(in srgb, var(--color-white) 1%, transparent) 100%);
border: 2px dashed color-mix(in srgb, var(--color-white) 12%, transparent);
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
@media (width <= 768px) {
max-height: 240px;
}
}
.metadata-section {
flex: 1;
display: flex;
@@ -2,12 +2,12 @@ import {Component, EventEmitter, inject, Input, Output} from '@angular/core';
import {TranslocoDirective, TranslocoService} from '@jsverse/transloco';
import {Book} from '../../../book/model/book.model';
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
import {CoverPlaceholderComponent} from '../../../../shared/components/cover-generator/cover-generator.component';
import {CoverComponent} from '../../../../shared/components/cover/cover.component';
@Component({
selector: 'app-reader-book-metadata-dialog',
standalone: true,
imports: [TranslocoDirective, CoverPlaceholderComponent],
imports: [TranslocoDirective, CoverComponent],
templateUrl: './metadata-dialog.component.html',
styleUrls: ['./metadata-dialog.component.scss']
})
@@ -4,27 +4,17 @@
<aside class="sidebar" role="button" tabindex="0" (click)="$event.stopPropagation()" (keydown.enter)="$event.stopPropagation()" [class.closing]="closing()">
<!-- Header with book info -->
<header class="sidebar-header">
@if (bookInfo().coverUrl) {
<img
[src]="bookInfo().coverUrl"
[alt]="t('bookCoverAlt')"
class="book-cover"
(click)="onCoverClick()"
role="button"
tabindex="0"
(keydown.enter)="onCoverClick()"
/>
} @else {
<app-cover-placeholder
class="book-cover"
[title]="bookInfo().title"
[author]="bookInfo().authors"
size="sm"
role="button"
tabindex="0"
(click)="onCoverClick()"
(keydown.enter)="onCoverClick()" />
}
<app-cover
class="book-cover"
[src]="bookInfo().coverUrl"
[title]="bookInfo().title"
[authors]="bookInfo().authors"
size="sm"
[alt]="bookInfo().title || t('bookCoverAlt')"
role="button"
tabindex="0"
(click)="onCoverClick()"
(keydown.enter)="onCoverClick()" />
<div class="book-meta">
<h2 class="book-title">{{ bookInfo().title }}</h2>
@if (bookInfo().authors) {
@@ -48,7 +48,6 @@ $sidebar-width: 300px;
.book-cover {
width: 60px;
height: 90px;
object-fit: cover;
border-radius: 4px;
box-shadow: 0 4px 12px rgb(0 0 0 / 30%);
flex-shrink: 0;
@@ -4,7 +4,7 @@ import {TranslocoDirective} from '@jsverse/transloco';
import {TocItem} from 'epubjs';
import {ReaderSidebarService, SidebarTab} from './sidebar.service';
import {ReaderIconComponent} from '../../shared/icon.component';
import {CoverPlaceholderComponent} from '../../../../../shared/components/cover-generator/cover-generator.component';
import {CoverComponent} from '../../../../../shared/components/cover/cover.component';
import {DatePipe, NgTemplateOutlet} from '@angular/common';
@Component({
@@ -13,7 +13,7 @@ import {DatePipe, NgTemplateOutlet} from '@angular/common';
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.scss'],
imports: [
DatePipe, NgTemplateOutlet, FormsModule, TranslocoDirective, ReaderIconComponent, CoverPlaceholderComponent]
DatePipe, NgTemplateOutlet, FormsModule, TranslocoDirective, ReaderIconComponent, CoverComponent]
})
export class ReaderSidebarComponent {
private readonly sidebarService = inject(ReaderSidebarService);
@@ -1,22 +1,15 @@
<div class="series-card" role="button" tabindex="0" (click)="onCardClick($event)" (keydown.enter)="onCardClick($event)">
<div class="stacked-covers" [ngClass]="'covers-' + series.coverBooks.length">
@for (book of series.coverBooks; track book.id; let i = $index) {
@if (getCoverUrl(i); as coverUrl) {
<img
[src]="coverUrl"
class="cover-img"
[ngClass]="'cover-' + i"
[alt]="series.seriesName"
loading="lazy"
decoding="async"/>
} @else {
<app-cover-placeholder
class="cover-img"
[ngClass]="'cover-' + i"
[title]="book.metadata?.title ?? ''"
[author]="(book.metadata?.authors ?? []).join(', ')"
size="sm" />
}
<app-cover
class="cover-img"
aria-hidden="true"
[ngClass]="'cover-' + i"
[src]="getCoverUrl(i)"
[title]="book.metadata?.title"
[authors]="book.metadata?.authors ?? []"
size="sm"
loading="lazy" />
}
</div>
@@ -40,7 +40,6 @@
position: absolute;
width: calc(105px * var(--card-scale, 1));
height: calc(152px * var(--card-scale, 1));
object-fit: cover;
border-radius: 4px;
box-shadow: 0 4px 12px rgb(0 0 0 / 40%);
transition: transform 0.3s ease, width 0.2s ease, height 0.2s ease;
@@ -7,7 +7,7 @@ import {TranslocoPipe} from '@jsverse/transloco';
import {SeriesSummary} from '../../model/series.model';
import {BookService} from '../../../book/service/book.service';
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
import {CoverPlaceholderComponent} from '../../../../shared/components/cover-generator/cover-generator.component';
import {CoverComponent} from '../../../../shared/components/cover/cover.component';
@Component({
selector: 'app-series-card',
@@ -15,7 +15,7 @@ import {CoverPlaceholderComponent} from '../../../../shared/components/cover-gen
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './series-card.component.html',
styleUrls: ['./series-card.component.scss'],
imports: [NgClass, ProgressBar, Button, Tooltip, TranslocoPipe, CoverPlaceholderComponent]
imports: [NgClass, ProgressBar, Button, Tooltip, TranslocoPipe, CoverComponent]
})
export class SeriesCardComponent {
@@ -1,67 +0,0 @@
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
import {CoverPlaceholderComponent, coverColorFor} from './cover-generator.component';
describe('CoverPlaceholderComponent', () => {
let fixture: ComponentFixture<CoverPlaceholderComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [CoverPlaceholderComponent],
}).compileComponents();
fixture = TestBed.createComponent(CoverPlaceholderComponent);
});
afterEach(() => {
TestBed.resetTestingModule();
});
it('renders the title and author text', () => {
fixture.componentRef.setInput('title', 'Dune');
fixture.componentRef.setInput('author', 'Frank Herbert');
fixture.detectChanges();
const el: HTMLElement = fixture.nativeElement;
expect(el.textContent).toContain('Dune');
expect(el.textContent).toContain('Frank Herbert');
});
it('applies the computed background color', () => {
fixture.componentRef.setInput('title', 'Dune');
fixture.componentRef.setInput('author', 'Frank Herbert');
fixture.detectChanges();
const container = fixture.nativeElement.querySelector('.placeholder');
expect(container.style.background).toBeTruthy();
});
it('applies the correct size class', () => {
fixture.componentRef.setInput('title', 'Test');
fixture.componentRef.setInput('size', 'lg');
fixture.detectChanges();
const container = fixture.nativeElement.querySelector('.placeholder');
expect(container.classList.contains('size-lg')).toBe(true);
});
});
describe('coverColorFor', () => {
it('returns a deterministic color for the same inputs', () => {
const first = coverColorFor('Dune', 'Frank Herbert');
const second = coverColorFor('Dune', 'Frank Herbert');
expect(first).toBe(second);
});
it('returns different colors for different inputs', () => {
const a = coverColorFor('Dune', 'Frank Herbert');
const b = coverColorFor('Project Hail Mary', 'Andy Weir');
expect(a).not.toBe(b);
});
it('returns a valid hex color', () => {
const color = coverColorFor('Test', 'Author');
expect(color).toMatch(/^#[0-9A-Fa-f]{6}$/);
});
});
@@ -1,112 +0,0 @@
import {ChangeDetectionStrategy, Component, computed, input} from '@angular/core';
const COVER_COLORS = [
'#1a1a2e', '#2d3436', '#0c3547', '#1e3d59', '#2c2c54', '#1b262c',
'#2B2D42', '#3D405B', '#463F3A', '#1B2838', '#2E4057', '#4A3728',
];
function hashString(str: string): number {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash = hash & hash;
}
return Math.abs(hash);
}
export function coverColorFor(title: string, author: string): string {
return COVER_COLORS[hashString(title + author) % COVER_COLORS.length];
}
export type CoverPlaceholderSize = 'sm' | 'md' | 'lg';
@Component({
selector: 'app-cover-placeholder',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div
class="placeholder"
[class.size-sm]="size() === 'sm'"
[class.size-md]="size() === 'md'"
[class.size-lg]="size() === 'lg'"
[style.background]="color()"
>
<div class="placeholder-title">{{ title() }}</div>
<div class="placeholder-author">{{ author() }}</div>
</div>
`,
styles: [`
:host {
display: block;
width: 100%;
height: 100%;
container-type: inline-size;
}
.placeholder {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
border-radius: inherit;
overflow: hidden;
}
.placeholder.size-sm { padding: min(0.4375rem, 4cqi); }
.placeholder.size-md { padding: min(0.875rem, 6cqi); }
.placeholder.size-lg { padding: min(1.3125rem, 8cqi); }
.placeholder-title {
color: rgba(255, 255, 255, 0.9);
font-weight: 600;
line-height: 1.375;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
word-break: break-word;
max-width: 100%;
}
.size-sm .placeholder-title {
font-size: min(11px, 10cqi);
margin-bottom: 2px;
}
.size-md .placeholder-title {
font-size: min(13px, 10cqi);
margin-bottom: 4px;
}
.size-lg .placeholder-title {
font-size: min(15px, 10cqi);
margin-bottom: 8px;
}
.placeholder-author {
color: rgba(255, 255, 255, 0.5);
letter-spacing: 0.025em;
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
overflow: hidden;
word-break: break-word;
max-width: 100%;
}
.size-sm .placeholder-author { font-size: min(9px, 8cqi); }
.size-md .placeholder-author { font-size: min(11px, 8cqi); }
.size-lg .placeholder-author { font-size: min(12px, 8cqi); }
`]
})
export class CoverPlaceholderComponent {
title = input('');
author = input('');
size = input<CoverPlaceholderSize>('md');
protected color = computed(() => coverColorFor(this.title(), this.author()));
}
@@ -0,0 +1,34 @@
@if (showImage() && preview()) {
<p-image
styleClass="block h-full w-full"
[imageClass]="imageClass()"
[src]="src() ?? ''"
[alt]="alt()"
[loading]="loading()"
appendTo="body"
[preview]="true"
(onImageError)="onError()"
/>
} @else if (showImage()) {
<img
[class]="imageClass()"
[src]="src() ?? ''"
[alt]="alt()"
[attr.loading]="loading()"
decoding="async"
(error)="onError()"
/>
} @else {
<div
class="placeholder group flex aspect-[5/7] h-full w-full flex-col items-center justify-center gap-1 overflow-hidden rounded-[inherit] p-1 text-center data-[size=md]:p-2 data-[size=lg]:gap-2 data-[size=lg]:p-4"
[attr.data-size]="size()"
[style.background]="color()"
>
<div class="placeholder-title line-clamp-3 max-w-full overflow-hidden break-words text-xs font-semibold leading-snug text-white/90 group-data-[size=md]:text-sm group-data-[size=lg]:text-base">
{{ title() }}
</div>
<div class="placeholder-author line-clamp-1 max-w-full overflow-hidden break-words text-xs text-white/55 group-data-[size=lg]:text-sm">
{{ authorsLabel() }}
</div>
</div>
}
@@ -0,0 +1,81 @@
import {ChangeDetectionStrategy, Component, computed, DestroyRef, inject, input, signal, viewChild} from '@angular/core';
import {Image} from 'primeng/image';
const COVER_COLORS = [
'#1a1a2e', '#2d3436', '#0c3547', '#1e3d59', '#2c2c54', '#1b262c',
'#2B2D42', '#3D405B', '#463F3A', '#1B2838', '#2E4057', '#4A3728',
];
function hashString(str: string): number {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = 31 * hash + str.charCodeAt(i);
hash |= 0;
}
return hash;
}
function coverColorFor(title: string, author: string): string {
return COVER_COLORS[Math.abs(hashString(title + author) % COVER_COLORS.length)];
}
type CoverSize = 'sm' | 'md' | 'lg';
type CoverFit = 'cover' | 'contain';
type CoverAuthors = string | string[];
@Component({
selector: 'app-cover',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [Image],
templateUrl: './cover.component.html',
host: {
class: 'block w-full',
'[class.h-full]': '!natural()',
'[class.h-auto]': 'natural()',
'(window:popstate)': 'closePreview()',
},
})
export class CoverComponent {
readonly src = input<string | null | undefined>(null);
readonly title = input<string | null | undefined>('');
readonly authors = input<CoverAuthors | null | undefined>([]);
readonly size = input<CoverSize>('md');
readonly fit = input<CoverFit>('cover');
readonly loading = input<'eager' | 'lazy'>('eager');
readonly alt = input('');
readonly natural = input(false);
readonly preview = input(false);
private readonly previewImage = viewChild(Image);
private readonly failedSrc = signal<string | null | undefined>(null);
protected readonly authorsLabel = computed(() => {
const authors = this.authors();
return Array.isArray(authors) ? authors.join(', ') : authors ?? '';
});
protected readonly color = computed(() => coverColorFor(this.title() ?? '', this.authorsLabel()));
protected readonly imageClass = computed(() => [
'cover-img block w-full rounded-[inherit]',
this.natural() ? 'h-auto' : 'h-full',
this.fit() === 'cover' ? 'object-cover' : 'object-contain',
].join(' '));
protected readonly showImage = computed(() => !!this.src() && this.failedSrc() !== this.src());
constructor() {
inject(DestroyRef).onDestroy(() => this.closePreview());
}
protected closePreview(): void {
if (!this.preview()) {
return;
}
this.previewImage()?.closePreview();
}
protected onError(): void {
this.failedSrc.set(this.src());
}
}