Introduce a new eBook reader with support for EPUB, MOBI, AZW3, and FB2 formats (#2258)

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-01-15 20:39:52 -07:00
committed by GitHub
co-authored by acx10
parent 775887b55f
commit 8c35f2415c
107 changed files with 13351 additions and 1733 deletions
@@ -124,6 +124,16 @@
{{ coverScalePreferenceService.scaleFactor.toFixed(2) }}x
</div>
</div>
<!-- Book type pill toggle control -->
<div class="flex flex-col gap-2">
<label for="show-book-type-pill-checkbox" class="font-medium">Show book type pill</label>
<p-checkbox
inputId="show-book-type-pill-checkbox"
[binary]="true"
[ngModel]="bookCardOverlayPreferenceService.showBookTypePill"
(onChange)="bookCardOverlayPreferenceService.setShowBookTypePill($event.checked)">
</p-checkbox>
</div>
</div>
</p-popover>
</div>
@@ -273,7 +283,8 @@
[onBookSelect]="handleBookSelect.bind(this)"
[isSeriesCollapsed]="seriesCollapseFilter.isSeriesCollapsed"
(checkboxClick)="onCheckboxClicked($event)"
[isSelected]="selectedBooks.has(book.id)">
[isSelected]="selectedBooks.has(book.id)"
[overlayPreferenceService]="bookCardOverlayPreferenceService">
</app-book-card>
</div>
}
@@ -51,6 +51,7 @@ import {TaskHelperService} from '../../../settings/task-management/task-helper.s
import {FilterLabelHelper} from './filter-label.helper';
import {LoadingService} from '../../../../core/services/loading.service';
import {BookNavigationService} from '../../service/book-navigation.service';
import {BookCardOverlayPreferenceService} from './book-card-overlay-preference.service';
export enum EntityType {
LIBRARY = 'Library',
@@ -123,6 +124,7 @@ export class BookBrowserComponent implements OnInit, AfterViewInit {
private pageTitle = inject(PageTitleService);
private loadingService = inject(LoadingService);
private bookNavigationService = inject(BookNavigationService);
protected bookCardOverlayPreferenceService = inject(BookCardOverlayPreferenceService);
bookState$: Observable<BookState> | undefined;
entity$: Observable<Library | Shelf | MagicShelf | null> | undefined;
@@ -0,0 +1,126 @@
import {inject, Injectable} from '@angular/core';
import {BehaviorSubject, Subject} from 'rxjs';
import {debounceTime, filter, takeUntil} from 'rxjs/operators';
import {UserService} from '../../../settings/user-management/user.service';
@Injectable({
providedIn: 'root'
})
export class BookCardOverlayPreferenceService {
private readonly userService = inject(UserService);
private readonly _showBookTypePill = new BehaviorSubject<boolean>(true);
readonly showBookTypePill$ = this._showBookTypePill.asObservable();
private destroy$ = new Subject<void>();
private hasUserToggled = false;
private currentContext: { type: 'LIBRARY' | 'SHELF' | 'MAGIC_SHELF', id: number } | null = null;
constructor() {
this.userService.userState$
.pipe(
filter(userState => !!userState?.user && userState.loaded),
takeUntil(this.destroy$)
)
.subscribe(() => {
this.loadPreferencesFromUser();
});
this.showBookTypePill$
.pipe(debounceTime(500))
.subscribe(show => {
if (this.hasUserToggled) {
this.persistPreference(show);
}
});
}
setShowBookTypePill(show: boolean): void {
this.hasUserToggled = true;
this._showBookTypePill.next(show);
}
get showBookTypePill(): boolean {
return this._showBookTypePill.value;
}
private loadPreferencesFromUser(): void {
const user = this.userService.getCurrentUser();
const prefs = user?.userSettings?.entityViewPreferences;
let show = true;
if (prefs) {
const globalAny = prefs.global as any;
show = prefs.global?.overlayBookType ?? globalAny?.showBookTypePill ?? true;
if (this.currentContext) {
const override = prefs.overrides?.find(o =>
o.entityType === this.currentContext?.type && o.entityId === this.currentContext?.id
);
if (override) {
const prefAny = override.preferences as any;
if (override.preferences.overlayBookType !== undefined) {
show = override.preferences.overlayBookType;
} else if (prefAny?.showBookTypePill !== undefined) {
show = prefAny.showBookTypePill;
}
}
}
}
this.hasUserToggled = false;
if (this._showBookTypePill.value !== show) {
this._showBookTypePill.next(show);
}
}
private persistPreference(show: boolean): void {
const user = this.userService.getCurrentUser();
if (!user) return;
const prefs = structuredClone(user.userSettings.entityViewPreferences ?? {
global: {
sortKey: 'addedOn',
sortDir: 'DESC',
view: 'GRID',
coverSize: 1.0,
seriesCollapsed: false,
overlayBookType: true
},
overrides: []
});
if (!prefs.overrides) {
prefs.overrides = [];
}
if (this.currentContext) {
let override = prefs.overrides.find(o =>
o.entityType === this.currentContext?.type && o.entityId === this.currentContext?.id
);
if (!override) {
override = {
entityType: this.currentContext.type,
entityId: this.currentContext.id,
preferences: {
...prefs.global,
overlayBookType: show
}
};
prefs.overrides.push(override);
} else {
override.preferences.overlayBookType = show;
}
} else {
prefs.global.overlayBookType = show;
}
this.userService.updateUserSetting(user.id, 'entityViewPreferences', prefs);
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
}
@@ -12,17 +12,23 @@
decoding="async"
(load)="onImageLoad()"/>
@if (!book.seriesCount && book.metadata?.seriesNumber != null) {
<div class="series-number-overlay">
#{{ book.metadata?.seriesNumber }}
</div>
}
@if (book.seriesCount && book.seriesCount >= 1) {
<div class="series-items-count-overlay" [pTooltip]="seriesCountTooltip" tooltipPosition="right">
<i class="pi pi-book" style="font-size: 0.65rem; margin-right: 2px;"></i>{{ book.seriesCount }}
</div>
}
<div class="top-left-overlay-stack">
@if (showBookTypePill && book.bookType) {
<div class="book-type-pill-overlay" [ngClass]="'book-type-' + book.bookType.toLowerCase()">
{{ book.bookType }}
</div>
}
@if (!book.seriesCount && book.metadata?.seriesNumber != null) {
<div class="series-number-overlay">
#{{ book.metadata?.seriesNumber }}
</div>
}
@if (book.seriesCount && book.seriesCount >= 1) {
<div class="series-items-count-overlay">
<i class="pi pi-book series-items-count-icon"></i>{{ book.seriesCount }}
</div>
}
</div>
@if (_isSeriesViewActive) {
<p-button [rounded]="true" icon="pi pi-info" class="info-btn" (click)="openSeriesInfo()"></p-button>
@@ -30,7 +36,7 @@
<p-button [rounded]="true" icon="pi pi-info" class="info-btn" (click)="openBookInfo(book)"></p-button>
}
@if (!_isSeriesViewActive && _canReadBook) {
@if (!_isSeriesViewActive) {
<p-button [rounded]="true" icon="pi pi-book" class="read-btn" (click)="readBook(book)"></p-button>
}
@@ -21,10 +21,6 @@
justify-content: center;
}
.cover-container.loaded {
background-color: transparent;
}
.book-cover {
width: 100%;
height: 100%;
@@ -157,13 +153,11 @@
.series-items-count-overlay {
position: absolute;
top: 8px;
left: 8px;
background-color: var(--primary-color);
color: var(--primary-text-color-dark);
font-size: 0.75rem;
padding: 3px 8px;
border-radius: 4px;
font-size: 0.7rem;
padding: 0 5px;
border-radius: 6px;
z-index: 3;
white-space: nowrap;
user-select: none;
@@ -176,6 +170,76 @@
gap: 2px;
}
.series-items-count-icon {
font-size: 0.6rem;
margin-right: 2px;
}
.book-type-pill-overlay {
position: absolute;
background: var(--primary-color, #6366f1);
color: var(--primary-text-color-dark, #fff);
font-size: 0.675rem;
font-weight: 700;
padding: 1px 6px;
border-radius: 6px;
z-index: 3;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.25);
letter-spacing: 0.03em;
user-select: none;
pointer-events: none;
text-transform: uppercase;
transition: background 0.2s;
}
.top-left-overlay-stack {
position: absolute;
top: 7px;
left: 7px;
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 4px;
z-index: 4;
}
.book-type-pill-overlay,
.series-number-overlay,
.series-items-count-overlay {
position: static;
margin: 0;
}
.book-type-epub {
background: #16a34a; /* medium green */
color: #fff;
}
.book-type-pdf {
background: #dc2626; /* medium red */
color: #fff;
}
.book-type-cbx {
background: #d97706; /* amber/orange */
color: #fff;
}
.book-type-mobi {
background: #2563eb; /* medium blue */
color: #fff;
}
.book-type-azw3 {
background: #0891b2; /* cyan/teal */
color: #fff;
}
.book-type-fb2 {
background: #7c3aed; /* vibrant purple */
color: #fff;
}
.read-status-indicator {
display: flex;
align-items: center;
@@ -23,6 +23,7 @@ import {ReadStatusHelper} from '../../../helpers/read-status.helper';
import {BookDialogHelperService} from '../book-dialog-helper.service';
import {TaskHelperService} from '../../../../settings/task-management/task-helper.service';
import {BookNavigationService} from '../../../service/book-navigation.service';
import {BookCardOverlayPreferenceService} from '../book-card-overlay-preference.service';
@Component({
selector: 'app-book-card',
@@ -45,6 +46,7 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
@Input() bottomBarHidden: boolean = false;
@Input() seriesViewEnabled: boolean = false;
@Input() isSeriesCollapsed: boolean = false;
@Input() overlayPreferenceService?: BookCardOverlayPreferenceService;
@ViewChild('checkboxElem') checkboxElem!: ElementRef<HTMLInputElement>;
@@ -69,7 +71,6 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
protected _koProgressPercentage: number | null = null;
protected _koboProgressPercentage: number | null = null;
protected _displayTitle: string | undefined = undefined;
protected _canReadBook: boolean = true;
protected _isSeriesViewActive: boolean = false;
protected _coverImageUrl: string = '';
protected _readStatusIcon: string = '';
@@ -86,6 +87,10 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
private user: User | null = null;
private menuInitialized = false;
showBookTypePill = true;
private overlayPrefSub?: any;
ngOnInit(): void {
this.computeAllMemoizedValues();
this.userService.userState$
@@ -98,6 +103,13 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
this.user = userState.user;
this.metadataCenterViewMode = userState.user?.userSettings?.metadataCenterViewMode ?? 'route';
});
if (this.overlayPreferenceService) {
this.overlayPrefSub = this.overlayPreferenceService.showBookTypePill$.subscribe(val => {
this.showBookTypePill = val;
this.cdr.markForCheck();
});
}
}
ngOnChanges(changes: SimpleChanges): void {
@@ -131,7 +143,6 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
this._displayTitle = (this.isSeriesCollapsed && this.book.metadata?.seriesName)
? this.book.metadata?.seriesName
: this.book.metadata?.title;
this._canReadBook = this.book?.bookType !== 'FB2';
this._coverImageUrl = this.urlHelper.getThumbnailUrl(this.book.id, this.book.metadata?.coverUpdatedOn);
this._readStatusIcon = this.readStatusHelper.getReadStatusIcon(this.book.readStatus);
@@ -770,5 +781,8 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy {
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
if (this.overlayPrefSub) {
this.overlayPrefSub.unsubscribe();
}
}
}
@@ -3,7 +3,7 @@ import {CbxBackgroundColor, CbxFitMode, CbxPageSpread, CbxPageViewMode, CbxScrol
import {BookReview} from '../components/book-reviews/book-review-service';
import {ZoomType} from 'ngx-extended-pdf-viewer';
export type BookType = "PDF" | "EPUB" | "CBX" | "FB2";
export type BookType = "PDF" | "EPUB" | "CBX" | "FB2" | "MOBI" | "AZW3";
export enum AdditionalFileType {
ALTERNATIVE_FORMAT = 'ALTERNATIVE_FORMAT',
@@ -48,6 +48,7 @@ export interface Book extends FileInfo {
libraryPath?: { id: number };
alternativeFormats?: AdditionalFile[];
supplementaryFiles?: AdditionalFile[];
[key: string]: unknown;
}
@@ -150,6 +151,7 @@ export interface BookMetadata {
tagsLocked?: boolean;
coverLocked?: boolean;
reviewsLocked?: boolean;
[key: string]: unknown;
}
@@ -210,6 +212,21 @@ export interface EpubViewerSetting {
customFontId?: number | null;
}
export interface EbookViewerSetting {
lineHeight: number;
justify: boolean;
hyphenate: boolean;
maxColumnCount: number;
gap: number;
fontSize: number;
theme: string
maxInlineSize: number;
maxBlockSize: number;
fontFamily: string | null;
isDark: boolean;
flow: 'paginated' | 'scrolled';
}
export interface CbxViewerSetting {
pageSpread: CbxPageSpread;
pageViewMode: CbxPageViewMode;
@@ -221,8 +238,10 @@ export interface CbxViewerSetting {
export interface BookSetting {
pdfSettings?: PdfViewerSetting;
epubSettings?: EpubViewerSetting;
ebookSettings?: EbookViewerSetting;
cbxSettings?: CbxViewerSetting;
newPdfSettings?: NewPdfReaderSetting;
[key: string]: unknown;
}
@@ -1,7 +1,7 @@
import {SortOption} from './sort.model';
export type LibraryScanMode = 'FILE_AS_BOOK' | 'FOLDER_AS_BOOK';
export type BookFileType = 'PDF' | 'EPUB' | 'CBX' | 'FB2';
export type BookFileType = 'PDF' | 'EPUB' | 'CBX' | 'FB2' | 'MOBI' | 'AZW3';
export interface Library {
id?: number;
@@ -68,12 +68,10 @@ describe('BookPatchService', () => {
it('should save EPUB progress', () => {
httpMock.post.mockReturnValue(of(void 0));
service.saveEpubProgress(2, 'cfi123', 0.8).subscribe(result => {
expect(result).toBeUndefined();
expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), {
bookId: 2,
epubProgress: {cfi: 'cfi123', percentage: 0.8}
});
service.saveEpubProgress(2, 'cfi123', 'href123', 0.8);
expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), {
bookId: 2,
epubProgress: {cfi: 'cfi123', href: 'href123', percentage: 0.8}
});
});
@@ -1,7 +1,7 @@
import {inject, Injectable} from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import {Observable} from 'rxjs';
import {tap} from 'rxjs/operators';
import {Observable, Subject} from 'rxjs';
import {distinctUntilChanged, exhaustMap, share, tap} from 'rxjs/operators';
import {Book, ReadStatus} from '../model/book.model';
import {BookStateService} from './book-state.service';
import {API_CONFIG} from '../../../core/config/api-config';
@@ -17,6 +17,33 @@ export class BookPatchService {
private http = inject(HttpClient);
private bookStateService = inject(BookStateService);
private epubProgressSubject = new Subject<{ bookId: number; cfi: string; href: string; percentage: number }>();
private epubProgress$ = this.epubProgressSubject.pipe(
distinctUntilChanged((prev, curr) =>
prev.bookId === curr.bookId &&
prev.cfi === curr.cfi &&
prev.href === curr.href &&
prev.percentage === curr.percentage
),
exhaustMap(payload => {
const body = {
bookId: payload.bookId,
epubProgress: {
cfi: payload.cfi,
href: payload.href,
percentage: payload.percentage
}
};
return this.http.post<void>(`${this.url}/progress`, body);
}),
share()
);
constructor() {
this.epubProgress$.subscribe();
}
updateBookShelves(bookIds: Set<number | undefined>, shelvesToAssign: Set<number | null | undefined>, shelvesToUnassign: Set<number | null | undefined>): Observable<Book[]> {
const requestPayload = {
bookIds: Array.from(bookIds),
@@ -49,15 +76,8 @@ export class BookPatchService {
return this.http.post<void>(`${this.url}/progress`, body);
}
saveEpubProgress(bookId: number, cfi: string, percentage: number): Observable<void> {
const body = {
bookId: bookId,
epubProgress: {
cfi: cfi,
percentage: percentage
}
};
return this.http.post<void>(`${this.url}/progress`, body);
saveEpubProgress(bookId: number, cfi: string, href: string, percentage: number): void {
this.epubProgressSubject.next({bookId, cfi, href, percentage});
}
saveCbxProgress(bookId: number, page: number, percentage: number): Observable<void> {
@@ -197,4 +217,3 @@ export class BookPatchService {
this.bookStateService.updateBookState({...currentState, books: updatedBooks});
}
}
@@ -329,12 +329,6 @@ describe('BookService', () => {
expect(result).toBeUndefined();
});
it('should save epub progress', async () => {
bookPatchServiceMock.saveEpubProgress.mockReturnValue(of(void 0));
const result = await firstValueFrom(service.saveEpubProgress(1, 'cfi', 0.5));
expect(result).toBeUndefined();
});
it('should save cbx progress', async () => {
bookPatchServiceMock.saveCbxProgress.mockReturnValue(of(void 0));
const result = await firstValueFrom(service.saveCbxProgress(1, 2, 0.5));
@@ -259,8 +259,8 @@ export class BookService {
? reader === 'ngx'
? 'pdf-reader'
: 'cbx-reader'
: book.bookType === 'EPUB'
? 'epub-reader'
: book.bookType === 'EPUB' || book.bookType === 'FB2' || book.bookType === 'MOBI' || book.bookType === 'AZW3'
? 'ebook-reader'
: book.bookType === 'CBX'
? 'cbx-reader'
: null;
@@ -414,9 +414,9 @@ export class BookService {
return this.bookPatchService.savePdfProgress(bookId, page, percentage);
}
saveEpubProgress(bookId: number, cfi: string, percentage: number): Observable<void> {
return this.bookPatchService.saveEpubProgress(bookId, cfi, percentage);
}
/*saveEpubProgress(bookId: number, cfi: string, href: string, percentage: number): Observable<void> {
return this.bookPatchService.saveEpubProgress(bookId, cfi, href, percentage);
}*/
saveCbxProgress(bookId: number, page: number, percentage: number): Observable<void> {
return this.bookPatchService.saveCbxProgress(bookId, page, percentage);
@@ -24,7 +24,12 @@
[horizontal]="true">
@for (book of books; track book.id) {
<div class="dashboard-scroller-card" [class.menu-open]="openMenuBookId === book.id">
<app-book-card [book]="book" [isCheckboxEnabled]="false" (menuToggled)="handleMenuToggle(book.id, $event)"></app-book-card>
<app-book-card
[book]="book"
[isCheckboxEnabled]="false"
(menuToggled)="handleMenuToggle(book.id, $event)"
[overlayPreferenceService]="bookCardOverlayPreferenceService"
></app-book-card>
</div>
}
</div>
@@ -1,10 +1,11 @@
import {Component, ElementRef, Input, ViewChild} from '@angular/core';
import {Component, ElementRef, Input, ViewChild, inject} from '@angular/core';
import {BookCardComponent} from '../../../book/components/book-browser/book-card/book-card.component';
import {InfiniteScrollDirective} from 'ngx-infinite-scroll';
import {ProgressSpinnerModule} from 'primeng/progressspinner';
import {Book} from '../../../book/model/book.model';
import {ScrollerType} from '../../models/dashboard-config.model';
import { BookCardOverlayPreferenceService } from '../../../book/components/book-browser/book-card-overlay-preference.service';
@Component({
selector: 'app-dashboard-scroller',
@@ -27,6 +28,8 @@ export class DashboardScrollerComponent {
@ViewChild('scrollContainer') scrollContainer!: ElementRef;
openMenuBookId: number | null = null;
public bookCardOverlayPreferenceService = inject(BookCardOverlayPreferenceService);
handleMenuToggle(bookId: number, isOpen: boolean) {
this.openMenuBookId = isOpen ? bookId : null;
}
@@ -197,7 +197,10 @@ export class MagicShelfComponent implements OnInit {
{label: 'EPUB', value: 'epub'},
{label: 'CBR', value: 'cbr'},
{label: 'CBZ', value: 'cbz'},
{label: 'CB7', value: 'cb7'}
{label: 'CB7', value: 'cb7'},
{label: 'FB2', value: 'fb2'},
{label: 'MOBI', value: 'mobi'},
{label: 'AZW3', value: 'azw3'}
];
readStatusOptions = Object.entries(ReadStatus).map(([key, value]) => ({
@@ -559,7 +559,7 @@
<p-splitbutton label="Read" icon="pi pi-book" [model]="readItems" (onClick)="read(book.id, 'ngx')" severity="primary"/>
}
}
@if (book!.bookType !== 'PDF' && book!.bookType !== 'FB2') {
@if (book!.bookType !== 'PDF') {
<p-button label="Read" icon="pi pi-book" (onClick)="read(book?.metadata!.bookId, undefined)" severity="primary"/>
}
<p-button label="Shelf" icon="pi pi-folder" severity="info" outlined (onClick)="assignShelf(book.id)" class="mobile-icon-only"></p-button>
@@ -734,6 +734,12 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
return 'purple';
case 'cb7':
return 'blue';
case 'fb2':
return 'orange';
case 'mobi':
return 'yellow';
case 'azw3':
return 'green';
default:
return 'gray';
}
@@ -0,0 +1,96 @@
<div
class="reader"
[style.background-color]="stateService.currentState.theme.bg ?? ''">
@if (isLoading) {
<div class="loader-overlay">
<div class="loader-content">
<div class="spinner"></div>
<p class="loader-text">Loading book...</p>
</div>
</div>
}
<app-reader-header
[bookTitle]="book?.metadata?.title!"
[currentTheme]="stateService.currentState.theme"
[isDark]="stateService.currentState.isDark"
[fontSize]="stateService.currentState.fontSize"
[lineHeight]="stateService.currentState.lineHeight"
[forceVisible]="forceHeaderVisible"
[flow]="stateService.currentState.flow"
(setFlow)="onSetFlow($event)"
(showChapters)="showChapters = true"
(showControls)="showControls = true"
(showMetadata)="showMetadata = true"
(createBookmark)="onCreateBookmark()"
(close)="location.back()"
(toggleDarkMode)="onToggleDarkMode()"
(increaseFontSize)="onIncreaseFontSize()"
(decreaseFontSize)="onDecreaseFontSize()"
(increaseLineHeight)="onIncreaseLineHeight()"
(decreaseLineHeight)="onDecreaseLineHeight()"
></app-reader-header>
<div class="reader-content" style="position: relative;">
@if (isCurrentCfiBookmarked) {
<div
style="
position: absolute;
top: 0;
left: 12px;
z-index: 10;
width: 48px;
height: 64px;
background: none;
pointer-events: none;
">
<svg width="48" height="64" viewBox="0 0 48 64">
<polygon points="0,0 48,0 48,64 24,48 0,64" fill="red"/>
</svg>
</div>
}
<div id="foliate-container" tabindex="0"></div>
</div>
<app-reader-navbar
[progressData]="currentProgressData"
[forceVisible]="forceNavbarVisible"
[sectionFractions]="sectionFractions"
(progressChange)="onProgressChange($event)">
</app-reader-navbar>
@if (showChapters) {
<app-reader-sidebar
[bookId]="book?.id ?? null"
[coverUpdatedOn]="coverUpdatedOn"
[bookTitle]="book?.metadata?.title ?? ''"
[bookAuthors]="(book?.metadata?.authors ?? []).join(', ')"
[chapters]="chapters"
[bookmarks]="bookmarks"
[currentChapterHref]="currentChapterHref"
(close)="showChapters = false"
(chapterClick)="onChapterClick($event)"
(bookmarkClick)="onBookmarkClick($event)"
(deleteBookmark)="onDeleteBookmark($event)"
(coverClick)="showMetadata = true"
></app-reader-sidebar>
}
@if (showControls) {
<app-settings-dialog
[stateService]="stateService"
[viewManager]="viewManager"
[bookId]="bookId"
(close)="showControls = false">
</app-settings-dialog>
}
@if (showMetadata) {
<app-reader-book-metadata-dialog
[book]="book"
(close)="showMetadata = false"
></app-reader-book-metadata-dialog>
}
</div>
@@ -0,0 +1,120 @@
.reader {
width: 100vw;
height: 100dvh;
overflow: hidden;
position: fixed;
top: 0;
left: 0;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
}
.reader-content {
position: relative;
flex: 1;
overflow: hidden;
width: 100%;
height: 100%;
}
.navigation-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 10;
cursor: pointer;
pointer-events: auto;
background: transparent;
}
#foliate-container {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
pointer-events: auto;
}
::ng-deep foliate-view {
width: 100% !important;
height: 100% !important;
display: block !important;
position: absolute !important;
top: 0 !important;
left: 0 !important;
}
.loader-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.8);
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
}
.loader-content {
display: flex;
flex-direction: column;
align-items: center;
gap: 1.5rem;
}
.spinner {
width: 48px;
height: 48px;
border: 4px solid rgba(255, 255, 255, 0.2);
border-top-color: #fff;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
.loader-text {
color: #fff;
font-size: 1.1rem;
margin: 0;
font-weight: 500;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
foliate-view::part(head) {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 16px;
font-size: 0.875rem;
color: var(--text-secondary, #666);
border-bottom: 1px solid var(--border-color, #e0e0e0);
font-family: inherit;
min-height: 32px;
box-sizing: border-box;
}
foliate-view::part(foot) {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 16px;
font-size: 0.875rem;
color: var(--text-secondary, #666);
border-top: 1px solid var(--border-color, #e0e0e0);
font-family: inherit;
min-height: 32px;
box-sizing: border-box;
}
@@ -0,0 +1,449 @@
import {Component, CUSTOM_ELEMENTS_SCHEMA, HostListener, inject, OnDestroy, OnInit} from '@angular/core';
import {CommonModule, Location} from '@angular/common';
import {forkJoin, Observable, of, Subject, throwError} from 'rxjs';
import {catchError, switchMap, takeUntil, tap} from 'rxjs/operators';
import {ReaderLoaderService} from './services/reader-loader.service';
import {ReaderViewManagerService} from './services/reader-view-manager.service';
import {ReaderStateService} from './services/reader-state.service';
import {ReaderStyleService} from './services/reader-style.service';
import {ReaderBookmarkService} from './services/reader-bookmark.service';
import {BookService} from '../../book/service/book.service';
import {ActivatedRoute} from '@angular/router';
import {BookMark, BookMarkService} from '../../../shared/service/book-mark.service';
import {BookPatchService} from '../../book/service/book-patch.service';
import {EpubCustomFontService} from '../epub-reader/service/epub-custom-font.service';
import {Book, EbookViewerSetting} from '../../book/model/book.model';
import {ReaderHeaderComponent} from './reader-layout/header/reader-header.component';
import {ReaderSidebarComponent} from './reader-layout/sidebar/reader-sidebar.component';
import {ReaderNavbarComponent} from './reader-layout/navbar/reader-navbar.component';
import {ReaderSettingsDialogComponent} from './reader-layout/header/reader-settings-dialog.component';
import {ReaderBookMetadataDialogComponent} from './reader-layout/sidebar/reader-book-metadata-dialog.component';
import {ReadingSessionService} from '../../../shared/service/reading-session.service';
import {TocItem} from 'epubjs';
import {PageInfo, ThemeInfo} from './utils/reader-header-footer.util';
import {ReaderHeaderFooterVisibilityManager} from './utils/reader-header-footer-visibility.util';
@Component({
selector: 'app-ebook-reader',
standalone: true,
imports: [
CommonModule,
ReaderHeaderComponent,
ReaderSettingsDialogComponent,
ReaderBookMetadataDialogComponent,
ReaderSidebarComponent,
ReaderNavbarComponent
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
providers: [
ReaderLoaderService,
ReaderViewManagerService,
ReaderStateService,
ReaderStyleService,
ReaderBookmarkService
],
templateUrl: './ebook-reader.component.html',
styleUrls: ['./ebook-reader.component.scss']
})
export class EbookReaderComponent implements OnInit, OnDestroy {
private destroy$ = new Subject<void>();
private loaderService = inject(ReaderLoaderService);
private styleService = inject(ReaderStyleService);
private bookService = inject(BookService);
private route = inject(ActivatedRoute);
private bookMarkService = inject(BookMarkService);
private bookPatchService = inject(BookPatchService);
private epubCustomFontService = inject(EpubCustomFontService);
private bookmarkService = inject(ReaderBookmarkService);
private readingSessionService = inject(ReadingSessionService);
public viewManager = inject(ReaderViewManagerService);
public stateService = inject(ReaderStateService);
protected location = inject(Location);
protected bookId!: number;
private hasLoadedOnce = false;
private hasStartedSession = false;
private _fileUrl: string | null = null;
private currentCfi: string | null = null;
private visibilityManager!: ReaderHeaderFooterVisibilityManager;
isLoading = true;
showControls = false;
showChapters = false;
showMetadata = false;
isCurrentCfiBookmarked = false;
forceHeaderVisible = false;
forceNavbarVisible = false;
chapters: TocItem[] = [];
bookmarks: BookMark[] = [];
book: Book | null = null;
coverUpdatedOn: string | undefined;
currentChapterName: string | null = null;
currentChapterHref: string | null = null;
currentProgressData: any = null;
private currentPageInfo: PageInfo | undefined;
private relocateTimeout: any;
private sectionFractionsTimeout: any;
sectionFractions: number[] = [];
ngOnInit() {
this.visibilityManager = new ReaderHeaderFooterVisibilityManager(window.innerHeight);
this.visibilityManager.onStateChange((state) => {
this.forceHeaderVisible = state.headerVisible;
this.forceNavbarVisible = state.footerVisible;
});
this.isLoading = true;
this.initializeFoliate().pipe(
switchMap(() => this.epubCustomFontService.loadAndCacheFonts()),
tap(() => this.stateService.refreshCustomFonts()),
switchMap(() => this.setupView()),
switchMap(() => this.loadBookFromAPI()),
tap(() => {
this.loadBookmarks();
this.subscribeToStateChanges();
this.subscribeToViewEvents();
this.isLoading = false;
}),
catchError(err => {
this.isLoading = false;
return of(null);
}),
takeUntil(this.destroy$)
).subscribe();
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
this.viewManager.destroy();
this.bookmarkService.reset();
this.epubCustomFontService.cleanup();
if (this.readingSessionService.isSessionActive()) {
const progress = typeof this.currentProgressData?.fraction === 'number'
? Math.round(this.currentProgressData.fraction * 100 * 100) / 100
: undefined;
this.readingSessionService.endSession(this.currentCfi || undefined, progress);
}
if (this._fileUrl) {
URL.revokeObjectURL(this._fileUrl);
this._fileUrl = null;
}
}
private initializeFoliate(): Observable<void> {
return this.loaderService.loadFoliateScript().pipe(
switchMap(() => this.loaderService.waitForCustomElement())
);
}
private setupView(): Observable<void> {
const container = document.getElementById('foliate-container');
if (!container) {
return throwError(() => new Error('Container not found'));
}
container.setAttribute('tabindex', '0');
this.viewManager.createView(container);
return of(undefined);
}
private loadBookFromAPI(): Observable<void> {
this.bookId = +this.route.snapshot.paramMap.get('bookId')!;
return this.stateService.initializeState(this.bookId).pipe(
switchMap(() => forkJoin({
state: this.stateService.initializeState(this.bookId),
book: this.bookService.getBookByIdFromAPI(this.bookId, false),
fileBlob: this.bookService.getFileContent(this.bookId)
})),
switchMap(({book, fileBlob}) => {
this.book = book;
this.coverUpdatedOn = book.metadata?.coverUpdatedOn;
const fileUrl = URL.createObjectURL(fileBlob);
this._fileUrl = fileUrl;
return this.viewManager.loadEpub(fileUrl).pipe(
tap(() => {
this.applyStyles();
this.chapters = this.viewManager.getChapters();
}),
switchMap(() => this.viewManager.getMetadata()),
switchMap(() => {
if (!this.hasLoadedOnce) {
this.hasLoadedOnce = true;
return this.viewManager.goTo(book.epubProgress!.cfi);
}
return of(undefined);
})
);
})
);
}
private loadBookmarks(): void {
this.bookMarkService.getBookmarksForBook(this.bookId)
.pipe(takeUntil(this.destroy$))
.subscribe(bookmarks => {
this.bookmarks = bookmarks;
this.updateIsCurrentCfiBookmarked();
});
}
private subscribeToStateChanges(): void {
this.stateService.state$
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.applyStyles());
}
private subscribeToViewEvents(): void {
this.viewManager.events$
.pipe(takeUntil(this.destroy$))
.subscribe(event => {
switch (event.type) {
case 'load':
this.applyStyles();
this.chapters = this.viewManager.getChapters();
this.updateSectionFractions();
break;
case 'relocate':
if (this.relocateTimeout) clearTimeout(this.relocateTimeout);
this.relocateTimeout = setTimeout(() => {
this.handleRelocateEvent(event.detail);
}, 100);
if (this.sectionFractionsTimeout) clearTimeout(this.sectionFractionsTimeout);
this.sectionFractionsTimeout = setTimeout(() => {
this.updateSectionFractions();
}, 500);
break;
case 'middle-single-tap':
this.toggleHeaderNavbarPinned();
break;
}
});
}
private updateSectionFractions(): void {
this.sectionFractions = this.viewManager.getSectionFractions();
}
private handleRelocateEvent(detail: any): void {
this.currentProgressData = detail;
const cfi = detail?.cfi ?? null;
const href = detail?.pageItem?.href ?? detail?.tocItem?.href ?? null;
const percentage = typeof detail?.fraction === 'number' ? detail.fraction * 100 : null;
if (!this.hasStartedSession && cfi && percentage !== null) {
this.hasStartedSession = true;
this.readingSessionService.startSession(this.book!.id, this.book?.bookType!, cfi, percentage);
}
if (cfi && percentage !== null) {
this.bookPatchService.saveEpubProgress(this.bookId, cfi, href, percentage);
this.readingSessionService.updateProgress(cfi, percentage);
}
const chapterLabel = detail?.tocItem?.label;
if (chapterLabel && chapterLabel !== this.currentChapterName) {
this.currentChapterName = chapterLabel;
}
if (href && href !== this.currentChapterHref) {
this.currentChapterHref = href;
}
if (detail?.section) {
const percentCompleted = Math.round((detail.fraction * 100) * 10) / 10;
const totalMinutes = detail.time?.section ?? 0;
const hours = Math.floor(totalMinutes / 60);
const minutes = Math.floor(totalMinutes % 60);
const seconds = Math.round((totalMinutes - Math.floor(totalMinutes)) * 60);
const parts: string[] = [];
if (hours) parts.push(`${hours}h`);
if (minutes) parts.push(`${minutes}m`);
if (seconds || parts.length === 0) parts.push(`${seconds}s`);
const sectionTimeText = parts.join(' ');
this.currentPageInfo = {
percentCompleted,
sectionTimeText
};
}
if (this.stateService.currentState.flow === 'paginated') {
const renderer = this.viewManager.getRenderer();
const theme: ThemeInfo = {
fg: this.stateService.currentState.theme.fg || this.stateService.currentState.theme.light.fg,
bg: this.stateService.currentState.theme.bg || this.stateService.currentState.theme.light.bg
};
if (renderer && renderer.heads && renderer.feet) {
this.viewManager.updateHeadersAndFooters(this.currentChapterName || '', this.currentPageInfo, theme);
} else {
this.viewManager.updateHeadersAndFooters(this.currentChapterName || '', this.currentPageInfo, theme);
}
}
if (cfi) {
this.currentCfi = cfi;
this.updateIsCurrentCfiBookmarked();
this.bookmarkService.updateCurrentPosition(cfi, chapterLabel);
}
}
private updateIsCurrentCfiBookmarked(): void {
if (!this.currentCfi || !this.bookmarks?.length) {
this.isCurrentCfiBookmarked = false;
return;
}
this.isCurrentCfiBookmarked = this.bookmarks.some(b => b.cfi === this.currentCfi);
}
private applyStyles(): void {
const renderer = this.viewManager.getRenderer();
if (renderer) {
this.styleService.applyStylesToRenderer(renderer, this.stateService.currentState);
if (this.stateService.currentState.flow) {
renderer.setAttribute?.('flow', this.stateService.currentState.flow);
}
}
}
private syncSettingsToBackend(): void {
const setting: EbookViewerSetting = {
lineHeight: this.stateService.currentState.lineHeight,
justify: this.stateService.currentState.justify,
hyphenate: this.stateService.currentState.hyphenate,
maxColumnCount: this.stateService.currentState.maxColumnCount,
gap: this.stateService.currentState.gap,
fontSize: this.stateService.currentState.fontSize,
theme: typeof this.stateService.currentState.theme === 'object' && 'name' in this.stateService.currentState.theme
? this.stateService.currentState.theme.name
: (this.stateService.currentState.theme as any),
maxInlineSize: this.stateService.currentState.maxInlineSize,
maxBlockSize: this.stateService.currentState.maxBlockSize,
fontFamily: this.stateService.currentState.fontFamily,
isDark: this.stateService.currentState.isDark,
flow: this.stateService.currentState.flow,
};
this.bookService.updateViewerSetting({ebookSettings: setting}, this.bookId)
.pipe(takeUntil(this.destroy$))
.subscribe();
}
onChapterClick(href: string): void {
this.viewManager.goTo(href).pipe(
tap(() => this.showChapters = false),
takeUntil(this.destroy$)
).subscribe();
}
onBookmarkClick(cfi: string): void {
this.viewManager.goTo(cfi).pipe(
tap(() => {
this.showChapters = false;
this.currentCfi = cfi;
this.updateIsCurrentCfiBookmarked();
}),
takeUntil(this.destroy$)
).subscribe();
}
onCreateBookmark(): void {
this.bookmarkService.createBookmarkAtCurrentPosition(this.bookId)
.pipe(takeUntil(this.destroy$))
.subscribe(success => {
if (success) {
this.loadBookmarks();
}
});
}
onDeleteBookmark(bookmarkId: number): void {
this.bookMarkService.deleteBookmark(bookmarkId)
.pipe(takeUntil(this.destroy$))
.subscribe({
next: () => this.loadBookmarks(),
error: () => {
}
});
}
onProgressChange(fraction: number): void {
this.viewManager.goToFraction(fraction)
.pipe(takeUntil(this.destroy$))
.subscribe();
}
onToggleDarkMode(): void {
this.stateService.toggleDarkMode();
this.syncSettingsToBackend();
}
onIncreaseFontSize(): void {
this.stateService.updateFontSize(1);
this.syncSettingsToBackend();
}
onDecreaseFontSize(): void {
this.stateService.updateFontSize(-1);
this.syncSettingsToBackend();
}
onIncreaseLineHeight(): void {
this.stateService.updateLineHeight(0.1);
this.syncSettingsToBackend();
}
onDecreaseLineHeight(): void {
this.stateService.updateLineHeight(-0.1);
this.syncSettingsToBackend();
}
onSetFlow(flow: 'paginated' | 'scrolled'): void {
this.stateService.setFlow(flow);
this.syncSettingsToBackend();
if (flow === 'paginated' && this.currentChapterName) {
setTimeout(() => {
const renderer = this.viewManager.getRenderer();
if (renderer && renderer.heads && renderer.feet) {
const theme: ThemeInfo = {
fg: this.stateService.currentState.theme.fg || this.stateService.currentState.theme.light.fg,
bg: this.stateService.currentState.theme.bg || this.stateService.currentState.theme.light.bg
};
this.viewManager.updateHeadersAndFooters(this.currentChapterName || '', this.currentPageInfo, theme);
}
}, 50);
}
}
private toggleHeaderNavbarPinned(): void {
this.visibilityManager.togglePinned();
}
@HostListener('document:mousemove', ['$event'])
onMouseMove(event: MouseEvent): void {
this.visibilityManager.handleMouseMove(event.clientY);
}
@HostListener('document:mouseleave', ['$event'])
onMouseLeave(event: MouseEvent): void {
this.visibilityManager.handleMouseLeave();
}
@HostListener('window:resize', ['$event'])
onWindowResize(event: Event): void {
this.visibilityManager.updateWindowHeight(window.innerHeight);
}
}
@@ -0,0 +1,19 @@
<div
class="reader-header"
[style.color]="currentTheme?.fg ?? ''"
[style.background]="currentTheme?.bg ?? ''"
[class.visible]="headerVisible">
<button class="icon-btn" (click)="showChapters.emit()" title="Chapters">
<i class="pi pi-bars" aria-label="Chapters"></i>
</button>
<button class="icon-btn" (click)="createBookmark.emit()" title="Create Bookmark">
<i class="pi pi-bookmark" aria-label="Create Bookmark"></i>
</button>
<span class="chapter-title">{{ bookTitle || '' }}</span>
<button class="icon-btn" (click)="showControls.emit()" title="Settings">
<i class="pi pi-cog" aria-label="Settings"></i>
</button>
<button class="icon-btn" (click)="close.emit(); $event.stopPropagation()" title="Close Reader">
<i class="pi pi-times" aria-label="Close Reader"></i>
</button>
</div>
@@ -0,0 +1,77 @@
.reader-header {
position: absolute;
top: 0;
left: 0;
right: 0;
height: 36px;
padding: 0 10px;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 14px;
z-index: 1000;
background: inherit;
border-bottom: 1px solid rgba(0,0,0,0.13);
box-shadow: 0 2px 8px 0 rgba(0,0,0,0.13);
opacity: 0;
pointer-events: none;
transform: translateY(-100%);
transition: opacity 0.25s ease-out, transform 0.25s ease-out;
&.visible {
opacity: 1;
pointer-events: auto;
transform: translateY(0);
}
.icon-btn {
background: none;
border: none;
color: inherit;
cursor: pointer;
padding: 6px;
border-radius: 50%;
transition: background 0.15s, box-shadow 0.15s;
display: flex;
align-items: center;
justify-content: center;
margin-right: 8px;
&:hover {
background: rgba(255, 255, 255, 0.14);
box-shadow: 0 2px 8px 0 rgba(0,0,0,0.10);
}
&:last-of-type {
margin-right: 0;
}
.pi {
font-size: 16px;
}
}
.chapter-title {
flex: 1;
text-align: center;
font-size: 14px;
font-weight: 500;
color: inherit;
pointer-events: none;
user-select: none;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
min-height: 1.2em;
}
}
@media (max-width: 600px) {
.reader-header {
padding: 0 6px;
.icon-btn {
padding: 10px;
}
}
}
@@ -0,0 +1,32 @@
import {Component, EventEmitter, Input, Output} from '@angular/core';
@Component({
selector: 'app-reader-header',
standalone: true,
templateUrl: './reader-header.component.html',
styleUrls: ['./reader-header.component.scss']
})
export class ReaderHeaderComponent {
@Input() bookTitle: string | null = null;
@Input() currentTheme: any = null;
@Input() isDark = false;
@Input() fontSize = 16;
@Input() lineHeight = 1.5;
@Input() forceVisible = false;
@Input() flow: 'paginated' | 'scrolled' = 'paginated';
@Output() showChapters = new EventEmitter<void>();
@Output() showControls = new EventEmitter<void>();
@Output() showMetadata = new EventEmitter<void>();
@Output() createBookmark = new EventEmitter<void>();
@Output() close = new EventEmitter<void>();
@Output() toggleDarkMode = new EventEmitter<void>();
@Output() increaseFontSize = new EventEmitter<void>();
@Output() decreaseFontSize = new EventEmitter<void>();
@Output() increaseLineHeight = new EventEmitter<void>();
@Output() decreaseLineHeight = new EventEmitter<void>();
@Output() setFlow = new EventEmitter<'paginated' | 'scrolled'>();
get headerVisible(): boolean {
return this.forceVisible;
}
}
@@ -0,0 +1,205 @@
<div class="dialog-overlay" (click)="close.emit()">
<div class="dialog" (click)="$event.stopPropagation()">
<div class="tabs-row">
<div class="tabs">
<button
class="tab"
[class.active]="activeTab === 'theme'"
(click)="activeTab = 'theme'">
Theme
</button>
<button
class="tab"
[class.active]="activeTab === 'typography'"
(click)="activeTab = 'typography'">
Typography
</button>
<button
class="tab"
[class.active]="activeTab === 'layout'"
(click)="activeTab = 'layout'">
Layout
</button>
</div>
<button class="close-btn" (click)="close.emit()">✕</button>
</div>
<div class="dialog-body">
@if (activeTab === 'theme') {
<div class="tab-content">
<div class="section-header dark-mode-header">
Dark Mode
<span class="mode-switch-wrapper">
<span class="mode-icon sun" [class.active]="!state.isDark">☀️</span>
<button class="switch" [class.active]="state.isDark" (click)="toggleDarkMode()">
<span class="slider"></span>
</button>
<span class="mode-icon moon" [class.active]="state.isDark">🌙</span>
</span>
</div>
<div class="section-header">Theme Colors</div>
<div class="theme-grid">
@for (theme of themes; track theme.name) {
<label class="theme-option">
<input
type="radio"
name="theme"
[value]="theme.name"
[checked]="state.theme.name === theme.name"
(change)="onThemeChange(theme.name)">
<div class="theme-card">
<div class="theme-colors">
<span class="color-swatch" [style.background-color]="state.isDark ? theme.dark.bg : theme.light.bg"></span>
<span class="color-swatch" [style.background-color]="state.isDark ? theme.dark.fg : theme.light.fg"></span>
</div>
<span class="theme-name">{{ theme.label }}</span>
</div>
</label>
}
</div>
</div>
}
@if (activeTab === 'typography') {
<div class="tab-content">
<div class="section-header">Font Settings</div>
<div class="control">
<label>Font Size</label>
<div class="control-right">
<div class="stepper">
<button (click)="decreaseFontSize()">−</button>
<span>{{ state.fontSize }}</span>
<button (click)="increaseFontSize()">+</button>
</div>
</div>
</div>
<div class="control">
<label>Line Height</label>
<div class="control-right">
<div class="stepper">
<button (click)="decreaseLineHeight()">−</button>
<span>{{ state.lineHeight | number:'1.1-1' }}</span>
<button (click)="increaseLineHeight()">+</button>
</div>
</div>
</div>
<div class="section-header">Font Family</div>
<div class="font-grid">
@for (font of fonts; track font.value) {
<button
class="font-option"
[class.active]="state.fontFamily === font.value"
[style.font-family]="font.value ? getFontFamilyForPreview(font.value) : 'inherit'"
(click)="setFontFamily(font.value)">
<span class="font-preview">Aa</span>
<span class="font-name">{{ font.name }}</span>
</button>
}
</div>
</div>
}
@if (activeTab === 'layout') {
<div class="tab-content">
<div class="section-header">Layout</div>
<div class="control">
<label>Reading Flow</label>
<div class="control-right">
<div class="radio-group">
<label>
<input
type="radio"
name="flow"
value="paginated"
[checked]="state.flow === 'paginated'"
(change)="setFlow('paginated')"
/>
Paginated
</label>
<label>
<input
type="radio"
name="flow"
value="scrolled"
[checked]="state.flow === 'scrolled'"
(change)="setFlow('scrolled')"
/>
Scrolled
</label>
</div>
</div>
</div>
<div class="control">
<label>Max Columns</label>
<div class="control-right">
<div class="stepper">
<button (click)="decreaseMaxColumnCount()">−</button>
<span>{{ state.maxColumnCount }}</span>
<button (click)="increaseMaxColumnCount()">+</button>
</div>
</div>
</div>
<div class="control">
<label>Column Gap</label>
<div class="control-right gap-control">
<input
#gapInput
type="range"
min="0"
max="0.5"
step="0.01"
[value]="state.gap"
(input)="setGap(gapInput.valueAsNumber)"
/>
<span class="value">{{ (state.gap * 100) | number : '1.0-0' }}%</span>
</div>
</div>
<div class="control">
<label>Max Width</label>
<div class="control-right">
<div class="stepper">
<button (click)="decreaseMaxInlineSize()">−</button>
<span>{{ state.maxInlineSize }}</span>
<button (click)="increaseMaxInlineSize()">+</button>
</div>
</div>
</div>
<div class="control">
<label>Max Height</label>
<div class="control-right">
<div class="stepper">
<button (click)="decreaseMaxBlockSize()">−</button>
<span>{{ state.maxBlockSize }}</span>
<button (click)="increaseMaxBlockSize()">+</button>
</div>
</div>
</div>
<div class="section-header">Text Options</div>
<div class="toggle-control">
<span>Justify Text</span>
<button class="switch" [class.active]="state.justify" (click)="toggleJustify()">
<span class="slider"></span>
</button>
</div>
<div class="toggle-control">
<span>Hyphenate</span>
<button class="switch" [class.active]="state.hyphenate" (click)="toggleHyphenate()">
<span class="slider"></span>
</button>
</div>
</div>
}
</div>
</div>
</div>
@@ -0,0 +1,672 @@
.dialog-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.2);
z-index: 12000;
display: flex;
align-items: center;
justify-content: center;
animation: fadeIn 0.2s ease-out;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.dialog {
background: rgba(30, 30, 30, 0.95);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border-radius: 12px;
width: 90%;
max-width: 520px;
height: 600px;
max-height: 85vh;
overflow: hidden;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
animation: slideUp 0.3s ease-out;
display: flex;
flex-direction: column;
}
@keyframes slideUp {
from {
transform: translateY(20px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.dialog-header {
padding: 16px 20px;
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
display: flex;
align-items: center;
justify-content: space-between;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.02) 0%, transparent 100%);
h2 {
margin: 0;
font-size: 18px;
font-weight: 600;
color: #ffffff;
letter-spacing: -0.3px;
}
}
.tabs-row {
display: flex;
align-items: center;
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
background: rgba(255, 255, 255, 0.02);
padding: 0 20px;
margin-bottom: 18px;
justify-content: center;
position: relative;
}
.tabs {
display: flex;
align-items: center;
justify-content: center;
flex: 0 1 auto;
}
.tabs-row-spacer {
display: none;
}
.tab {
background: none;
border: none;
color: rgba(255, 255, 255, 0.6);
padding: 12px 18px;
cursor: pointer;
font-size: 14px;
font-weight: 500;
position: relative;
transition: all 0.2s ease;
text-align: center;
min-width: 80px;
display: flex;
align-items: center;
justify-content: center;
&:hover {
color: rgba(255, 255, 255, 0.8);
}
&.active {
color: #ffffff;
&::after {
content: '';
position: absolute;
left: 50%;
bottom: 0;
transform: translateX(-50%);
width: 60%;
height: 2px;
background: #4a9eff;
border-radius: 1px;
}
}
}
.close-btn {
position: absolute;
right: 20px;
top: 50%;
transform: translateY(-50%);
margin-left: 0;
background: none;
border: none;
color: rgba(255, 255, 255, 0.6);
font-size: 20px;
cursor: pointer;
border-radius: 6px;
transition: all 0.2s ease;
line-height: 1;
&:hover {
background: rgba(255, 255, 255, 0.08);
color: rgba(255, 255, 255, 0.9);
}
}
.dialog-body {
padding: 20px 25px;
overflow-y: auto;
flex: 1 1 0;
min-height: 0;
max-height: 100%;
&::-webkit-scrollbar {
width: 8px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.15);
border-radius: 4px;
&:hover {
background: rgba(255, 255, 255, 0.25);
}
}
section {
margin-bottom: 20px;
padding-bottom: 16px;
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
&:last-child {
margin-bottom: 0;
border-bottom: none;
padding-bottom: 0;
}
h3 {
margin: 0 0 10px 0;
font-size: 12px;
font-weight: 600;
color: rgba(255, 255, 255, 0.5);
text-transform: uppercase;
letter-spacing: 0.8px;
}
}
}
.tab-content {
animation: fadeIn 0.2s ease-out;
}
.mode-toggle,
.toggle-control {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 0;
margin-bottom: 2px;
span {
color: rgba(255, 255, 255, 0.9);
font-size: 14px;
font-weight: 500;
}
}
.mode-switch-wrapper {
display: flex;
align-items: center;
gap: 10px;
}
.mode-icon {
font-size: 18px;
opacity: 0.3;
transition: all 0.3s ease;
user-select: none;
&.active {
opacity: 1;
transform: scale(1.1);
}
&.sun {
filter: grayscale(100%);
&.active {
filter: grayscale(0%);
}
}
&.moon {
filter: grayscale(100%);
&.active {
filter: grayscale(0%);
}
}
}
.switch {
position: relative;
width: 44px;
height: 24px;
background: rgba(255, 255, 255, 0.15);
border: none;
border-radius: 12px;
cursor: pointer;
transition: background 0.3s ease;
padding: 0;
&.active {
background: #4a9eff;
.slider {
transform: translateX(20px);
}
}
.slider {
position: absolute;
top: 2px;
left: 2px;
width: 20px;
height: 20px;
background: #ffffff;
border-radius: 50%;
transition: transform 0.3s ease;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
&:hover {
background: rgba(255, 255, 255, 0.2);
&.active {
background: #5ba9ff;
}
}
}
.theme-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 14px;
margin-bottom: 16px;
}
@media (max-width: 768px) {
.theme-grid {
grid-template-columns: repeat(3, 1fr);
}
}
.theme-option {
cursor: pointer;
input[type="radio"] {
display: none;
}
.theme-card {
background: rgba(255, 255, 255, 0.05);
border: 2px solid rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 10px;
transition: all 0.2s ease;
display: flex;
flex-direction: column;
gap: 8px;
&:hover {
background: rgba(255, 255, 255, 0.08);
border-color: rgba(255, 255, 255, 0.2);
}
}
input:checked + .theme-card {
border-color: #4a9eff;
background: rgba(74, 158, 255, 0.1);
}
.theme-colors {
display: flex;
gap: 4px;
height: 24px;
}
.color-swatch {
flex: 1;
border-radius: 3px;
border: 1px solid rgba(0, 0, 0, 0.2);
}
.theme-name {
color: rgba(255, 255, 255, 0.9);
font-size: 12px;
font-weight: 500;
text-align: center;
}
}
.font-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 14px;
margin-bottom: 20px;
}
.font-option {
background: rgba(255, 255, 255, 0.05);
border: 2px solid rgba(255, 255, 255, 0.1);
border-radius: 8px;
padding: 10px;
cursor: pointer;
transition: all 0.2s ease;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
&:hover {
background: rgba(255, 255, 255, 0.08);
border-color: rgba(255, 255, 255, 0.2);
}
&.active {
border-color: #4a9eff;
background: rgba(74, 158, 255, 0.1);
}
.font-preview {
font-size: 24px;
color: #ffffff;
line-height: 1;
}
.font-name {
color: rgba(255, 255, 255, 0.7);
font-size: 12px;
font-weight: 500;
text-align: center;
}
}
.control {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 16px;
min-height: 32px;
&:last-child {
margin-bottom: 0;
}
> label {
color: rgba(255, 255, 255, 0.9);
font-size: 14px;
font-weight: 500;
flex-shrink: 0;
}
&.checkbox-control {
label {
display: flex;
align-items: center;
gap: 8px;
cursor: pointer;
width: 100%;
padding: 4px 0;
transition: color 0.2s ease;
&:hover {
color: #ffffff;
}
input[type="checkbox"] {
width: 16px;
height: 16px;
cursor: pointer;
accent-color: #4a9eff;
}
span {
flex: 1;
}
}
}
input[type="range"] {
flex: 1;
margin: 0 10px;
height: 5px;
background: rgba(255, 255, 255, 0.12);
border-radius: 3px;
outline: none;
cursor: pointer;
&::-webkit-slider-thumb {
-webkit-appearance: none;
width: 14px;
height: 14px;
border-radius: 50%;
background: #4a9eff;
cursor: pointer;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
transition: all 0.2s ease;
&:hover {
transform: scale(1.1);
box-shadow: 0 2px 8px rgba(74, 158, 255, 0.5);
}
}
&::-moz-range-thumb {
width: 14px;
height: 14px;
border-radius: 50%;
background: #4a9eff;
border: none;
cursor: pointer;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
transition: all 0.2s ease;
&:hover {
transform: scale(1.1);
box-shadow: 0 2px 8px rgba(74, 158, 255, 0.5);
}
}
}
.value {
color: rgba(255, 255, 255, 0.6);
font-size: 12px;
min-width: 42px;
text-align: right;
font-variant-numeric: tabular-nums;
}
select {
background: rgba(255, 255, 255, 0.08);
color: #ffffff;
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 6px;
padding: 6px 12px;
font-size: 13px;
cursor: pointer;
transition: all 0.2s ease;
min-width: 130px;
&:hover {
background: rgba(255, 255, 255, 0.12);
border-color: rgba(255, 255, 255, 0.25);
}
&:focus {
outline: none;
border-color: #4a9eff;
box-shadow: 0 0 0 3px rgba(74, 158, 255, 0.1);
}
option {
background: #1e1e1e;
color: #ffffff;
}
}
}
.control-right {
display: flex;
align-items: center;
gap: 8px;
}
.gap-control {
flex: 1;
max-width: 200px;
min-width: 160px;
input[type="range"] {
flex: 1;
margin-right: 8px;
}
.value {
min-width: 38px;
}
}
.stepper {
display: flex;
align-items: center;
gap: 4px;
background: rgba(255, 255, 255, 0.05);
padding: 3px;
border-radius: 6px;
border: 1px solid rgba(255, 255, 255, 0.1);
button {
width: 28px;
height: 28px;
background: rgba(255, 255, 255, 0.08);
color: rgba(255, 255, 255, 0.9);
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ease;
font-weight: 300;
&:hover {
background: rgba(255, 255, 255, 0.15);
color: #ffffff;
}
&:active {
transform: scale(0.95);
}
}
span {
min-width: 48px;
text-align: center;
color: #ffffff;
font-size: 13px;
font-weight: 500;
font-variant-numeric: tabular-nums;
}
}
.toggle {
width: 36px;
height: 36px;
padding: 0;
background: rgba(255, 255, 255, 0.08);
color: rgba(255, 255, 255, 0.7);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 6px;
cursor: pointer;
font-size: 16px;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.2s ease;
.icon {
display: block;
line-height: 1;
}
&:hover {
background: rgba(255, 255, 255, 0.12);
border-color: rgba(255, 255, 255, 0.25);
transform: translateY(-1px);
}
&:active {
transform: translateY(0);
}
}
.section-header {
color: rgba(255, 255, 255, 0.5);
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 1px;
margin-top: 24px;
margin-bottom: 12px;
padding-bottom: 8px;
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
&:first-child {
margin-top: 0;
}
&.dark-mode-header {
display: flex;
align-items: center;
font-size: 11px;
font-weight: 600;
gap: 30px;
padding-bottom: 8px;
margin-bottom: 30px;
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
}
}
.radio-group {
display: flex;
gap: 18px;
label {
display: flex;
align-items: center;
gap: 7px;
cursor: pointer;
font-size: 14px;
color: rgba(255, 255, 255, 0.85);
font-weight: 500;
position: relative;
user-select: none;
input[type="radio"] {
appearance: none;
width: 18px;
height: 18px;
border: 2px solid #4a9eff;
border-radius: 50%;
background: rgba(255, 255, 255, 0.08);
margin: 0 6px 0 0;
outline: none;
transition: border-color 0.2s, box-shadow 0.2s;
&:checked {
background: #4a9eff;
box-shadow: 0 0 0 2px rgba(74, 158, 255, 0.15);
border-color: #4a9eff;
}
&:focus {
box-shadow: 0 0 0 2px #4a9eff;
}
}
}
}
@@ -0,0 +1,157 @@
import {Component, EventEmitter, Inject, Input, OnInit, Output, Renderer2} from '@angular/core';
import {DecimalPipe, DOCUMENT} from '@angular/common';
import {ReaderStateService} from '../../services/reader-state.service';
import {ReaderViewManagerService} from '../../services/reader-view-manager.service';
import {BookService} from '../../../../book/service/book.service';
import {EpubCustomFontService} from '../../../epub-reader/service/epub-custom-font.service';
import {EbookViewerSetting} from '../../../../book/model/book.model';
@Component({
selector: 'app-settings-dialog',
standalone: true,
imports: [DecimalPipe],
templateUrl: './reader-settings-dialog.component.html',
styleUrls: ['./reader-settings-dialog.component.scss']
})
export class ReaderSettingsDialogComponent implements OnInit {
@Input() stateService!: ReaderStateService;
@Input() viewManager!: ReaderViewManagerService;
@Input() bookId!: number;
@Output() close = new EventEmitter<void>();
activeTab: 'theme' | 'typography' | 'layout' = 'theme';
constructor(
private bookService: BookService,
private customFontService: EpubCustomFontService,
private renderer: Renderer2,
@Inject(DOCUMENT) private document: Document
) {
}
ngOnInit() {
this.customFontService.injectCustomFontsStylesheet(this.renderer, this.document);
}
getFontFamilyForPreview(fontValue: string): string {
return this.customFontService.getFontFamilyForPreview(fontValue);
}
get state() {
return this.stateService.currentState;
}
get themes() {
return this.stateService.themes;
}
get fonts() {
return this.stateService.fonts;
}
private syncSettingsToBackend() {
const setting: EbookViewerSetting = {
lineHeight: this.state.lineHeight,
justify: this.state.justify,
hyphenate: this.state.hyphenate,
maxColumnCount: this.state.maxColumnCount,
gap: this.state.gap,
fontSize: this.state.fontSize,
theme: typeof this.state.theme === 'object' && 'name' in this.state.theme ? this.state.theme.name : (this.state.theme as any),
maxInlineSize: this.state.maxInlineSize,
maxBlockSize: this.state.maxBlockSize,
fontFamily: this.state.fontFamily,
isDark: this.state.isDark,
flow: this.state.flow,
};
this.bookService.updateViewerSetting({ebookSettings: setting}, this.bookId).subscribe();
}
setFontFamily(value: string | null) {
this.stateService.setFontFamily(value);
this.syncSettingsToBackend();
}
increaseFontSize() {
this.stateService.updateFontSize(1);
this.syncSettingsToBackend();
}
decreaseFontSize() {
this.stateService.updateFontSize(-1);
this.syncSettingsToBackend();
}
increaseLineHeight() {
this.stateService.updateLineHeight(0.1);
this.syncSettingsToBackend();
}
decreaseLineHeight() {
this.stateService.updateLineHeight(-0.1);
this.syncSettingsToBackend();
}
increaseMaxColumnCount() {
this.stateService.updateMaxColumnCount(1);
this.syncSettingsToBackend();
}
decreaseMaxColumnCount() {
this.stateService.updateMaxColumnCount(-1);
this.syncSettingsToBackend();
}
setGap(value: number) {
const delta = value - this.state.gap;
this.stateService.updateGap(delta);
this.syncSettingsToBackend();
}
toggleJustify() {
this.stateService.toggleJustify();
this.syncSettingsToBackend();
}
toggleHyphenate() {
this.stateService.toggleHyphenate();
this.syncSettingsToBackend();
}
increaseMaxInlineSize() {
this.stateService.updateMaxInlineSize(40);
this.syncSettingsToBackend();
}
decreaseMaxInlineSize() {
this.stateService.updateMaxInlineSize(-40);
this.syncSettingsToBackend();
}
increaseMaxBlockSize() {
this.stateService.updateMaxBlockSize(60);
this.syncSettingsToBackend();
}
decreaseMaxBlockSize() {
this.stateService.updateMaxBlockSize(-60);
this.syncSettingsToBackend();
}
toggleDarkMode() {
this.stateService.toggleDarkMode();
this.syncSettingsToBackend();
}
onThemeChange(themeName: string) {
this.stateService.setThemeByName(themeName);
this.syncSettingsToBackend();
}
setFlow(flow: 'paginated' | 'scrolled') {
this.stateService.setFlow(flow);
this.viewManager.getRenderer()?.setAttribute?.('flow', flow);
this.syncSettingsToBackend();
}
}
@@ -0,0 +1,92 @@
<div
class="reader-navbar"
[style.color]="'#ffffff'"
[style.background]="'#1a1a1a'"
[class.visible]="navbarVisible">
<button class="icon-btn" title="Previous">
<i class="pi pi-caret-left" aria-label="Previous"></i>
</button>
<div class="progress-section">
<button class="location-btn" (click)="toggleLocationPopover()" title="Location">
<span class="location-text">{{ currentPercentage }}%</span>
</button>
<div class="progress-slider-wrapper">
<input
type="range"
class="progress-slider"
[min]="0"
[max]="100"
[value]="currentPercentage"
(input)="onProgressChange($event)"
title="Progress"/>
<div class="progress-ticks">
@for (frac of sectionFractions; track frac) {
<span class="progress-tick" [style.left.%]="frac * 100"></span>
}
</div>
</div>
</div>
<button class="icon-btn" title="Next">
<i class="pi pi-caret-right" aria-label="Next"></i>
</button>
</div>
@if (showLocationPopover) {
<div class="location-popover" [style.color]="'#ffffff'" [style.background]="'#1a1a1a'" (mousedown)="$event.preventDefault()">
<div class="popover-content">
<div class="time-info">
<div class="time-section">
<span class="label">Time Left in Section</span>
<span class="value">{{ timeSection }}</span>
</div>
<div class="separator"></div>
<div class="time-section">
<span class="label">Time Left in Book</span>
<span class="value">{{ timeTotal }}</span>
</div>
</div>
<div class="divider"></div>
<div class="location-controls">
<div class="control-row">
<label>Page</label>
<span>{{ currentPage }}</span>
</div>
<div class="control-row">
<label>Location</label>
<input type="number" [value]="locationCurrent"/>
<span>/ {{ locationTotal }}</span>
</div>
<div class="control-row">
<label>Section</label>
<span>{{ sectionCurrent }} / {{ sectionTotal }}</span>
</div>
</div>
<div class="divider"></div>
<div class="section-navigation">
<button class="nav-btn" title="First Section" (click)="onFirstSection()">
<i class="pi pi-step-backward"></i>
</button>
<button class="nav-btn" title="Previous Section" (click)="onPreviousSection()">
<i class="pi pi-caret-left"></i>
</button>
<button class="nav-btn" title="Jump To…">
<i class="pi pi-ellipsis-v"></i>
</button>
<button class="nav-btn" title="Next Section" (click)="onNextSection()">
<i class="pi pi-caret-right"></i>
</button>
<button class="nav-btn" title="Last Section" (click)="onLastSection()">
<i class="pi pi-step-forward"></i>
</button>
</div>
</div>
</div>
}
@@ -0,0 +1,301 @@
.reader-navbar {
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 40px;
padding: 0 12px;
display: flex;
align-items: center;
gap: 8px;
z-index: 1000;
background: rgba(30, 30, 30, 0.95);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border-top: 1px solid rgba(255, 255, 255, 0.08);
box-shadow: 0 -2px 8px 0 rgba(0, 0, 0, 0.3);
opacity: 0;
pointer-events: none;
transform: translateY(100%);
transition: opacity 0.25s ease-out, transform 0.25s ease-out;
color: white;
&.visible {
opacity: 1;
pointer-events: auto;
transform: translateY(0);
}
.icon-btn {
background: none;
border: none;
color: rgba(255, 255, 255, 0.9);
font-size: 18px;
cursor: pointer;
padding: 0;
border-radius: 50%;
transition: background 0.15s, box-shadow 0.15s, color 0.15s;
width: 36px;
height: 36px;
aspect-ratio: 1 / 1;
display: flex;
align-items: center;
justify-content: center;
&:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.08);
box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.10);
color: #ffffff;
}
&:disabled {
opacity: 0.4;
cursor: not-allowed;
}
}
.progress-section {
flex: 1;
display: flex;
align-items: center;
gap: 12px;
.location-btn {
background: rgba(255, 255, 255, 0.05);
border: 1px solid rgba(255, 255, 255, 0.1);
color: rgba(255, 255, 255, 0.9);
padding: 4px 12px;
border-radius: 4px;
cursor: pointer;
font-size: 13px;
font-weight: 500;
transition: background 0.15s, color 0.15s;
&:hover {
background: rgba(255, 255, 255, 0.1);
color: #ffffff;
}
}
.progress-slider-wrapper {
position: relative;
flex: 1;
display: flex;
align-items: center;
.progress-slider {
flex: 1;
height: 6px;
border-radius: 3px;
outline: none;
-webkit-appearance: none;
background: rgba(255, 255, 255, 0.15);
position: relative;
z-index: 1;
&::-webkit-slider-thumb {
-webkit-appearance: none;
width: 16px;
height: 16px;
border-radius: 50%;
background: #4a9eff;
cursor: pointer;
}
&::-moz-range-thumb {
width: 16px;
height: 16px;
border-radius: 50%;
background: #4a9eff;
cursor: pointer;
border: none;
}
}
.progress-ticks {
position: absolute;
left: 0;
top: 50%;
width: 100%;
height: 10px;
transform: translateY(-50%);
pointer-events: none;
z-index: 0;
}
.progress-tick {
position: absolute;
top: 0;
width: 1.5px;
height: 10px;
background: rgba(255, 255, 255, 0.5);
border-radius: 2px;
}
}
}
}
.location-popover {
position: absolute;
bottom: 58px;
left: 50%;
transform: translateX(-50%);
background: rgba(30, 30, 30, 0.95);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 12px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.5);
z-index: 1001;
min-width: 380px;
animation: popoverSlideIn 0.15s ease-out;
transform-origin: bottom center;
color: white;
.popover-content {
padding: 20px;
}
.time-info {
display: flex;
gap: 24px;
align-items: center;
justify-content: space-around;
padding: 8px 0;
.time-section {
display: flex;
flex-direction: column;
gap: 6px;
text-align: center;
flex: 1;
.label {
font-size: 11px;
color: rgba(255, 255, 255, 0.6);
text-transform: uppercase;
letter-spacing: 0.5px;
font-weight: 500;
}
.value {
font-size: 20px;
font-weight: 600;
letter-spacing: -0.3px;
color: #ffffff;
}
}
.separator {
width: 1px;
height: 44px;
background: rgba(255, 255, 255, 0.12);
}
}
.divider {
height: 1px;
background: rgba(255, 255, 255, 0.08);
margin: 16px 0;
}
.location-controls {
display: flex;
flex-direction: column;
gap: 10px;
padding: 4px 0;
.control-row {
display: flex;
align-items: center;
gap: 16px;
label {
min-width: 70px;
font-size: 13px;
font-weight: 500;
color: rgba(255, 255, 255, 0.85);
}
input {
width: 65px;
padding: 6px 10px;
background: rgba(255, 255, 255, 0.06);
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 6px;
color: #ffffff;
font-size: 13px;
text-align: right;
transition: background 0.15s, border-color 0.15s;
&:focus {
outline: none;
background: rgba(255, 255, 255, 0.1);
border-color: rgba(255, 255, 255, 0.2);
}
}
span {
font-size: 13px;
color: rgba(255, 255, 255, 0.85);
}
}
}
.section-navigation {
display: flex;
gap: 8px;
justify-content: center;
align-items: center;
.nav-btn {
background: none;
border: none;
color: rgba(255, 255, 255, 0.9);
padding: 0;
margin: 0;
border-radius: 50%;
cursor: pointer;
font-size: 16px;
transition: background 0.15s ease, box-shadow 0.15s ease, transform 0.15s ease, color 0.15s ease;
width: 40px;
height: 40px;
min-width: 40px;
min-height: 40px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
&:hover {
background: rgba(255, 255, 255, 0.08);
box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.15);
transform: scale(1.05);
color: #ffffff;
}
&:active {
background: rgba(255, 255, 255, 0.15);
transform: scale(0.95);
}
i {
font-size: 18px;
display: flex;
align-items: center;
justify-content: center;
}
}
}
}
@keyframes popoverSlideIn {
from {
opacity: 0;
transform: translateX(-50%) translateY(4px) scale(0.95);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0) scale(1);
}
}
@@ -0,0 +1,144 @@
import {Component, EventEmitter, HostListener, inject, Input, Output} from '@angular/core';
import {ReaderViewManagerService} from '../../services/reader-view-manager.service';
interface TocItem {
label: string;
href: string;
subitems: any;
id: number;
}
interface PageItem {
label: string;
href: string;
subitems: any;
id: number;
}
interface RelocateEventDetail {
fraction: number;
section: { current: number; total: number };
location: { current: number; next: number; total: number };
time: { section: number; total: number };
tocItem: TocItem;
pageItem: PageItem;
cfi: string;
range: any;
}
@Component({
selector: 'app-reader-navbar',
standalone: true,
templateUrl: './reader-navbar.component.html',
styleUrls: ['./reader-navbar.component.scss']
})
export class ReaderNavbarComponent {
@Input() progressData: RelocateEventDetail | null = null;
@Input() forceVisible = false;
@Input() sectionFractions: number[] = [];
@Output() progressChange = new EventEmitter<number>();
private managerService = inject(ReaderViewManagerService);
showLocationPopover = false;
@HostListener('document:click', ['$event'])
onDocumentClick(event: MouseEvent) {
const target = event.target as HTMLElement;
const clickedInside = target.closest('.location-popover') || target.closest('.location-btn');
if (!clickedInside && this.showLocationPopover) {
this.showLocationPopover = false;
}
}
@HostListener('window:blur')
onWindowBlur() {
setTimeout(() => {
if (this.showLocationPopover) {
this.showLocationPopover = false;
}
}, 200);
}
toggleLocationPopover() {
this.showLocationPopover = !this.showLocationPopover;
}
get currentFraction(): number {
return this.progressData?.fraction ?? 0;
}
get currentPercentage(): number {
return Math.round(this.currentFraction * 100);
}
get timeTotal(): string {
return this.formatDuration((this.progressData?.time.total ?? 0) * 60);
}
get timeSection(): string {
return this.formatDuration((this.progressData?.time.section ?? 0) * 60);
}
get locationCurrent(): number {
return this.progressData?.location.current ?? 0;
}
get locationTotal(): number {
return this.progressData?.location.total ?? 0;
}
get sectionCurrent(): number {
return this.progressData?.section.current ?? 0;
}
get sectionTotal(): number {
return this.progressData?.section.total ?? 0;
}
get currentPage(): string {
return this.progressData?.pageItem?.label ?? 'N/A';
}
get navbarVisible(): boolean {
return this.forceVisible;
}
onProgressChange(event: Event) {
const target = event.target as HTMLInputElement;
const fraction = parseFloat(target.value) / 100;
this.progressChange.emit(fraction);
}
onFirstSection() {
this.managerService.goToSection(0).subscribe();
}
onPreviousSection(): void {
const s = this.progressData?.section;
if (!s || s.current <= 0) return;
this.managerService.goToSection(s.current - 1).subscribe();
}
onNextSection(): void {
const s = this.progressData?.section;
if (!s || s.current >= s.total - 1) return;
this.managerService.goToSection(s.current + 1).subscribe();
}
onLastSection(): void {
const s = this.progressData?.section;
if (!s || s.total <= 0) return;
this.managerService.goToSection(s.total - 1).subscribe();
}
private formatDuration(seconds: number): string {
if (seconds < 60) return `${Math.round(seconds)} sec`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes} min`;
const hours = Math.floor(minutes / 60);
const remainingMinutes = minutes % 60;
return remainingMinutes > 0
? `${hours} hr ${remainingMinutes} min`
: `${hours} hr`;
}
}
@@ -0,0 +1,199 @@
<div class="dialog-overlay" (click)="close.emit()">
<div class="dialog" (click)="$event.stopPropagation()">
<div class="dialog-header">
<h2>Book Information</h2>
<button class="close-btn" (click)="close.emit()">✕</button>
</div>
<div class="dialog-body">
<div class="metadata-container">
<div class="cover-section">
@if (bookCoverUrl) {
<img [src]="bookCoverUrl" [alt]="metadata?.title || 'Book cover'" class="book-cover">
} @else {
<div class="cover-placeholder">
<span class="placeholder-icon">📚</span>
</div>
}
</div>
<div class="metadata-section">
<div class="metadata-group">
<h3 class="section-title">Basic Information</h3>
<div class="metadata-item">
<span class="label">Title</span>
<span class="value">{{ metadata?.title || 'Unknown' }}</span>
</div>
@if (metadata?.subtitle) {
<div class="metadata-item">
<span class="label">Subtitle</span>
<span class="value">{{ metadata?.subtitle }}</span>
</div>
}
<div class="metadata-item">
<span class="label">Author(s)</span>
<span class="value">{{ formatAuthors(metadata?.authors) }}</span>
</div>
@if (metadata?.publisher) {
<div class="metadata-item">
<span class="label">Publisher</span>
<span class="value">{{ metadata?.publisher }}</span>
</div>
}
@if (metadata?.publishedDate) {
<div class="metadata-item">
<span class="label">Published</span>
<span class="value">{{ formatDate(metadata?.publishedDate) }}</span>
</div>
}
@if (metadata?.language) {
<div class="metadata-item">
<span class="label">Language</span>
<span class="value">{{ metadata?.language }}</span>
</div>
}
@if (metadata?.pageCount) {
<div class="metadata-item">
<span class="label">Pages</span>
<span class="value">{{ metadata?.pageCount }}</span>
</div>
}
</div>
@if (metadata?.seriesName) {
<div class="metadata-group">
<h3 class="section-title">Series</h3>
<div class="metadata-item">
<span class="label">Series Name</span>
<span class="value">{{ metadata?.seriesName }}</span>
</div>
@if (metadata?.seriesNumber) {
<div class="metadata-item">
<span class="label">Book Number</span>
<span class="value">
{{ metadata?.seriesNumber }}@if (metadata?.seriesTotal) {
/ {{ metadata?.seriesTotal }}
}
</span>
</div>
}
</div>
}
@if (metadata?.isbn13 || metadata?.isbn10 || metadata?.asin) {
<div class="metadata-group">
<h3 class="section-title">Identifiers</h3>
@if (metadata?.isbn13) {
<div class="metadata-item">
<span class="label">ISBN-13</span>
<span class="value">{{ metadata?.isbn13 }}</span>
</div>
}
@if (metadata?.isbn10) {
<div class="metadata-item">
<span class="label">ISBN-10</span>
<span class="value">{{ metadata?.isbn10 }}</span>
</div>
}
@if (metadata?.asin) {
<div class="metadata-item">
<span class="label">ASIN</span>
<span class="value">{{ metadata?.asin }}</span>
</div>
}
</div>
}
@if (metadata?.rating || metadata?.goodreadsRating || metadata?.amazonRating) {
<div class="metadata-group">
<h3 class="section-title">Ratings</h3>
@if (metadata?.goodreadsRating) {
<div class="metadata-item">
<span class="label">Goodreads</span>
<span class="value">
⭐ {{ metadata?.goodreadsRating?.toFixed(2) }}
@if (metadata?.goodreadsReviewCount) {
<span class="review-count">({{ metadata?.goodreadsReviewCount }} reviews)</span>
}
</span>
</div>
}
@if (metadata?.amazonRating) {
<div class="metadata-item">
<span class="label">Amazon</span>
<span class="value">
⭐ {{ metadata?.amazonRating?.toFixed(2) }}
@if (metadata?.amazonReviewCount) {
<span class="review-count">({{ metadata?.amazonReviewCount }} reviews)</span>
}
</span>
</div>
}
</div>
}
@if (metadata?.categories && metadata?.categories!.length > 0) {
<div class="metadata-group">
<h3 class="section-title">Categories</h3>
<div class="tags-container">
@for (category of metadata?.categories; track category) {
<span class="tag">{{ category }}</span>
}
</div>
</div>
}
@if (metadata?.tags && metadata?.tags!.length > 0) {
<div class="metadata-group">
<h3 class="section-title">Tags</h3>
<div class="tags-container">
@for (tag of metadata?.tags; track tag) {
<span class="tag">{{ tag }}</span>
}
</div>
</div>
}
@if (book?.fileSizeKb) {
<div class="metadata-group">
<h3 class="section-title">File Information</h3>
<div class="metadata-item">
<span class="label">File Size</span>
<span class="value">{{ formatFileSize(book?.fileSizeKb) }}</span>
</div>
@if (book?.fileName) {
<div class="metadata-item">
<span class="label">File Name</span>
<span class="value file-name">{{ book?.fileName }}</span>
</div>
}
</div>
}
@if (metadata?.description) {
<div class="metadata-group">
<h3 class="section-title">Description</h3>
<p class="description">{{ metadata?.description }}</p>
</div>
}
</div>
</div>
</div>
</div>
</div>
@@ -0,0 +1,261 @@
.dialog-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.2);
z-index: 12000;
display: flex;
align-items: center;
justify-content: center;
animation: fadeIn 0.2s ease-out;
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.dialog {
background: rgba(30, 30, 30, 0.95);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border-radius: 12px;
width: 90%;
max-width: 800px;
max-height: 85vh;
display: flex;
flex-direction: column;
overflow: hidden;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
animation: slideUp 0.3s ease-out;
@media (max-width: 768px) {
width: 95%;
max-height: 90vh;
margin: 20px;
}
}
@keyframes slideUp {
from {
transform: translateY(20px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.dialog-header {
padding: 16px 20px;
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
display: flex;
align-items: center;
justify-content: space-between;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.02) 0%, transparent 100%);
h2 {
margin: 0;
font-size: 18px;
font-weight: 600;
color: #ffffff;
letter-spacing: -0.3px;
}
}
.close-btn {
background: none;
border: none;
color: rgba(255, 255, 255, 0.6);
font-size: 20px;
cursor: pointer;
padding: 4px 8px;
border-radius: 6px;
transition: all 0.2s ease;
line-height: 1;
&:hover {
background: rgba(255, 255, 255, 0.08);
color: rgba(255, 255, 255, 0.9);
}
}
.dialog-body {
padding: 20px;
overflow-y: auto;
flex: 1;
min-height: 0;
@media (max-width: 768px) {
padding: 16px;
}
&::-webkit-scrollbar {
width: 8px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.15);
border-radius: 4px;
&:hover {
background: rgba(255, 255, 255, 0.25);
}
}
}
.metadata-container {
display: flex;
gap: 24px;
@media (max-width: 768px) {
flex-direction: column;
gap: 16px;
}
}
.cover-section {
flex-shrink: 0;
width: 240px;
@media (max-width: 768px) {
width: 100%;
max-width: 180px;
margin: 0 auto;
}
}
.book-cover {
width: 100%;
height: auto;
border-radius: 8px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
max-height: 360px;
object-fit: cover;
@media (max-width: 768px) {
max-height: 270px;
}
}
.cover-placeholder {
width: 100%;
aspect-ratio: 2/3;
background: linear-gradient(135deg, rgba(255, 255, 255, 0.05) 0%, rgba(255, 255, 255, 0.02) 100%);
border: 2px dashed rgba(255, 255, 255, 0.15);
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
@media (max-width: 768px) {
max-height: 270px;
}
.placeholder-icon {
font-size: 64px;
opacity: 0.3;
@media (max-width: 768px) {
font-size: 48px;
}
}
}
.metadata-section {
flex: 1;
display: flex;
flex-direction: column;
gap: 20px;
}
.metadata-group {
animation: fadeIn 0.2s ease-out;
&:not(:last-child) {
padding-bottom: 16px;
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
}
}
.section-title {
color: rgba(255, 255, 255, 0.5);
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 1px;
margin: 0 0 12px 0;
}
.metadata-item {
display: grid;
grid-template-columns: 120px 1fr;
gap: 12px;
margin-bottom: 10px;
align-items: start;
&:last-child {
margin-bottom: 0;
}
@media (max-width: 768px) {
grid-template-columns: 1fr;
gap: 4px;
}
}
.label {
color: rgba(255, 255, 255, 0.6);
font-size: 13px;
font-weight: 500;
}
.value {
color: rgba(255, 255, 255, 0.95);
font-size: 13px;
word-break: break-word;
&.file-name {
font-family: 'Courier New', monospace;
font-size: 12px;
color: rgba(255, 255, 255, 0.8);
}
}
.review-count {
color: rgba(255, 255, 255, 0.5);
font-size: 12px;
margin-left: 4px;
}
.tags-container {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.tag {
background: rgba(74, 158, 255, 0.15);
color: rgba(255, 255, 255, 0.9);
padding: 4px 12px;
border-radius: 12px;
font-size: 12px;
font-weight: 500;
border: 1px solid rgba(74, 158, 255, 0.25);
}
.description {
color: rgba(255, 255, 255, 0.8);
font-size: 13px;
line-height: 1.6;
margin: 0;
white-space: pre-wrap;
}
@@ -0,0 +1,52 @@
import {Component, EventEmitter, inject, Input, Output} from '@angular/core';
import {CommonModule} from '@angular/common';
import {Book} from '../../../../book/model/book.model';
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
@Component({
selector: 'app-reader-book-metadata-dialog',
standalone: true,
imports: [CommonModule],
templateUrl: './reader-book-metadata-dialog.component.html',
styleUrls: ['./reader-book-metadata-dialog.component.scss']
})
export class ReaderBookMetadataDialogComponent {
@Input() book: Book | null = null;
@Output() close = new EventEmitter<void>();
private urlHelperService = inject(UrlHelperService);
get metadata() {
return this.book?.metadata;
}
get bookCoverUrl(): string | null {
if (!this.book?.id) return null;
const coverUpdatedOn = this.book.metadata?.coverUpdatedOn;
return this.urlHelperService.getCoverUrl(this.book.id, coverUpdatedOn);
}
formatDate(date: string | undefined): string {
if (!date) return 'N/A';
try {
return new Date(date).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
} catch {
return date;
}
}
formatAuthors(authors: string[] | undefined): string {
if (!authors || authors.length === 0) return 'Unknown';
return authors.join(', ');
}
formatFileSize(sizeKb: number | undefined): string {
if (!sizeKb) return 'N/A';
if (sizeKb < 1024) return `${sizeKb.toFixed(1)} KB`;
return `${(sizeKb / 1024).toFixed(2)} MB`;
}
}
@@ -0,0 +1,104 @@
<div class="dialog-overlay"
(click)="onOverlayClick()"
[class.closing]="closing">
<div class="sidebar"
(click)="$event.stopPropagation()"
[class.closing]="closing">
<div class="sidebar-header">
<div class="sidebar-header-book">
@if (bookCoverUrl) {
<img
[src]="bookCoverUrl"
alt="Book cover"
class="sidebar-book-cover clickable"
(click)="onCoverClick()"
role="button"
tabindex="0"
(keydown.enter)="onCoverClick()"
(keydown.space)="onCoverClick()"
title="View book details"
/>
}
<div class="sidebar-book-meta">
<div class="sidebar-book-title ellipsis">{{ bookTitle }}</div>
@if (bookAuthors) {
<div class="sidebar-book-authors ellipsis">{{ bookAuthors }}</div>
}
</div>
</div>
</div>
<div class="sidebar-tabs">
<button
class="tab-btn"
[class.active]="activeTab === 'chapters'"
(click)="activeTab = 'chapters'"
aria-label="Chapters"
>
<i class="pi pi-book tab-icon"></i>
<span class="tab-label">Chapters</span>
</button>
<button
class="tab-btn"
[class.active]="activeTab === 'bookmarks'"
(click)="activeTab = 'bookmarks'"
aria-label="Bookmarks"
>
<i class="pi pi-bookmark tab-icon"></i>
<span class="tab-label">Bookmarks</span>
</button>
</div>
<div class="sidebar-body">
@switch (activeTab) {
@case ('chapters') {
<ul class="chapter-list">
@for (chapter of chapters; track chapter.href) {
<ng-container *ngTemplateOutlet="chapterNode; context: { $implicit: chapter, level: 0 }"></ng-container>
}
</ul>
<ng-template #chapterNode let-chapter let-level="level">
<li>
<div class="chapter-row"
[class.has-subchapters]="chapter.subitems?.length"
[class.active]="isChapterActive(chapter.href)"
[style.paddingLeft.px]="12 + (level * 16)"
(click)="chapter.subitems?.length ? toggleChapterExpand(chapter.href) : onChapterClick(chapter.href)">
<span class="chapter-label ellipsis">{{ chapter.label }}</span>
@if (chapter.subitems?.length) {
<span class="accordion-icon" [class.expanded]="isChapterExpanded(chapter.href)">
<i class="pi" [ngClass]="isChapterExpanded(chapter.href) ? 'pi-chevron-down' : 'pi-chevron-right'"></i>
</span>
}
</div>
@if (chapter.subitems?.length && isChapterExpanded(chapter.href)) {
<ul class="subchapter-list">
@for (sub of chapter.subitems; track sub.href) {
<ng-container *ngTemplateOutlet="chapterNode; context: { $implicit: sub, level: level + 1 }"></ng-container>
}
</ul>
}
</li>
</ng-template>
}
@case ('bookmarks') {
@if (bookmarks.length > 0) {
<ul>
@for (bookmark of bookmarks; track bookmark.id) {
<li class="bookmark-item" (click)="onBookmarkClick(bookmark.cfi)">
<div class="bookmark-info">
<div class="bookmark-title ellipsis">{{ bookmark.title }}</div>
<div class="bookmark-date">{{ bookmark.createdAt | date: 'short' }}</div>
</div>
<button class="bookmark-delete-btn" (click)="onDeleteBookmark($event, bookmark.id)" aria-label="Delete bookmark">
&times;
</button>
</li>
}
</ul>
} @else {
<div class="empty-tab">No bookmarks yet.</div>
}
}
}
</div>
</div>
</div>
@@ -0,0 +1,416 @@
.dialog-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.2);
z-index: 12000;
display: flex;
align-items: flex-start;
animation: fadeIn 200ms ease-out;
&.closing {
animation: fadeOut 200ms ease-in forwards;
}
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes fadeOut {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
.sidebar {
position: fixed;
top: 0;
left: 0;
bottom: 0;
width: 260px;
background: rgba(30, 30, 30, 0.95);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
box-shadow: 8px 0 32px rgba(0, 0, 0, 0.5);
z-index: 13001;
display: flex;
flex-direction: column;
color: white;
border-top-right-radius: 12px;
border-bottom-right-radius: 12px;
overflow: hidden;
animation: slideIn 250ms ease-out;
&.closing {
animation: slideOut 250ms ease-in forwards;
}
}
@keyframes slideIn {
from {
transform: translateX(-100%);
}
to {
transform: translateX(0);
}
}
@keyframes slideOut {
from {
transform: translateX(0);
}
to {
transform: translateX(-100%);
}
}
.sidebar-header {
display: flex;
align-items: center;
justify-content: flex-start;
padding: 16px;
min-height: 100px;
background: rgba(255, 255, 255, 0.02);
border-bottom: 1px solid rgba(255, 255, 255, 0.08);
position: relative;
}
.sidebar-header-book {
display: flex;
align-items: center;
gap: 12px;
}
.sidebar-book-cover {
width: 84px;
height: 117px;
object-fit: cover;
border-radius: 2px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.13);
background: #222;
flex-shrink: 0;
&.clickable {
cursor: pointer;
transition: transform 0.2s ease, opacity 0.2s ease, box-shadow 0.2s ease;
&:hover {
transform: scale(1.05);
opacity: 0.9;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}
&:active {
transform: scale(0.98);
}
&:focus-visible {
outline: 2px solid #4a90e2;
outline-offset: 2px;
}
}
}
.sidebar-book-meta {
display: flex;
flex-direction: column;
min-width: 0;
gap: 4px;
.sidebar-book-title {
font-size: 13px;
font-weight: 600;
color: #ffffff;
margin-bottom: 2px;
line-height: 1.2;
max-width: 220px;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-word;
max-height: calc(1.2em * 3);
}
.sidebar-book-authors {
font-size: 11px;
color: rgba(255, 255, 255, 0.6);
line-height: 1.2;
max-width: 220px;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
text-overflow: ellipsis;
word-break: break-word;
}
}
.sidebar-body {
flex: 1;
overflow-y: auto;
padding: 12px 0 12px 0;
&::-webkit-scrollbar {
width: 8px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.15);
border-radius: 4px;
&:hover {
background: rgba(255, 255, 255, 0.25);
}
}
ul {
list-style: none;
padding: 0;
margin: 0;
}
li {
padding: 6px 12px 6px 12px;
cursor: pointer;
font-size: 14px;
border-radius: 8px;
margin: 1px 8px;
transition: background 0.2s ease, color 0.2s ease;
color: rgba(255, 255, 255, 0.9);
background: transparent;
&:hover {
background: rgba(255, 255, 255, 0.08);
color: #ffffff;
}
border-bottom: none;
.chapter-label {
display: block;
width: 100%;
}
.ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
display: block;
width: 100%;
}
}
.bookmark-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
padding: 8px 12px;
.bookmark-info {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
flex-grow: 1;
}
.bookmark-title {
font-size: 13px;
font-weight: 500;
color: rgba(255, 255, 255, 0.9);
}
.bookmark-date {
font-size: 11px;
color: rgba(255, 255, 255, 0.5);
}
}
.bookmark-delete-btn {
background: none;
border: none;
color: rgba(255, 255, 255, 0.4);
cursor: pointer;
font-size: 18px;
padding: 4px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.2s ease, color 0.2s ease;
flex-shrink: 0;
&:hover {
background: rgba(255, 255, 255, 0.08);
color: #ffffff;
}
}
}
.sidebar-tabs {
display: flex;
background: rgba(255, 255, 255, 0.02);
border-top: 1px solid rgba(255, 255, 255, 0.08);
height: 50px;
align-items: center;
box-sizing: border-box;
overflow: hidden;
z-index: 13002;
position: relative;
}
.sidebar-tabs > * {
flex: 1;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
color: rgba(255, 255, 255, 0.75);
cursor: pointer;
user-select: none;
position: relative;
transition: background 0.15s ease, color 0.15s ease;
}
.sidebar-tabs > *:hover {
background: rgba(255, 255, 255, 0.05);
color: #fff;
}
.sidebar-tabs > *.active {
background: rgba(255, 255, 255, 0.08);
color: #fff;
}
.sidebar-tabs > *:not(:last-child)::after {
content: '';
position: absolute;
right: 0;
top: 8px;
bottom: 8px;
width: 1px;
background: rgba(255, 255, 255, 0.08);
}
.tab-btn {
flex: 1;
background: none;
border: none;
color: rgba(255, 255, 255, 0.6);
font-size: 13px;
padding: 8px 0;
cursor: pointer;
border-radius: 0;
transition: all 0.2s ease;
outline: none;
display: flex;
flex-direction: column;
align-items: center;
gap: 2px;
position: relative;
z-index: 13003;
&.active {
color: #ffffff;
font-weight: 600;
background: transparent;
border-bottom: 1.5px solid white;
z-index: 1;
}
&:hover:not(.active) {
background: transparent;
color: rgba(255, 255, 255, 0.8);
z-index: 2;
}
}
.tab-icon {
font-size: 16px;
display: block;
margin-bottom: 1px;
}
.tab-label {
font-size: 11px;
letter-spacing: 0.01em;
}
.empty-tab {
color: rgba(255, 255, 255, 0.5);
font-size: 14px;
text-align: center;
margin-top: 24px;
}
.chapter-list > li {
padding: 0;
margin: 0 8px;
border-radius: 8px;
}
.chapter-row {
display: flex;
align-items: center;
cursor: pointer;
padding: 6px 12px;
border-radius: 8px;
transition: background 0.2s;
color: rgba(255, 255, 255, 0.9);
&:hover {
background: rgba(255, 255, 255, 0.08);
color: #fff;
}
&.has-subchapters {
font-weight: 600;
}
&.active {
background: rgba(74, 144, 226, 0.3);
color: #ffffff;
font-weight: 600;
&:hover {
background: rgba(74, 144, 226, 0.4);
}
}
}
.accordion-icon {
margin-left: auto;
transition: transform 0.2s;
display: flex;
align-items: center;
i {
font-size: 13px;
}
}
.subchapter-list {
list-style: none;
padding-left: 0;
margin: 0;
li {
padding: 0;
margin: 0;
}
}
@@ -0,0 +1,127 @@
import {Component, EventEmitter, inject, Input, OnChanges, Output, SimpleChanges} from '@angular/core';
import {CommonModule} from '@angular/common';
import {BookMark} from '../../../../../shared/service/book-mark.service';
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
import {TocItem} from 'epubjs';
@Component({
selector: 'app-reader-sidebar',
standalone: true,
templateUrl: './reader-sidebar.component.html',
styleUrls: ['./reader-sidebar.component.scss'],
imports: [CommonModule]
})
export class ReaderSidebarComponent implements OnChanges {
@Input() bookId: number | null = null;
@Input() coverUpdatedOn: string | undefined;
@Input() bookTitle: string = '';
@Input() bookAuthors: string = '';
@Input() chapters: TocItem[] = [];
@Input() bookmarks: BookMark[] = [];
@Input() currentChapterHref: string | null = null;
@Output() close = new EventEmitter<void>();
@Output() chapterClick = new EventEmitter<string>();
@Output() bookmarkClick = new EventEmitter<string>();
@Output() deleteBookmark = new EventEmitter<number>();
@Output() coverClick = new EventEmitter<void>();
private urlHelperService = inject(UrlHelperService);
activeTab: 'chapters' | 'bookmarks' | 'annotation' = 'chapters';
closing = false;
bookCoverUrl: string | null = null;
expandedChapters = new Set<string>();
ngOnChanges(changes: SimpleChanges): void {
if (changes['bookId'] || changes['coverUpdatedOn']) {
this.bookCoverUrl = this.bookId
? this.urlHelperService.getThumbnailUrl(this.bookId, this.coverUpdatedOn)
: null;
}
if (changes['currentChapterHref']) {
if (this.currentChapterHref) {
this.autoExpandCurrentChapter();
}
}
}
private autoExpandCurrentChapter(): void {
if (!this.currentChapterHref) return;
const expandParents = (items: TocItem[], parents: string[] = []): boolean => {
for (const item of items) {
const currentParents = [...parents, item.href];
const normalizedItemHref = item.href.split('#')[0].replace(/^\//, '');
const normalizedCurrentHref = this.currentChapterHref!.split('#')[0].replace(/^\//, '');
if (normalizedItemHref === normalizedCurrentHref || item.href === this.currentChapterHref) {
parents.forEach(parentHref => this.expandedChapters.add(parentHref));
return true;
}
if (item.subitems?.length) {
if (expandParents(item.subitems, currentParents)) {
return true;
}
}
}
return false;
};
expandParents(this.chapters);
}
private closeWithAnimation(callback?: () => void) {
this.closing = true;
setTimeout(() => {
this.closing = false;
if (callback) callback();
this.close.emit();
}, 250);
}
onChapterClick(href: string) {
this.closeWithAnimation(() => this.chapterClick.emit(href));
}
onBookmarkClick(cfi: string) {
this.closeWithAnimation(() => this.bookmarkClick.emit(cfi));
}
onDeleteBookmark(event: MouseEvent, bookmarkId: number) {
event.stopPropagation();
this.deleteBookmark.emit(bookmarkId);
}
onCoverClick() {
this.closeWithAnimation(() => this.coverClick.emit());
}
onOverlayClick() {
this.closeWithAnimation();
}
toggleChapterExpand(href: string) {
if (this.expandedChapters.has(href)) {
this.expandedChapters.delete(href);
} else {
this.expandedChapters.add(href);
}
}
isChapterExpanded(href: string): boolean {
return this.expandedChapters.has(href);
}
isChapterActive(href: string): boolean {
if (!this.currentChapterHref) return false;
const normalizedItemHref = href.split('#')[0].replace(/^\//, '');
const normalizedCurrentHref = this.currentChapterHref.split('#')[0].replace(/^\//, '');
return normalizedItemHref === normalizedCurrentHref || href === this.currentChapterHref;
}
}
@@ -0,0 +1,65 @@
import {inject, Injectable} from '@angular/core';
import {Observable, of} from 'rxjs';
import {catchError, map} from 'rxjs/operators';
import {BookMarkService} from '../../../../shared/service/book-mark.service';
import {MessageService} from 'primeng/api';
@Injectable()
export class ReaderBookmarkService {
private currentCFI: string | null = null;
private currentChapterName: string | null = null;
private bookMarkService = inject(BookMarkService);
private messageService = inject(MessageService);
updateCurrentPosition(cfi: string, chapterName?: string): void {
this.currentCFI = cfi;
if (chapterName) {
this.currentChapterName = chapterName;
}
}
createBookmarkAtCurrentPosition(bookId: number): Observable<boolean> {
const cfi = this.currentCFI;
if (!cfi) {
console.error('Could not get current CFI - please navigate to a page first');
return of(false);
}
const title = this.currentChapterName || 'Bookmark';
return this.bookMarkService.createBookmark({bookId, cfi, title}).pipe(
map(() => {
this.messageService.add({
severity: 'success',
summary: 'Bookmark Added',
detail: 'Your bookmark was added successfully.'
});
return true;
}),
catchError(error => {
const isDuplicate = error?.status === 409;
this.messageService.add(
isDuplicate
? {
severity: 'warn',
summary: 'Bookmark Already Exists',
detail: 'You already have a bookmark at this location.'
}
: {
severity: 'error',
summary: 'Unable to Add Bookmark',
detail: 'Something went wrong while adding the bookmark. Please try again.'
}
);
return of(false);
})
);
}
reset(): void {
this.currentCFI = null;
this.currentChapterName = null;
}
}
@@ -0,0 +1,37 @@
import {Injectable} from '@angular/core';
import {defer, from, Observable, of} from 'rxjs';
import {switchMap} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ReaderLoaderService {
private scriptLoaded = false;
loadFoliateScript(): Observable<void> {
if (this.scriptLoaded || customElements.get('foliate-view')) {
return of(undefined);
}
return defer(() => new Observable<void>(observer => {
const script = document.createElement('script');
script.type = 'module';
script.src = '/assets/foliate/view.js';
script.onload = () => {
this.scriptLoaded = true;
setTimeout(() => {
observer.next();
observer.complete();
}, 100);
};
script.onerror = () => observer.error(new Error('Failed to load foliate.js'));
document.head.appendChild(script);
}));
}
waitForCustomElement(): Observable<void> {
return defer(() => from(customElements.whenDefined('foliate-view'))).pipe(
switchMap(() => of(undefined))
);
}
}
@@ -0,0 +1,239 @@
import {inject, Injectable} from '@angular/core';
import {BehaviorSubject, forkJoin, Observable} from 'rxjs';
import {map, tap} from 'rxjs/operators';
import {Theme, themes} from './reader-themes';
import {BookService} from '../../../book/service/book.service';
import {UserService} from '../../../settings/user-management/user.service';
import {EpubCustomFontService} from '../../epub-reader/service/epub-custom-font.service';
export interface ReaderState {
lineHeight: number;
justify: boolean;
hyphenate: boolean;
maxColumnCount: number;
gap: number;
fontSize: number;
theme: Theme;
maxInlineSize: number;
maxBlockSize: number;
fontFamily: string | null;
isDark: boolean;
flow: 'paginated' | 'scrolled';
}
@Injectable({
providedIn: 'root'
})
export class ReaderStateService {
private epubCustomFontService = inject(EpubCustomFontService);
private readonly BASE_FONTS = [
{name: 'Publisher\'s', value: null},
{name: 'Serif', value: 'serif'},
{name: 'Sans-Serif', value: 'sans-serif'},
{name: 'Monospace', value: 'monospace'},
{name: 'Cursive', value: 'cursive'},
];
private readonly defaultState: ReaderState = {
lineHeight: 1.5,
justify: true,
hyphenate: true,
maxColumnCount: 2,
gap: 0.05,
fontSize: 16,
theme: {
...themes[0],
fg: themes[0].dark.fg,
bg: themes[0].dark.bg,
link: themes[0].dark.link,
},
maxInlineSize: 720,
maxBlockSize: 1440,
fontFamily: null,
isDark: true,
flow: 'paginated',
};
private stateSubject = new BehaviorSubject<ReaderState>(this.defaultState);
public state$ = this.stateSubject.asObservable();
get currentState(): ReaderState {
return this.stateSubject.value;
}
readonly themes = themes;
private fontsSubject = new BehaviorSubject<Array<{ name: string; value: string | null }>>(this.BASE_FONTS);
get fonts(): Array<{ name: string; value: string | null }> {
return this.fontsSubject.value;
}
constructor(private bookService: BookService, private userService: UserService) {
this.loadCustomFontsIntoList();
}
private loadCustomFontsIntoList(): void {
const customFonts = this.epubCustomFontService.getCustomFonts();
const customFontOptions = customFonts.map(font => ({
name: font.fontName.replace(/\.(ttf|otf|woff|woff2)$/i, ''),
value: `custom:${font.id}`
}));
const updatedFonts = [
...this.fontsSubject.value,
...customFontOptions
];
this.fontsSubject.next(updatedFonts);
}
refreshCustomFonts(): void {
this.fontsSubject.next([...this.BASE_FONTS]);
this.loadCustomFontsIntoList();
}
initializeState(bookId: number): Observable<void> {
return forkJoin([
this.userService.getMyself(),
this.bookService.getBookSetting(bookId)
]).pipe(
tap(([myself, bookSetting]) => {
const settingScope = myself.userSettings.perBookSetting.epub;
const globalSettings = myself.userSettings.ebookReaderSetting;
const individualSetting = bookSetting?.ebookSettings;
const settings = settingScope === 'Global' ? globalSettings : (individualSetting || globalSettings);
const newState: Partial<ReaderState> = {};
if (settings.fontSize != null) newState.fontSize = settings.fontSize;
if (settings.lineHeight != null) newState.lineHeight = settings.lineHeight;
if (settings.fontFamily != null) {
if (settings.fontFamily.startsWith('custom:')) {
newState.fontFamily = settings.fontFamily;
} else {
const numericId = parseInt(settings.fontFamily, 10);
if (!isNaN(numericId) && numericId.toString() === settings.fontFamily) {
newState.fontFamily = `custom:${numericId}`;
} else {
newState.fontFamily = settings.fontFamily;
}
}
} else if ((settings as any).customFontId != null) {
newState.fontFamily = `custom:${(settings as any).customFontId}`;
}
if (settings.gap != null) newState.gap = settings.gap;
if (settings.hyphenate != null) newState.hyphenate = settings.hyphenate;
if (settings.justify != null) newState.justify = settings.justify;
if (settings.maxColumnCount != null) newState.maxColumnCount = settings.maxColumnCount;
if (settings.maxInlineSize != null) newState.maxInlineSize = settings.maxInlineSize;
if (settings.maxBlockSize != null) newState.maxBlockSize = settings.maxBlockSize;
if (settings.isDark != null) newState.isDark = settings.isDark;
if (settings.flow) newState.flow = settings.flow;
if (settings.theme) {
const theme = this.themes.find(t => t.name === settings.theme);
if (theme) {
newState.theme = {
...theme,
fg: settings.isDark ? theme.dark.fg : theme.light.fg,
bg: settings.isDark ? theme.dark.bg : theme.light.bg,
link: settings.isDark ? theme.dark.link : theme.light.link,
};
}
}
if (Object.keys(newState).length > 0) {
this.updateState(newState);
}
}),
map(() => void 0)
);
}
updateLineHeight(delta: number): void {
const current = this.currentState.lineHeight;
const newValue = Math.max(0.8, Math.min(3, current + delta));
this.updateState({lineHeight: newValue});
}
updateMaxColumnCount(delta: number): void {
const current = this.currentState.maxColumnCount;
const newValue = Math.max(1, Math.min(10, current + delta));
this.updateState({maxColumnCount: newValue});
}
updateGap(delta: number): void {
const current = this.currentState.gap;
const newValue = Math.max(0, Math.min(0.5, current + delta));
this.updateState({gap: newValue});
}
toggleJustify(): void {
this.updateState({justify: !this.currentState.justify});
}
toggleHyphenate(): void {
this.updateState({hyphenate: !this.currentState.hyphenate});
}
updateFontSize(delta: number): void {
const newFontSize = Math.max(10, Math.min(32, this.currentState.fontSize + delta));
this.updateState({fontSize: newFontSize});
}
setTheme(theme: Theme): void {
this.updateState({theme});
}
setFontFamily(font: string | null): void {
if (font === null) {
this.updateState({fontFamily: null});
} else if (!font.includes(':') && !isNaN(parseInt(font, 10)) && parseInt(font, 10).toString() === font) {
this.updateState({fontFamily: `custom:${font}`});
} else {
this.updateState({fontFamily: font});
}
}
updateMaxInlineSize(delta: number): void {
const newValue = Math.max(400, Math.min(1600, this.currentState.maxInlineSize + delta));
this.updateState({maxInlineSize: newValue});
}
updateMaxBlockSize(delta: number): void {
const newValue = Math.max(600, Math.min(2400, this.currentState.maxBlockSize + delta));
this.updateState({maxBlockSize: newValue});
}
toggleDarkMode() {
const currentTheme = this.currentState.theme;
const newIsDark = !this.currentState.isDark;
const newTheme = {
...currentTheme,
fg: newIsDark ? currentTheme.dark.fg : currentTheme.light.fg,
bg: newIsDark ? currentTheme.dark.bg : currentTheme.light.bg,
link: newIsDark ? currentTheme.dark.link : currentTheme.light.link,
};
this.updateState({theme: newTheme, isDark: newIsDark});
}
setThemeByName(themeName: string) {
const theme = this.themes.find(t => t.name === themeName);
if (theme) {
const newTheme = {
...theme,
fg: this.currentState.isDark ? theme.dark.fg : theme.light.fg,
bg: this.currentState.isDark ? theme.dark.bg : theme.light.bg,
link: this.currentState.isDark ? theme.dark.link : theme.light.link,
};
this.setTheme(newTheme);
}
}
setFlow(flow: 'paginated' | 'scrolled'): void {
this.updateState({ flow });
}
private updateState(partial: Partial<ReaderState>): void {
this.stateSubject.next({...this.currentState, ...partial});
}
}
@@ -0,0 +1,190 @@
import {inject, Injectable} from '@angular/core';
import {ReaderState} from './reader-state.service';
import {EpubCustomFontService} from '../../epub-reader/service/epub-custom-font.service';
@Injectable({
providedIn: 'root'
})
export class ReaderStyleService {
private epubCustomFontService = inject(EpubCustomFontService);
generateCSS(state: ReaderState): string {
const {lineHeight, justify, hyphenate, fontSize, theme, fontFamily} = state;
const userStylesheet = '';
const overrideFont = false;
const mediaActiveClass = 'media-active';
let fontFaceRule = '';
let actualFontFamily = null;
if (fontFamily !== null) {
const customFontId = this.parseCustomFontId(fontFamily);
if (customFontId !== null) {
const customFont = this.epubCustomFontService.getCustomFontById(customFontId);
const blobUrl = this.epubCustomFontService.getBlobUrl(customFontId);
if (customFont && blobUrl) {
const sanitizedFontName = this.epubCustomFontService.sanitizeFontName(customFont.fontName);
actualFontFamily = `"${sanitizedFontName}", sans-serif`;
fontFaceRule = `@font-face {
font-family: "${sanitizedFontName}";
src: url("${blobUrl}") format("truetype");
font-weight: normal;
font-style: normal;
font-display: swap;
}`;
}
} else {
actualFontFamily = fontFamily;
}
}
const fontFamilyRule = actualFontFamily ? `
body {
font-family: ${actualFontFamily} !important;
}
body * {
font-family: inherit !important;
}` : '';
return `
${fontFaceRule}
@namespace epub "http://www.idpf.org/2007/ops";
@media print {
html {
column-width: auto !important;
height: auto !important;
width: auto !important;
}
}
@media screen {
html {
color-scheme: light dark;
color: ${theme.fg || theme.light.fg};
font-size: ${fontSize}px;
}${fontFamilyRule}
a:any-link {
color: ${theme.link || theme.light.link};
text-decoration-color: light-dark(
color-mix(in srgb, currentColor 20%, transparent),
color-mix(in srgb, currentColor 40%, transparent));
text-underline-offset: .1em;
}
a:any-link:hover {
text-decoration-color: unset;
}
@media (prefers-color-scheme: dark) {
html {
color: ${theme.fg || theme.dark.fg};
}
a:any-link {
color: ${theme.link || theme.dark.link};
}
}
aside[epub|type~="footnote"] {
display: none;
}
}
html {
line-height: ${lineHeight};
hanging-punctuation: allow-end last;
orphans: 2;
widows: 2;
}
[align="left"] { text-align: left; }
[align="right"] { text-align: right; }
[align="center"] { text-align: center; }
[align="justify"] { text-align: justify; }
:is(hgroup, header) p {
text-align: unset;
hyphens: unset;
}
h1, h2, h3, h4, h5, h6, hgroup, th {
text-wrap: balance;
}
pre {
white-space: pre-wrap !important;
tab-size: 2;
}
@media screen and (prefers-color-scheme: light) {
${(theme.bg || theme.light.bg) !== '#ffffff' ? `
html, body {
color: ${theme.fg || theme.light.fg} !important;
background: none !important;
}
body * {
color: inherit !important;
border-color: currentColor !important;
background-color: ${theme.bg || theme.light.bg} !important;
}
a:any-link {
color: ${theme.link || theme.light.link} !important;
}
svg, img {
background-color: transparent !important;
mix-blend-mode: multiply;
}
.${mediaActiveClass}, .${mediaActiveClass} * {
color: ${theme.fg || theme.light.fg} !important;
background: color-mix(in hsl, ${theme.fg || theme.light.fg}, #fff 50%) !important;
background: color-mix(in hsl, ${theme.fg || theme.light.fg}, ${theme.bg || theme.light.bg} 85%) !important;
}` : ''}
}
@media screen and (prefers-color-scheme: dark) {
html, body {
color: ${theme.fg || theme.dark.fg} !important;
background: none !important;
}
body * {
color: inherit !important;
border-color: currentColor !important;
background-color: ${theme.bg || theme.dark.bg} !important;
}
a:any-link {
color: ${theme.link || theme.dark.link} !important;
}
.${mediaActiveClass}, .${mediaActiveClass} * {
color: ${theme.fg || theme.dark.fg} !important;
background: color-mix(in hsl, ${theme.fg || theme.dark.fg}, #000 50%) !important;
background: color-mix(in hsl, ${theme.fg || theme.dark.fg}, ${theme.bg || theme.dark.bg} 75%) !important;
}
}
p, li, blockquote, dd {
line-height: ${lineHeight};
text-align: ${justify ? 'justify' : 'start'} !important;
hyphens: ${hyphenate ? 'auto' : 'none'};
}
${overrideFont ? '' : ''}
${userStylesheet}
`;
}
private parseCustomFontId(fontFamily: string): number | null {
if (fontFamily.startsWith('custom:')) {
const id = parseInt(fontFamily.substring(7), 10);
return !isNaN(id) ? id : null;
}
const id = parseInt(fontFamily, 10);
return !isNaN(id) && id.toString() === fontFamily ? id : null;
}
applyStylesToRenderer(renderer: any, state: ReaderState): void {
if (!renderer) return;
renderer.setAttribute('max-column-count', state.maxColumnCount);
renderer.setAttribute('gap', `${state.gap * 100}%`);
renderer.setAttribute('max-inline-size', `${state.maxInlineSize}px`);
renderer.setAttribute('max-block-size', `${state.maxBlockSize}px`);
if (typeof renderer.setStyles === 'function') {
const css = this.generateCSS(state);
renderer.setStyles(css);
}
if (state.flow === 'paginated') {
renderer.setAttribute('margin', '40px');
} else {
renderer.removeAttribute('margin');
}
}
}
@@ -0,0 +1,78 @@
export interface ThemeMode {
fg: string;
bg: string;
link: string;
}
export interface Theme {
name: string;
label: string;
light: ThemeMode;
dark: ThemeMode;
fg?: string;
bg?: string;
link?: string;
}
export const themes: Theme[] = [
{
name: 'default', label: 'Default',
light: {fg: '#000000', bg: '#ffffff', link: '#0066cc'},
dark: {fg: '#e0e0e0', bg: '#222222', link: '#77bbee'},
},
{
name: 'gray', label: 'Gray',
light: {fg: '#222222', bg: '#e0e0e0', link: '#4488cc'},
dark: {fg: '#c6c6c6', bg: '#444444', link: '#88ccee'},
},
{
name: 'sepia', label: 'Sepia',
light: {fg: '#5b4636', bg: '#f1e8d0', link: '#008b8b'},
dark: {fg: '#ffd595', bg: '#342e25', link: '#48d1cc'},
},
{
name: 'crimson', label: 'Crimson',
light: {fg: '#212529', bg: '#ffffff', link: '#dd0031'},
dark: {fg: '#dee2e6', bg: '#343a40', link: '#ff4081'},
},
{
name: 'meadow', label: 'Meadow',
light: {fg: '#232c16', bg: '#d7dbbd', link: '#177b4d'},
dark: {fg: '#d8deba', bg: '#333627', link: '#a6d608'},
},
{
name: 'rosewood', label: 'Rosewood',
light: {fg: '#4e1609', bg: '#f0d1d5', link: '#de3838'},
dark: {fg: '#e5c4c8', bg: '#462f32', link: '#ff646e'},
},
{
name: 'azure', label: 'Azure',
light: {fg: '#262d48', bg: '#cedef5', link: '#2d53e5'},
dark: {fg: '#babee1', bg: '#282e47', link: '#ff646e'},
},
{
name: 'dawnlight', label: 'Dawnlight',
light: {fg: '#586e75', bg: '#fdf6e3', link: '#268bd2'},
dark: {fg: '#93a1a1', bg: '#002b36', link: '#268bd2'},
},
{
name: 'ember', label: 'Ember',
light: {fg: '#3c3836', bg: '#fbf1c7', link: '#076678'},
dark: {fg: '#ebdbb2', bg: '#282828', link: '#83a598'},
},
{
name: 'aurora', label: 'Aurora',
light: {fg: '#2e3440', bg: '#eceff4', link: '#5e81ac'},
dark: {fg: '#d8dee9', bg: '#2e3440', link: '#88c0d0'},
},
{
name: 'ocean', label: 'Ocean',
light: {fg: '#0a4d4d', bg: '#e0f7fa', link: '#00838f'},
dark: {fg: '#b2dfdb', bg: '#263238', link: '#4dd0e1'},
},
{
name: 'mist', label: 'Mist',
light: {fg: '#4a148c', bg: '#f3e5f5', link: '#7b1fa2'},
dark: {fg: '#c7b6dd', bg: '#3a3150', link: '#b39ddb'},
},
];
@@ -0,0 +1,329 @@
import {Injectable} from '@angular/core';
import {defer, from, Observable, of, Subject, throwError, timer} from 'rxjs';
import {catchError, map, switchMap} from 'rxjs/operators';
import {PageInfo, ReaderHeaderFooterUtil, ThemeInfo} from '../utils/reader-header-footer.util';
export interface ViewEvent {
type: 'load' | 'relocate' | 'error' | 'middle-single-tap';
detail?: any;
}
interface TocItem {
label: string;
href: string;
subitems?: TocItem[];
}
export interface BookMetadata {
title?: string;
authors?: string[];
language?: string;
publisher?: string;
description?: string;
identifier?: string;
coverUrl?: string;
[key: string]: any;
}
@Injectable({
providedIn: 'root'
})
export class ReaderViewManagerService {
private readonly DOUBLE_CLICK_INTERVAL_MS = 300;
private readonly LONG_HOLD_THRESHOLD_MS = 500;
private readonly LEFT_ZONE_PERCENT = 0.3;
private readonly RIGHT_ZONE_PERCENT = 0.7;
private view: any;
private isNavigating = false;
private lastClickTime = 0;
private lastClickZone: 'left' | 'middle' | 'right' | null = null;
private longHoldTimeout: ReturnType<typeof setTimeout> | null = null;
private keydownHandler?: (event: KeyboardEvent) => void;
private clickedDocs = new WeakSet<Document>();
private eventSubject = new Subject<ViewEvent>();
public events$ = this.eventSubject.asObservable();
createView(container: HTMLElement): void {
this.view = document.createElement('foliate-view');
this.view.style.width = '100%';
this.view.style.height = '100%';
this.view.style.display = 'block';
container.appendChild(this.view);
this.attachEventListeners();
this.attachKeyboardHandler();
}
loadEpub(epubPath: string): Observable<void> {
if (!this.view) {
return throwError(() => new Error('View not created'));
}
return timer(100).pipe(
switchMap(() => from(fetch(epubPath))),
switchMap(response => {
if (!response.ok) {
throw new Error(`EPUB not found: ${response.status}`);
}
return from(response.blob());
}),
switchMap(blob => {
const file = new File([blob], epubPath.split('/').pop() || 'book.epub', {
type: 'application/epub+zip'
});
return from(this.view.open(file) as Promise<void>);
}),
map(() => undefined),
catchError(err => throwError(() => err))
);
}
destroy(): void {
if (this.keydownHandler) {
document.removeEventListener('keydown', this.keydownHandler);
this.keydownHandler = undefined;
}
this.view?.remove();
this.view = null;
}
goTo(target?: string | number | null): Observable<void> {
const resolvedTarget = target ?? 0;
if (!this.view) {
return of(undefined);
}
return defer(() =>
from(this.view.goTo(resolvedTarget) as Promise<void>)
).pipe(
map(() => undefined)
);
}
goToSection(index: number): Observable<void> {
return this.goTo(index);
}
goToFraction(fraction: number): Observable<void> {
if (!this.view) {
return of(undefined);
}
return defer(() => from(this.view.goToFraction(fraction) as Promise<void>)).pipe(
map(() => undefined)
);
}
prev(): void {
this.view?.prev();
}
next(): void {
this.view?.next();
}
getRenderer(): any {
return this.view?.renderer;
}
updateHeadersAndFooters(chapterName: string, pageInfo?: PageInfo, theme?: ThemeInfo): void {
const renderer = this.getRenderer();
ReaderHeaderFooterUtil.updateHeadersAndFooters(renderer, chapterName, pageInfo, theme);
}
getChapters(): TocItem[] {
if (!this.view?.book?.toc) return [];
const mapToc = (items: any[]): TocItem[] =>
items.map(item => ({
label: item.label,
href: item.href,
subitems: item.subitems?.length ? mapToc(item.subitems) : undefined
}));
return mapToc(this.view.book.toc);
}
getSectionFractions(): number[] {
if (!this.view?.getSectionFractions) return [];
return this.view.getSectionFractions();
}
getMetadata(): Observable<BookMetadata> {
if (!this.view?.book?.metadata) {
return of({});
}
const {metadata} = this.view.book;
return this.getCoverUrl().pipe(
map(coverUrl => ({
title: metadata.title,
authors: metadata.authors,
language: metadata.language,
publisher: metadata.publisher,
description: metadata.description,
identifier: metadata.identifier,
coverUrl,
...metadata
}))
);
}
getCover(): Observable<Blob | null> {
if (!this.view?.book?.getCover) {
return of(null);
}
return defer(() => {
const coverPromise = this.view.book.getCover();
return coverPromise ? from(coverPromise as Promise<Blob | null>) : of(null);
});
}
getCoverUrl(): Observable<string | null> {
return this.getCover().pipe(
map(blob => blob ? URL.createObjectURL(blob) : null)
);
}
private attachEventListeners(): void {
this.view.addEventListener('load', (e: any) => {
this.eventSubject.next({type: 'load', detail: e.detail});
if (e.detail?.doc) {
if (this.keydownHandler) {
e.detail.doc.addEventListener('keydown', this.keydownHandler);
}
this.attachIframeEventHandlers(e.detail.doc);
}
});
this.view.addEventListener('relocate', (e: any) => {
this.eventSubject.next({type: 'relocate', detail: e.detail});
});
this.view.addEventListener('error', (e: any) => {
this.eventSubject.next({type: 'error', detail: e.detail});
});
window.addEventListener('message', (event) => {
if (event.data?.type === 'iframe-click') {
this.handleIframeClickMessage(event.data);
}
});
}
private attachKeyboardHandler(): void {
this.keydownHandler = (event: KeyboardEvent) => {
const k = event.key;
if (k === 'ArrowLeft' || k === 'h' || k === 'PageUp') {
this.prev();
event.preventDefault();
} else if (k === 'ArrowRight' || k === 'l' || k === 'PageDown') {
this.next();
event.preventDefault();
}
};
document.addEventListener('keydown', this.keydownHandler);
}
private attachIframeEventHandlers(doc: Document): void {
if (this.clickedDocs.has(doc)) {
return;
}
this.clickedDocs.add(doc);
doc.addEventListener('mousedown', (event: MouseEvent) => {
this.longHoldTimeout = setTimeout(() => {
this.longHoldTimeout = null;
}, this.LONG_HOLD_THRESHOLD_MS);
}, true);
doc.addEventListener('click', (event: MouseEvent) => {
const iframe = doc.defaultView?.frameElement as HTMLIFrameElement | null;
if (!iframe) return;
const iframeRect = iframe.getBoundingClientRect();
const viewportX = iframeRect.left + event.clientX;
const viewportY = iframeRect.top + event.clientY;
window.postMessage({
type: 'iframe-click',
clientX: viewportX,
clientY: viewportY,
iframeLeft: iframeRect.left,
iframeWidth: iframeRect.width,
eventClientX: event.clientX,
target: (event.target as HTMLElement)?.tagName
}, '*');
}, true);
}
private handleIframeClickMessage(data: any): void {
const now = Date.now();
const timeSinceLastClick = now - this.lastClickTime;
const viewRect = this.view.getBoundingClientRect();
const x = data.clientX - viewRect.left;
const width = viewRect.width;
const leftThreshold = width * this.LEFT_ZONE_PERCENT;
const rightThreshold = width * this.RIGHT_ZONE_PERCENT;
let currentZone: 'left' | 'middle' | 'right';
if (x < leftThreshold) {
currentZone = 'left';
} else if (x > rightThreshold) {
currentZone = 'right';
} else {
currentZone = 'middle';
}
if (timeSinceLastClick < this.DOUBLE_CLICK_INTERVAL_MS && this.lastClickZone === currentZone) {
this.lastClickTime = now;
this.lastClickZone = currentZone;
if (currentZone !== 'middle') {
}
return;
}
this.lastClickTime = now;
this.lastClickZone = currentZone;
setTimeout(() => {
if (Date.now() - this.lastClickTime >= this.DOUBLE_CLICK_INTERVAL_MS) {
this.processIframeClick(data);
}
}, this.DOUBLE_CLICK_INTERVAL_MS);
}
private processIframeClick(data: any): void {
if (!this.longHoldTimeout) {
return;
}
if (this.isNavigating) {
return;
}
const viewRect = this.view.getBoundingClientRect();
const x = data.clientX - viewRect.left;
const width = viewRect.width;
const leftThreshold = width * this.LEFT_ZONE_PERCENT;
const rightThreshold = width * this.RIGHT_ZONE_PERCENT;
if (x < leftThreshold) {
this.isNavigating = true;
this.prev();
setTimeout(() => this.isNavigating = false, 300);
} else if (x > rightThreshold) {
this.isNavigating = true;
this.next();
setTimeout(() => this.isNavigating = false, 300);
} else {
this.eventSubject.next({type: 'middle-single-tap'});
}
}
}
@@ -0,0 +1,93 @@
export interface HeaderFooterVisibilityState {
headerVisible: boolean;
footerVisible: boolean;
}
export class ReaderHeaderFooterVisibilityManager {
private isPinned = false;
private mouseY = 0;
private readonly HEADER_HEIGHT = 20;
private readonly FOOTER_HEIGHT = 20;
private readonly TRIGGER_ZONE = 20;
private headerVisible = false;
private footerVisible = false;
private onStateChangeCallback?: (state: HeaderFooterVisibilityState) => void;
constructor(private windowHeight: number) {
}
onStateChange(callback: (state: HeaderFooterVisibilityState) => void): void {
this.onStateChangeCallback = callback;
}
updateWindowHeight(height: number): void {
this.windowHeight = height;
}
handleMouseMove(mouseY: number): void {
this.mouseY = mouseY;
this.updateVisibility();
}
handleMouseLeave(): void {
if (!this.isPinned) {
this.setHeaderVisible(false);
this.setFooterVisible(false);
this.notifyStateChange();
}
}
togglePinned(): void {
this.isPinned = !this.isPinned;
this.updateVisibility();
}
getVisibilityState(): HeaderFooterVisibilityState {
return {
headerVisible: this.headerVisible,
footerVisible: this.footerVisible
};
}
private updateVisibility(): void {
if (
this.mouseY <= this.TRIGGER_ZONE ||
(this.mouseY <= this.HEADER_HEIGHT && this.headerVisible) ||
this.isPinned
) {
this.setHeaderVisible(true);
} else if (this.mouseY > this.HEADER_HEIGHT) {
this.setHeaderVisible(this.isPinned);
}
const footerTop = this.windowHeight - this.FOOTER_HEIGHT;
if (
this.mouseY >= this.windowHeight - this.TRIGGER_ZONE ||
(this.mouseY >= footerTop && this.footerVisible) ||
this.isPinned
) {
this.setFooterVisible(true);
} else if (this.mouseY < footerTop) {
this.setFooterVisible(this.isPinned);
}
this.notifyStateChange();
}
private setHeaderVisible(visible: boolean): void {
this.headerVisible = visible;
}
private setFooterVisible(visible: boolean): void {
this.footerVisible = visible;
}
private notifyStateChange(): void {
if (this.onStateChangeCallback) {
this.onStateChangeCallback(this.getVisibilityState());
}
}
}
@@ -0,0 +1,130 @@
export interface PageInfo {
percentCompleted: number;
sectionTimeText: string;
}
export interface ThemeInfo {
fg: string;
bg: string;
}
export class ReaderHeaderFooterUtil {
private static readonly DEFAULT_FONT_SIZE = '0.875rem';
static updateHeadersAndFooters(renderer: any, chapterName: string, pageInfo?: PageInfo, theme?: ThemeInfo): void {
if (!renderer) {
return;
}
const columnCount = renderer.heads?.length || 0;
const isSingleColumn = columnCount === 1;
this.updateHeaders(renderer, chapterName, isSingleColumn, theme);
this.updateFooters(renderer, pageInfo, isSingleColumn, theme);
}
private static updateHeaders(renderer: any, chapterName: string, isSingleColumn: boolean, theme?: ThemeInfo): void {
if (!renderer.heads || !Array.isArray(renderer.heads) || renderer.heads.length === 0) {
return;
}
const headerStyle = this.buildStyle(theme);
renderer.heads.forEach((headElement: HTMLElement, index: number) => {
if (headElement) {
headElement.style.visibility = 'visible';
const headerContent = this.createHeaderContent(chapterName, isSingleColumn, index, headerStyle);
headElement.replaceChildren(headerContent);
}
});
}
private static updateFooters(renderer: any, pageInfo: PageInfo | undefined, isSingleColumn: boolean, theme?: ThemeInfo): void {
if (!renderer.feet || !Array.isArray(renderer.feet) || renderer.feet.length === 0 || !pageInfo) {
return;
}
const footerStyle = this.buildStyle(theme);
renderer.feet.forEach((footElement: HTMLElement, index: number) => {
if (footElement) {
const footerContent = this.createFooterContent(pageInfo, isSingleColumn, index, renderer.feet.length, footerStyle);
footElement.replaceChildren(footerContent);
}
});
}
private static buildStyle(theme?: ThemeInfo): string {
const baseStyle = `width: 100%; display: flex; justify-content: space-between; align-items: center; font-size: ${this.DEFAULT_FONT_SIZE}; font-family: inherit;`;
if (theme) {
return `${baseStyle} color: ${theme.fg};`;
}
return baseStyle;
}
private static createHeaderContent(chapterName: string, isSingleColumn: boolean, index: number, style: string): HTMLElement {
const headerContent = document.createElement('div');
headerContent.style.cssText = style;
if (isSingleColumn) {
const spacer = document.createElement('span');
const chapterSpan = document.createElement('span');
chapterSpan.textContent = chapterName || '';
chapterSpan.style.textAlign = 'right';
headerContent.style.justifyContent = 'left';
headerContent.appendChild(spacer);
headerContent.appendChild(chapterSpan);
} else {
if (index === 0) {
const chapterSpan = document.createElement('span');
chapterSpan.textContent = chapterName || '';
chapterSpan.style.textAlign = 'left';
headerContent.appendChild(chapterSpan);
}
}
return headerContent;
}
private static createFooterContent(pageInfo: PageInfo, isSingleColumn: boolean, index: number, totalColumns: number, style: string): HTMLElement {
const footerContent = document.createElement('div');
footerContent.style.cssText = style;
const text = 'Time remaining in section: ' + (pageInfo.sectionTimeText ?? '0s');
if (isSingleColumn) {
const timeSpan = document.createElement('span');
timeSpan.textContent = text;
timeSpan.style.textAlign = 'left';
const progressSpan = document.createElement('span');
progressSpan.textContent = `${pageInfo.percentCompleted}%`;
progressSpan.style.textAlign = 'right';
footerContent.appendChild(timeSpan);
footerContent.appendChild(progressSpan);
} else {
if (index === 0) {
const timeSpan = document.createElement('span');
timeSpan.textContent = text;
timeSpan.style.textAlign = 'left';
footerContent.appendChild(timeSpan);
const spacer = document.createElement('span');
footerContent.appendChild(spacer);
} else if (index === totalColumns - 1) {
const spacer = document.createElement('span');
footerContent.appendChild(spacer);
const progressSpan = document.createElement('span');
progressSpan.textContent = `${pageInfo.percentCompleted}%`;
progressSpan.style.textAlign = 'right';
footerContent.appendChild(progressSpan);
}
}
return footerContent;
}
}
@@ -695,7 +695,7 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
this.progressPercentage = Math.round(percentage * 1000) / 10;
}
this.bookService.saveEpubProgress(this.epub.id, cfi, Math.round(percentage * 1000) / 10).subscribe();
//this.bookService.saveEpubProgress(this.epub.id, cfi, '', Math.round(percentage * 1000) / 10).subscribe();
this.readingSessionService.updateProgress(
location.start.cfi,
@@ -0,0 +1,123 @@
import {Injectable, inject} from '@angular/core';
import {CustomFontService} from '../../../../shared/service/custom-font.service';
import {CustomFont} from '../../../../shared/model/custom-font.model';
import {Observable, forkJoin, of, from} from 'rxjs';
import {map, switchMap, tap, catchError} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class EpubCustomFontService {
private customFontService = inject(CustomFontService);
private customFonts: CustomFont[] = [];
private customFontBlobUrls = new Map<number, string>();
loadAndCacheFonts(): Observable<CustomFont[]> {
return this.customFontService.getUserFonts().pipe(
tap(fonts => this.customFonts = fonts),
switchMap(fonts =>
from(this.customFontService.loadAllFonts(fonts)).pipe(
switchMap(() => this.cacheCustomFontsAsBlobs(fonts)),
map(() => fonts)
)
),
catchError(() => of([]))
);
}
private cacheCustomFontsAsBlobs(fonts: CustomFont[]): Observable<void> {
if (fonts.length === 0) {
return of(undefined);
}
const requests = fonts.map(font =>
this.cacheSingleFont(font).pipe(
catchError(() => of(undefined))
)
);
return forkJoin(requests).pipe(map(() => undefined));
}
private cacheSingleFont(font: CustomFont): Observable<void> {
const fontUrl = this.customFontService.getFontUrl(font.id);
const fontUrlWithToken = this.customFontService.appendToken(fontUrl);
return from(fetch(fontUrlWithToken)).pipe(
switchMap(response => from(response.blob())),
tap(blob => {
const blobUrl = URL.createObjectURL(blob);
this.customFontBlobUrls.set(font.id, blobUrl);
}),
map(() => undefined)
);
}
getBlobUrl(fontId: number): string | undefined {
return this.customFontBlobUrls.get(fontId);
}
getCustomFonts(): CustomFont[] {
return this.customFonts;
}
getCustomFontById(fontId: number): CustomFont | undefined {
return this.customFonts.find(f => f.id === fontId);
}
cleanup(): void {
this.customFontBlobUrls.forEach(url => URL.revokeObjectURL(url));
this.customFontBlobUrls.clear();
}
sanitizeFontName(fontName: string): string {
return fontName.replace(/\.(ttf|otf|woff|woff2)$/i, '').replace(/["'()]/g, '').replace(/\s+/g, '-');
}
getFontFamilyForPreview(fontValue: string): string {
if (fontValue.startsWith('custom:')) {
const id = parseInt(fontValue.substring(7), 10);
if (!isNaN(id)) {
const customFont = this.getCustomFontById(id);
if (customFont) {
return `"${this.sanitizeFontName(customFont.fontName)}", sans-serif`;
}
}
}
return fontValue;
}
generateCustomFontsStylesheet(): string {
const customFonts = this.getCustomFonts();
if (customFonts.length === 0) return '';
let css = '';
customFonts.forEach(font => {
const blobUrl = this.getBlobUrl(font.id);
if (blobUrl) {
const sanitizedName = this.sanitizeFontName(font.fontName);
css += `
@font-face {
font-family: "${sanitizedName}";
src: url("${blobUrl}") format("truetype");
font-weight: normal;
font-style: normal;
font-display: swap;
}
`;
}
});
return css;
}
injectCustomFontsStylesheet(renderer: any, document: Document): void {
const css = this.generateCustomFontsStylesheet();
if (css) {
const styleEl = renderer.createElement('style');
styleEl.textContent = css;
renderer.appendChild(document.head, styleEl);
}
}
}
@@ -180,10 +180,12 @@
display: flex;
align-items: center;
gap: 1rem;
border: 1px solid var(--p-content-border-color);
border-radius: 8px;
padding: 1rem;
background: var(--p-content-background);
border-radius: 8px;
background: rgba(220, 38, 38, 0.1);
border: 1px solid rgba(220, 38, 38, 0.3);
color: var(--p-red-400);
max-width: 500px;
margin: 0 1rem;
@media (max-width: 768px) {
@@ -191,21 +193,24 @@
}
.pi {
font-size: 1.5rem;
color: var(--p-text-muted-color);
font-size: 1.25rem;
flex-shrink: 0;
color: var(--p-red-300);
}
}
.access-denied-content {
h3 {
margin: 0 0 0.25rem 0;
margin: 0 0 0.5rem 0;
font-size: 1rem;
color: var(--p-text-color);
font-weight: 600;
color: var(--p-red-300);
}
p {
margin: 0;
color: var(--p-text-muted-color);
font-size: 0.875rem;
line-height: 1.5;
color: var(--p-red-400);
}
}
@@ -15,7 +15,13 @@
</div>
</div>
<!-- EPUB Settings -->
<div class="info-notice unsupported-formats-note" style="margin-bottom: 1rem;">
<i class="pi pi-info-circle"></i>
<div>
<strong>Note:</strong> Writing metadata is <b>not supported</b> for FB2, AZW3, and MOBI formats.
</div>
</div>
<div class="setting-item">
<div class="setting-info">
<label class="setting-label">Write Metadata to EPUB</label>
@@ -55,7 +61,6 @@
</div>
</div>
<!-- CBX Settings -->
<div class="setting-item">
<div class="setting-info">
<label class="setting-label">Write Metadata to CBX</label>
@@ -95,7 +100,6 @@
</div>
</div>
<!-- PDF Settings -->
<div class="setting-item">
<div class="setting-info">
<label class="setting-label">Write Metadata to PDF</label>
@@ -213,3 +213,29 @@
}
}
}
.info-notice.unsupported-formats-note {
background: color-mix(
in srgb,
var(--p-surface-900) 90%,
var(--p-blue-600) 10%
);
border-left: 4px solid var(--p-blue-400);
color: var(--p-text-color);
padding: 0.75rem 1rem;
border-radius: 8px;
display: flex;
align-items: flex-start;
gap: 0.75rem;
.pi-info-circle {
color: var(--p-blue-400);
margin-top: 0.15rem;
flex-shrink: 0;
}
strong {
color: var(--p-blue-300);
font-weight: 700;
}
}
@@ -87,11 +87,11 @@ export class MetadataPersistenceSettingsComponent implements OnInit {
saveToOriginalFile: {
epub: {
enabled: persistenceSettings.saveToOriginalFile?.epub?.enabled ?? false,
maxFileSizeInMb: persistenceSettings.saveToOriginalFile?.epub?.maxFileSizeInMb ?? 100
maxFileSizeInMb: persistenceSettings.saveToOriginalFile?.epub?.maxFileSizeInMb ?? 250
},
pdf: {
enabled: persistenceSettings.saveToOriginalFile?.pdf?.enabled ?? false,
maxFileSizeInMb: persistenceSettings.saveToOriginalFile?.pdf?.maxFileSizeInMb ?? 100
maxFileSizeInMb: persistenceSettings.saveToOriginalFile?.pdf?.maxFileSizeInMb ?? 250
},
cbx: {
enabled: persistenceSettings.saveToOriginalFile?.cbx?.enabled ?? false,
@@ -1,125 +1,289 @@
<div class="epub-preferences-container">
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Theme</label>
<div class="theme-selector">
@for (theme of themes; track theme) {
<button
type="button"
class="theme-option"
[class.selected]="selectedTheme === theme.key"
[style.background-color]="theme.color"
(click)="selectedTheme = theme.key"
[attr.aria-label]="theme.name"
[pTooltip]="theme.name"
tooltipPosition="bottom">
@if (selectedTheme === theme.key) {
<i class="pi pi-check"></i>
}
</button>
}
<div class="settings-group">
<h3 class="group-title">Appearance</h3>
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Theme</label>
<div class="theme-selector">
@for (theme of themes; track theme) {
<button
type="button"
class="theme-option"
[class.selected]="selectedTheme === theme.name"
(click)="selectedTheme = theme.name"
[attr.aria-label]="theme.label"
[pTooltip]="theme.label"
tooltipPosition="bottom">
<span class="theme-colors">
<span class="theme-color" [style.background-color]="theme.light.bg"></span>
<span class="theme-color" [style.background-color]="theme.dark.bg"></span>
</span>
@if (selectedTheme === theme.name) {
<i class="pi pi-check"></i>
}
</button>
}
</div>
</div>
<p class="setting-description">
Select a color scheme to match your reading environment and comfort.
</p>
</div>
<p class="setting-description">
Choose the visual theme for EPUB reading experience.
</p>
</div>
</div>
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Font</label>
<div class="button-group">
@for (font of fonts; track font) {
<button
type="button"
class="option-button font-button"
[class.selected]="selectedFont === font.key"
[class.separator]="font.key === 'separator'"
[attr.data-font]="font.key"
[disabled]="font.key === 'separator'"
(click)="selectedFont = font.key"
[pTooltip]="font.name"
tooltipPosition="bottom">
<span class="option-text"
[style.font-family]="font.key && font.key.startsWith('custom:') ? getCustomFontName(font.key) : null">
{{ font.displayName }}
</span>
</button>
}
@if (!customFontsReady) {
<p-skeleton width="3.5rem" height="2.5rem" borderRadius="6px"></p-skeleton>
}
</div>
</div>
<p class="setting-description">
Select the font family for text display.
</p>
</div>
</div>
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Flow</label>
<div class="button-group">
@for (flow of flowOptions; track flow) {
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Dark Mode</label>
<div class="button-group">
<button
type="button"
class="option-button"
[class.selected]="selectedFlow === flow.key"
(click)="selectedFlow = flow.key">
<i [class]="flow.icon"></i>
<span class="option-text">{{ flow.name }}</span>
[class.selected]="!isDark"
(click)="isDark = false">
<i class="pi pi-sun"></i>
<span class="option-text">Light</span>
</button>
}
</div>
</div>
<p class="setting-description">
Configure text flow and reading direction.
</p>
</div>
</div>
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Page Spread</label>
<div class="button-group">
@for (spread of spreadOptions; track spread) {
<button
type="button"
class="option-button"
[class.selected]="selectedSpread === spread.key"
(click)="selectedSpread = spread.key">
<i [class]="spread.icon"></i>
<span class="option-text">{{ spread.name }}</span>
[class.selected]="isDark"
(click)="isDark = true">
<i class="pi pi-moon"></i>
<span class="option-text">Dark</span>
</button>
}
</div>
</div>
<p class="setting-description">
Switch between light and dark backgrounds for day or night reading.
</p>
</div>
<p class="setting-description">
Choose between single page or double page spread view.
</p>
</div>
</div>
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Font Size</label>
<div class="font-size-controls">
<p-button icon="pi pi-minus" size="small" rounded (click)="decreaseFontSize()"></p-button>
<span class="font-size-value">{{ fontSize }}%</span>
<p-button icon="pi pi-plus" size="small" rounded (click)="increaseFontSize()"></p-button>
<div class="settings-group">
<h3 class="group-title">Typography</h3>
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Font Family</label>
<div class="button-group">
@for (font of fonts; track font) {
<button
type="button"
class="option-button font-button"
[class.selected]="selectedFont === font.key"
[class.separator]="font.key === 'separator'"
[attr.data-font]="font.key"
[disabled]="font.key === 'separator'"
(click)="selectedFont = font.key"
[pTooltip]="font.name"
tooltipPosition="bottom">
<span class="option-text" [style.font-family]="font.key && font.key.startsWith('custom:') ? getCustomFontName(font.key) : null">
{{ font.displayName }}
</span>
</button>
}
@if (!customFontsReady) {
<p-skeleton width="3.5rem" height="2.5rem" borderRadius="6px"></p-skeleton>
}
</div>
</div>
<p class="setting-description">
Choose a typeface that best suits your reading preference.
</p>
</div>
</div>
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Font Size</label>
<div class="font-size-controls">
<p-button icon="pi pi-minus" size="small" rounded outlined (click)="decreaseFontSize()"></p-button>
<span class="font-size-value">{{ fontSize }}pt</span>
<p-button icon="pi pi-plus" size="small" rounded outlined (click)="increaseFontSize()"></p-button>
</div>
</div>
<p class="setting-description">
Increase or decrease text size in points for optimal readability.
</p>
</div>
</div>
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Line Height</label>
<div class="font-size-controls">
<p-button icon="pi pi-minus" size="small" rounded outlined (click)="decreaseLineHeight()"></p-button>
<span class="font-size-value">{{ lineHeight.toFixed(1) }}</span>
<p-button icon="pi pi-plus" size="small" rounded outlined (click)="increaseLineHeight()"></p-button>
</div>
</div>
<p class="setting-description">
Adjust vertical spacing between lines for better legibility.
</p>
</div>
</div>
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Text Justification</label>
<div class="button-group">
<button
type="button"
class="option-button"
[class.selected]="!justify"
(click)="justify = false">
<i class="pi pi-align-left"></i>
<span class="option-text">Left</span>
</button>
<button
type="button"
class="option-button"
[class.selected]="justify"
(click)="justify = true">
<i class="pi pi-align-justify"></i>
<span class="option-text">Justified</span>
</button>
</div>
</div>
<p class="setting-description">
Align text to the left or justify it for a clean edge on both sides.
</p>
</div>
</div>
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Hyphenation</label>
<div class="button-group">
<button
type="button"
class="option-button"
[class.selected]="!hyphenate"
(click)="hyphenate = false">
<i class="pi pi-times"></i>
<span class="option-text">Off</span>
</button>
<button
type="button"
class="option-button"
[class.selected]="hyphenate"
(click)="hyphenate = true">
<i class="pi pi-check"></i>
<span class="option-text">On</span>
</button>
</div>
</div>
<p class="setting-description">
Enable to break long words at line ends for a smoother text flow.
</p>
</div>
</div>
</div>
<div class="settings-group">
<h3 class="group-title">Layout</h3>
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Flow</label>
<div class="button-group">
<button
type="button"
class="option-button"
[class.selected]="flow === 'paginated'"
(click)="flow = 'paginated'">
<i class="pi pi-clone"></i>
<span class="option-text">Paginated</span>
</button>
<button
type="button"
class="option-button"
[class.selected]="flow === 'scrolled'"
(click)="flow = 'scrolled'">
<i class="pi pi-arrows-v"></i>
<span class="option-text">Scrolled</span>
</button>
</div>
</div>
<p class="setting-description">
Choose between paginated (page-by-page) or continuous scrolling flow.
</p>
</div>
</div>
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Max Columns</label>
<div class="font-size-controls">
<p-button icon="pi pi-minus" size="small" rounded outlined (click)="maxColumnCount = maxColumnCount > 1 ? maxColumnCount - 1 : 1"></p-button>
<span class="font-size-value">{{ maxColumnCount }}</span>
<p-button icon="pi pi-plus" size="small" rounded outlined (click)="maxColumnCount = maxColumnCount < 4 ? maxColumnCount + 1 : 4"></p-button>
</div>
</div>
<p class="setting-description">
Set how many columns the text is split into on wide screens.
</p>
</div>
</div>
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Column Gap</label>
<div class="font-size-controls">
<p-button icon="pi pi-minus" size="small" rounded outlined (click)="decreaseGap()"></p-button>
<span class="font-size-value">{{ gap }}px</span>
<p-button icon="pi pi-plus" size="small" rounded outlined (click)="increaseGap()"></p-button>
</div>
</div>
<p class="setting-description">
Control the space between columns for a balanced layout.
</p>
</div>
</div>
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Max Width</label>
<div class="font-size-controls">
<p-button icon="pi pi-minus" size="small" rounded outlined (click)="decreaseMaxInlineSize()"></p-button>
<span class="font-size-value">{{ maxInlineSize }}px</span>
<p-button icon="pi pi-plus" size="small" rounded outlined (click)="increaseMaxInlineSize()"></p-button>
</div>
</div>
<p class="setting-description">
Limit the maximum width of the reading area for easier line tracking.
</p>
</div>
</div>
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Max Height</label>
<div class="font-size-controls">
<p-button icon="pi pi-minus" size="small" rounded outlined (click)="decreaseMaxBlockSize()"></p-button>
<span class="font-size-value">{{ maxBlockSize }}px</span>
<p-button icon="pi pi-plus" size="small" rounded outlined (click)="increaseMaxBlockSize()"></p-button>
</div>
</div>
<p class="setting-description">
Limit the maximum height of the reading area to fit your screen.
</p>
</div>
<p class="setting-description">
Adjust the text size for comfortable reading.
</p>
</div>
</div>
</div>
@@ -1,7 +1,25 @@
.epub-preferences-container {
display: flex;
flex-direction: column;
gap: 2rem;
}
.settings-group {
display: flex;
flex-direction: column;
gap: 1rem;
padding: 1.5rem;
border-radius: 0.75rem;
border: 1px solid color-mix(in srgb, var(--text-color) 10%, transparent);
.group-title {
font-size: 1.125rem;
font-weight: 600;
color: var(--p-text-color);
margin: 0 0 0.5rem 0;
padding-bottom: 0.75rem;
border-bottom: 1px solid color-mix(in srgb, var(--text-color) 10%, transparent);
}
}
.setting-item {
@@ -80,7 +98,7 @@
.font-size-controls {
display: flex;
align-items: center;
gap: 1rem;
gap: 0.5rem;
.font-size-value {
min-width: 3rem;
@@ -96,32 +114,70 @@
flex-wrap: wrap;
.theme-option {
width: 2.5rem;
height: 2.5rem;
border-radius: 0.375rem;
border: 1.5px solid transparent;
display: flex;
flex-direction: column;
align-items: center;
gap: 0.5rem;
background: color-mix(in srgb, var(--text-color) 5%, transparent);
color: var(--text-color);
cursor: pointer;
transition: all 0.2s ease;
position: relative;
display: flex;
align-items: center;
justify-content: center;
min-width: 48px;
.theme-colors {
display: flex;
gap: 0;
padding: 0;
border-radius: 0.5rem;
overflow: hidden;
border: 2px solid color-mix(in srgb, var(--text-color) 20%, transparent);
box-sizing: border-box;
width: 72px;
height: 36px;
background: none;
}
.theme-color {
width: 36px;
height: 36px;
display: inline-block;
border-radius: 0;
border: none;
margin: 0;
padding: 0;
}
i {
color: white;
font-size: 0.875rem;
font-weight: bold;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
position: absolute;
top: 4px;
right: 4px;
font-size: 0.75rem;
color: var(--primary-color);
margin-left: 0;
padding-left: 0;
}
&:hover {
transform: scale(1.1);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
.theme-colors {
border-color: color-mix(in srgb, var(--primary-color) 40%, transparent);
}
}
&.selected {
border-color: var(--primary-color);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--primary-color) 25%, transparent);
.theme-colors {
border-color: var(--primary-color);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--primary-color) 15%, transparent);
}
color: var(--primary-color);
background: color-mix(in srgb, var(--primary-color) 10%, transparent);
&:hover {
transform: translateY(-2px);
}
}
}
}
@@ -219,3 +275,4 @@
}
}
}
@@ -9,6 +9,7 @@ import {CustomFont} from '../../../../shared/model/custom-font.model';
import {skip, Subject, takeUntil} from 'rxjs';
import {addCustomFontsToDropdown} from '../../../../shared/util/custom-font.util';
import {Skeleton} from 'primeng/skeleton';
import {themes} from '../../../readers/ebook-reader/services/reader-themes';
@Component({
selector: 'app-epub-reader-preferences-component',
@@ -40,33 +41,7 @@ export class EpubReaderPreferencesComponent implements OnInit, OnDestroy {
{name: 'Monospace', displayName: 'Monospace', key: 'monospace'}
];
readonly flowOptions = [
{name: 'Paginated', key: 'paginated', icon: 'pi pi-book'},
{name: 'Scrolled', key: 'scrolled', icon: 'pi pi-sort-alt'}
];
readonly spreadOptions = [
{name: 'Single', key: 'single', icon: 'pi pi-file'},
{name: 'Double', key: 'double', icon: 'pi pi-copy'}
];
readonly themes = [
{name: 'White', key: 'white', color: '#FFFFFF'},
{name: 'Black', key: 'black', color: '#1A1A1A'},
{name: 'Grey', key: 'grey', color: '#4B5563'},
{name: 'Sepia', key: 'sepia', color: '#F4ECD8'},
{name: 'Green', key: 'green', color: '#D1FAE5'},
{name: 'Lavender', key: 'lavender', color: '#E9D5FF'},
{name: 'Cream', key: 'cream', color: '#FEF3C7'},
{name: 'Light Blue', key: 'light-blue', color: '#DBEAFE'},
{name: 'Peach', key: 'peach', color: '#FECACA'},
{name: 'Mint', key: 'mint', color: '#A7F3D0'},
{name: 'Dark Slate', key: 'dark-slate', color: '#1E293B'},
{name: 'Dark Olive', key: 'dark-olive', color: '#3F3F2C'},
{name: 'Dark Purple', key: 'dark-purple', color: '#3B2F4A'},
{name: 'Dark Teal', key: 'dark-teal', color: '#0F3D3E'},
{name: 'Dark Brown', key: 'dark-brown', color: '#3E2723'}
];
readonly themes = themes;
customFontsReady = false;
@@ -129,12 +104,13 @@ export class EpubReaderPreferencesComponent implements OnInit, OnDestroy {
}
private isCurrentlySelectedFontDeleted(newFonts: CustomFont[]): boolean {
const customFontId = this.userSettings.epubReaderSetting.customFontId;
if (!customFontId) {
const fontFamily = this.userSettings.ebookReaderSetting.fontFamily;
if (!fontFamily || !fontFamily.startsWith('custom:')) {
return false;
}
const fontStillExists = newFonts.some(font => font.id === customFontId);
const fontId = fontFamily.split(':')[1];
const fontStillExists = newFonts.some(font => font.id === parseInt(fontId, 10));
return !fontStillExists;
}
@@ -144,93 +120,176 @@ export class EpubReaderPreferencesComponent implements OnInit, OnDestroy {
}
get selectedTheme(): string | null {
return this.userSettings.epubReaderSetting.theme;
return this.userSettings.ebookReaderSetting.theme;
}
set selectedTheme(value: string | null) {
if (typeof value === "string") {
this.userSettings.epubReaderSetting.theme = value;
this.userSettings.ebookReaderSetting.theme = value;
}
this.readerPreferencesService.updatePreference(['epubReaderSetting', 'theme'], value);
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'theme'], value);
}
get selectedFont(): string | null {
// If customFontId is set, return the custom font key
if (this.userSettings.epubReaderSetting.customFontId) {
return `custom:${this.userSettings.epubReaderSetting.customFontId}`;
}
return this.userSettings.epubReaderSetting.font;
return this.userSettings.ebookReaderSetting.fontFamily;
}
set selectedFont(value: string | null) {
// Handle custom fonts
if (value && value.startsWith('custom:')) {
const fontIdStr = value.split(':')[1];
const fontId = parseInt(fontIdStr, 10);
if (isNaN(fontId)) {
console.error('Invalid custom font ID:', value);
return;
}
// Update both fields in local state
this.userSettings.epubReaderSetting.customFontId = fontId;
this.userSettings.epubReaderSetting.font = value;
if (typeof value === "string") {
this.userSettings.ebookReaderSetting.fontFamily = value;
} else {
// Clear customFontId and set font in local state
this.userSettings.epubReaderSetting.customFontId = null;
if (typeof value === "string") {
this.userSettings.epubReaderSetting.font = value;
} else {
// value is null - set to default font
this.userSettings.epubReaderSetting.font = null as any;
}
this.userSettings.ebookReaderSetting.fontFamily = null as any;
}
// Single API call with entire epubReaderSetting object
this.readerPreferencesService.updatePreference(['epubReaderSetting'], this.userSettings.epubReaderSetting);
}
get selectedFlow(): string | null {
return this.userSettings.epubReaderSetting.flow;
}
set selectedFlow(value: string | null) {
if (typeof value === "string") {
this.userSettings.epubReaderSetting.flow = value;
}
this.readerPreferencesService.updatePreference(['epubReaderSetting', 'flow'], value);
}
get selectedSpread(): string | null {
return this.userSettings.epubReaderSetting.spread;
}
set selectedSpread(value: string | null) {
if (typeof value === "string") {
this.userSettings.epubReaderSetting.spread = value;
}
this.readerPreferencesService.updatePreference(['epubReaderSetting', 'spread'], value);
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'fontFamily'], value);
}
get fontSize(): number {
return this.userSettings.epubReaderSetting.fontSize;
return this.userSettings.ebookReaderSetting.fontSize;
}
set fontSize(value: number) {
this.userSettings.epubReaderSetting.fontSize = value;
this.readerPreferencesService.updatePreference(['epubReaderSetting', 'fontSize'], value);
this.userSettings.ebookReaderSetting.fontSize = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'fontSize'], value);
}
get lineHeight(): number {
return this.userSettings.ebookReaderSetting.lineHeight;
}
set lineHeight(value: number) {
this.userSettings.ebookReaderSetting.lineHeight = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'lineHeight'], value);
}
get justify(): boolean {
return this.userSettings.ebookReaderSetting.justify;
}
set justify(value: boolean) {
this.userSettings.ebookReaderSetting.justify = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'justify'], value);
}
get hyphenate(): boolean {
return this.userSettings.ebookReaderSetting.hyphenate;
}
set hyphenate(value: boolean) {
this.userSettings.ebookReaderSetting.hyphenate = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'hyphenate'], value);
}
get maxColumnCount(): number {
return this.userSettings.ebookReaderSetting.maxColumnCount;
}
set maxColumnCount(value: number) {
this.userSettings.ebookReaderSetting.maxColumnCount = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'maxColumnCount'], value);
}
get gap(): number {
return this.userSettings.ebookReaderSetting.gap;
}
set gap(value: number) {
this.userSettings.ebookReaderSetting.gap = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'gap'], value);
}
get maxInlineSize(): number {
return this.userSettings.ebookReaderSetting.maxInlineSize;
}
set maxInlineSize(value: number) {
this.userSettings.ebookReaderSetting.maxInlineSize = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'maxInlineSize'], value);
}
get maxBlockSize(): number {
return this.userSettings.ebookReaderSetting.maxBlockSize;
}
set maxBlockSize(value: number) {
this.userSettings.ebookReaderSetting.maxBlockSize = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'maxBlockSize'], value);
}
get isDark(): boolean {
return this.userSettings.ebookReaderSetting.isDark;
}
set isDark(value: boolean) {
this.userSettings.ebookReaderSetting.isDark = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'isDark'], value);
}
get flow(): 'paginated' | 'scrolled' {
return this.userSettings.ebookReaderSetting.flow;
}
set flow(value: 'paginated' | 'scrolled') {
this.userSettings.ebookReaderSetting.flow = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'flow'], value);
}
increaseFontSize() {
if (this.fontSize < 250) {
this.fontSize += 10;
if (this.fontSize < 72) {
this.fontSize += 1;
}
}
decreaseFontSize() {
if (this.fontSize > 50) {
this.fontSize -= 10;
if (this.fontSize > 8) {
this.fontSize -= 1;
}
}
increaseLineHeight() {
if (this.lineHeight < 3) {
this.lineHeight += 0.1;
}
}
decreaseLineHeight() {
if (this.lineHeight > 1) {
this.lineHeight -= 0.1;
}
}
increaseGap() {
if (this.gap < 100) {
this.gap += 5;
}
}
decreaseGap() {
if (this.gap > 0) {
this.gap -= 5;
}
}
increaseMaxInlineSize() {
if (this.maxInlineSize < 2000) {
this.maxInlineSize += 50;
}
}
decreaseMaxInlineSize() {
if (this.maxInlineSize > 400) {
this.maxInlineSize -= 50;
}
}
increaseMaxBlockSize() {
if (this.maxBlockSize < 2000) {
this.maxBlockSize += 50;
}
}
decreaseMaxBlockSize() {
if (this.maxBlockSize > 400) {
this.maxBlockSize -= 50;
}
}
@@ -5,7 +5,7 @@
Reader Preferences
</h2>
<p class="settings-description">
Configure reader settings scope and customize reading experience for different book formats including PDF, EPUB, and CBX files.
Configure reading experience settings for your library. Set default preferences that serve as overrides for individual books, or allow each book to maintain its own custom settings for PDF, EPUB, FB2, MOBI, AZW3, and CBX formats.
</p>
</div>
@@ -14,10 +14,10 @@
<div class="section-header">
<h3 class="section-title">
<i class="pi pi-cog"></i>
Reader Settings Scope
Settings Application Mode
</h3>
<p class="section-description">
Select whether to apply the same reader settings (font, theme, spread, zoom, etc.) globally for all books or individually per book.
Control how default settings are applied. Select "Default Override" to apply your configured defaults to all books of the same format, overriding individual book preferences. Choose "Book-Specific" to let each book retain its own custom reading settings.
</p>
</div>
@@ -32,17 +32,15 @@
type="button"
class="option-button"
[class.selected]="selectedPdfScope === item.key"
(click)="selectedPdfScope = item.key; onPdfScopeChange()"
[pTooltip]="item.name"
tooltipPosition="bottom">
(click)="selectedPdfScope = item.key; onPdfScopeChange()">
<i [class]="item.icon"></i>
<span class="option-text">{{ item.name }}</span>
<span class="option-text">{{ item.key === 'Global' ? 'Default Override' : 'Book-Specific' }}</span>
</button>
}
</div>
</div>
<p class="setting-description">
Choose how PDF reader settings are applied across your library.
Choose whether default zoom, layout, and navigation settings override individual PDF preferences or if each document maintains its own settings.
</p>
</div>
</div>
@@ -50,24 +48,22 @@
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">EPUB Reader Settings</label>
<label class="setting-label">eBook Reader Settings</label>
<div class="button-group">
@for (item of scopeOptions; track item) {
<button
type="button"
class="option-button"
[class.selected]="selectedEpubScope === item.key"
(click)="selectedEpubScope = item.key; onEpubScopeChange()"
[pTooltip]="item.name"
tooltipPosition="bottom">
(click)="selectedEpubScope = item.key; onEpubScopeChange()">
<i [class]="item.icon"></i>
<span class="option-text">{{ item.name }}</span>
<span class="option-text">{{ item.key === 'Global' ? 'Default Override' : 'Book-Specific' }}</span>
</button>
}
</div>
</div>
<p class="setting-description">
Choose how EPUB reader settings are applied across your library.
Choose whether default font, theme, and layout settings override individual eBook preferences (EPUB, FB2, MOBI, AZW3) or if each book maintains its own settings.
</p>
</div>
</div>
@@ -82,17 +78,15 @@
type="button"
class="option-button"
[class.selected]="selectedCbxScope === item.key"
(click)="selectedCbxScope = item.key; onCbxScopeChange()"
[pTooltip]="item.name"
tooltipPosition="bottom">
(click)="selectedCbxScope = item.key; onCbxScopeChange()">
<i [class]="item.icon"></i>
<span class="option-text">{{ item.name }}</span>
<span class="option-text">{{ item.key === 'Global' ? 'Default Override' : 'Book-Specific' }}</span>
</button>
}
</div>
</div>
<p class="setting-description">
Choose how CBX (comic book) reader settings are applied across your library.
Choose whether default layout, direction, and scaling settings override individual comic book preferences (CBZ, CBR, CB7) or if each file maintains its own settings.
</p>
</div>
</div>
@@ -103,10 +97,10 @@
<div class="section-header">
<h3 class="section-title">
<i class="pi pi-book"></i>
EPUB Preferences: Global
eBook Reader: Default Settings
</h3>
<p class="section-description">
Set default reading options that will apply to all EPUB books in your library, including font, theme, text flow, and layout preferences.
Set default preferences for eBook formats (EPUB, FB2, MOBI, AZW3). When "Default Override" mode is active, these settings will override individual book preferences. Configure typography, themes, text flow, and layout options.
</p>
</div>
@@ -121,10 +115,10 @@
<div class="section-header">
<h3 class="section-title">
<i class="pi pi-file-pdf"></i>
PDF Preferences: Global
PDF Reader: Default Settings
</h3>
<p class="section-description">
Set default reading options that apply to all PDF books in your library, including zoom level, page layout, and navigation behavior.
Set default preferences for PDF documents. When "Default Override" mode is active, these settings will override individual document preferences. Configure zoom levels, display modes, scroll behavior, and navigation.
</p>
</div>
@@ -139,10 +133,10 @@
<div class="section-header">
<h3 class="section-title">
<i class="pi pi-images"></i>
CBX Preferences: Global
Comic Book Reader: Default Settings
</h3>
<p class="section-description">
Configure default reading settings for all comic books in your library, including page layout, reading direction, and image scaling.
Set default preferences for comic book archives (CBZ, CBR, CB7). When "Default Override" mode is active, these settings will override individual file preferences. Configure page layout, reading direction, and image rendering.
</p>
</div>
@@ -158,10 +152,10 @@
<div class="section-header">
<h3 class="section-title">
<i class="pi pi-palette"></i>
Custom Fonts Management
Custom Font Library
</h3>
<p class="section-description">
Upload and manage up to 10 custom fonts for a personalized reading experience in the EPUB reader. Each font can then be selected in the EPUB reader settings.
Personalize your reading experience by uploading custom fonts to use with eBook formats (EPUB, FB2, MOBI, AZW3). Upload up to 10 custom font files that will be available for selection in the eBook reader settings.
</p>
</div>
<div class="settings-card">
@@ -44,6 +44,20 @@ const mockUser: User = {
perBookSetting: {pdf: '', epub: '', cbx: ''},
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
ebookReaderSetting: {
lineHeight: 1,
justify: false,
hyphenate: false,
maxColumnCount: 1,
gap: 0,
fontSize: 1,
theme: '',
maxInlineSize: 0,
maxBlockSize: 0,
fontFamily: '',
isDark: false,
flow: 'paginated'
},
cbxReaderSetting: {
pageSpread: CbxPageSpread.EVEN,
pageViewMode: CbxPageViewMode.SINGLE_PAGE,
@@ -61,7 +75,7 @@ const mockUser: User = {
metadataCenterViewMode: 'route',
enableSeriesView: true,
entityViewPreferences: {
global: {sortKey: '', sortDir: 'ASC', view: 'GRID', coverSize: 1, seriesCollapsed: false},
global: {sortKey: '', sortDir: 'ASC', view: 'GRID', coverSize: 1, seriesCollapsed: false, overlayBookType: false},
overrides: []
},
koReaderEnabled: false,
@@ -1,956 +0,0 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {TestBed} from '@angular/core/testing';
import {EnvironmentInjector, runInInjectionContext} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {of, throwError} from 'rxjs';
import {
CbxFitMode,
CbxPageSpread,
CbxPageViewMode,
PdfPageSpread,
PdfPageViewMode,
User,
UserService,
UserUpdateRequest
} from './user.service';
import {AuthService} from '../../../shared/service/auth.service';
describe('UserService', () => {
let service: UserService;
let httpClientMock: any;
let authServiceMock: any;
const mockUser: User = {
id: 1,
username: 'testuser',
name: 'Test User',
email: 'test@example.com',
assignedLibraries: [],
permissions: {
admin: true,
canUpload: true,
canDownload: true,
canEmailBook: true,
canDeleteBook: true,
canEditMetadata: true,
canManageLibrary: true,
canManageMetadataConfig: true,
canSyncKoReader: true,
canSyncKobo: true,
canAccessOpds: true,
canAccessBookdrop: true,
canAccessLibraryStats: true,
canAccessUserStats: true,
canAccessTaskManager: true,
canManageEmailConfig: true,
canManageGlobalPreferences: true,
canManageIcons: true,
canManageFonts: true,
demoUser: false,
canBulkAutoFetchMetadata: true,
canBulkCustomFetchMetadata: true,
canBulkEditMetadata: true,
canBulkRegenerateCover: true,
canMoveOrganizeFiles: true,
canBulkLockUnlockMetadata: true
},
userSettings: {
perBookSetting: {pdf: '', epub: '', cbx: ''},
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
cbxReaderSetting: {
pageSpread: CbxPageSpread.EVEN,
pageViewMode: CbxPageViewMode.SINGLE_PAGE,
fitMode: CbxFitMode.ACTUAL_SIZE
},
newPdfReaderSetting: {
pageSpread: PdfPageSpread.EVEN,
pageViewMode: PdfPageViewMode.SINGLE_PAGE
},
sidebarLibrarySorting: {field: '', order: ''},
sidebarShelfSorting: {field: '', order: ''},
sidebarMagicShelfSorting: {field: '', order: ''},
filterMode: 'and',
filterSortingMode: 'alphabetical',
metadataCenterViewMode: 'route',
enableSeriesView: true,
entityViewPreferences: {
global: {sortKey: '', sortDir: 'ASC', view: 'GRID', coverSize: 1, seriesCollapsed: false},
overrides: []
},
koReaderEnabled: false,
autoSaveMetadata: false
}
};
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn()
};
authServiceMock = {
token$: of('token')
};
TestBed.configureTestingModule({
providers: [
UserService,
{provide: HttpClient, useValue: httpClientMock},
{provide: AuthService, useValue: authServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(
injector,
() => TestBed.inject(UserService)
);
});
it('should initialize with default state', () => {
expect(service.userStateSubject.value).toEqual({
user: null,
loaded: false,
error: null
});
});
it('should set initial user', () => {
service.setInitialUser(mockUser);
expect(service.userStateSubject.value.user).toEqual(mockUser);
expect(service.userStateSubject.value.loaded).toBe(true);
});
it('should get current user', () => {
service.setInitialUser(mockUser);
expect(service.getCurrentUser()).toEqual(mockUser);
});
it('should fetch myself and update state', () => {
httpClientMock.get.mockReturnValue(of(mockUser));
service['fetchMyself']().subscribe(user => {
expect(user).toEqual(mockUser);
expect(service.userStateSubject.value.user).toEqual(mockUser);
expect(service.userStateSubject.value.loaded).toBe(true);
});
});
it('should handle fetch myself error', () => {
httpClientMock.get.mockReturnValue(throwError(() => new Error('fail')));
service['fetchMyself']().subscribe({
error: (err: any) => {
expect(service.userStateSubject.value.error).toBe('fail');
expect(err).toBeInstanceOf(Error);
}
});
});
it('should get myself via getMyself()', () => {
httpClientMock.get.mockReturnValue(of(mockUser));
service.getMyself().subscribe(user => {
expect(user).toEqual(mockUser);
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/me'));
});
});
it('should create user', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const {id, ...userData} = mockUser;
service.createUser(userData).subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.post).toHaveBeenCalled();
});
});
it('should get users', () => {
httpClientMock.get.mockReturnValue(of([mockUser]));
service.getUsers().subscribe(users => {
expect(users).toEqual([mockUser]);
expect(httpClientMock.get).toHaveBeenCalled();
});
});
it('should update user', () => {
httpClientMock.put.mockReturnValue(of(mockUser));
const update: UserUpdateRequest = {name: 'New Name'};
service.updateUser(1, update).subscribe(user => {
expect(user).toEqual(mockUser);
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/1'), update);
});
});
it('should delete user', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteUser(1).subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/1'));
});
});
it('should change user password', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.changeUserPassword(1, 'newpass').subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('change-user-password'), {userId: 1, newPassword: 'newpass'});
});
});
it('should handle change user password error', () => {
httpClientMock.put.mockReturnValue(throwError(() => ({error: {message: 'bad'}})));
service.changeUserPassword(1, 'badpass').subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('bad');
}
});
});
it('should change password', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.changePassword('old', 'new').subscribe(result => {
expect(result).toBeUndefined();
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('change-password'), {currentPassword: 'old', newPassword: 'new'});
});
});
it('should handle change password error', () => {
httpClientMock.put.mockReturnValue(throwError(() => ({error: {message: 'fail'}})));
service.changePassword('old', 'bad').subscribe({
error: (err: any) => {
expect(err).toBeInstanceOf(Error);
expect(err.message).toBe('fail');
}
});
});
it('should update user setting and update state', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.setInitialUser(mockUser);
service.updateUserSetting(1, 'koReaderEnabled', true);
expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/1/settings'), {key: 'koReaderEnabled', value: true}, expect.anything());
expect(service.userStateSubject.value.user?.userSettings.koReaderEnabled).toBe(true);
});
});
describe('UserService - API Contract Tests', () => {
let service: UserService;
let httpClientMock: any;
let authServiceMock: any;
beforeEach(() => {
httpClientMock = {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
delete: vi.fn()
};
authServiceMock = {
token$: of('token')
};
TestBed.configureTestingModule({
providers: [
UserService,
{provide: HttpClient, useValue: httpClientMock},
{provide: AuthService, useValue: authServiceMock}
]
});
const injector = TestBed.inject(EnvironmentInjector);
service = runInInjectionContext(injector, () => TestBed.inject(UserService));
});
describe('User interface contract', () => {
it('should validate all required User fields exist', () => {
const requiredFields: (keyof User)[] = [
'id', 'username', 'name', 'email', 'assignedLibraries', 'permissions', 'userSettings'
];
const mockResponse: User = {
id: 1,
username: 'test',
name: 'Test',
email: 'test@test.com',
assignedLibraries: [],
permissions: {
admin: false,
canUpload: false,
canDownload: false,
canEmailBook: false,
canDeleteBook: false,
canEditMetadata: false,
canManageLibrary: false,
canManageMetadataConfig: false,
canSyncKoReader: false,
canSyncKobo: false,
canAccessOpds: false,
canAccessBookdrop: false,
canAccessLibraryStats: false,
canAccessUserStats: false,
canAccessTaskManager: false,
canManageEmailConfig: false,
canManageGlobalPreferences: false,
canManageIcons: false,
canManageFonts: false,
demoUser: false,
canBulkAutoFetchMetadata: false,
canBulkCustomFetchMetadata: false,
canBulkEditMetadata: false,
canBulkRegenerateCover: false,
canMoveOrganizeFiles: false,
canBulkLockUnlockMetadata: false
},
userSettings: {
perBookSetting: {pdf: '', epub: '', cbx: ''},
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
sidebarLibrarySorting: {field: '', order: ''},
sidebarShelfSorting: {field: '', order: ''},
sidebarMagicShelfSorting: {field: '', order: ''},
filterMode: 'and',
filterSortingMode: 'alphabetical',
metadataCenterViewMode: 'route',
enableSeriesView: true,
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []},
koReaderEnabled: false,
autoSaveMetadata: false
}
};
httpClientMock.get.mockReturnValue(of(mockResponse));
service.getMyself().subscribe(user => {
requiredFields.forEach(field => {
expect(user).toHaveProperty(field);
expect(user[field]).toBeDefined();
});
});
});
it('should validate all required Permission fields exist', () => {
const requiredPermissions = [
'admin', 'canUpload', 'canDownload', 'canEmailBook', 'canDeleteBook',
'canEditMetadata', 'canManageLibrary', 'canManageMetadataConfig',
'canSyncKoReader', 'canSyncKobo', 'canAccessOpds', 'canAccessBookdrop',
'canAccessLibraryStats', 'canAccessUserStats', 'canAccessTaskManager',
'canManageEmailConfig', 'canManageGlobalPreferences', 'canManageIcons',
'canManageFonts', // <-- Added test for canManageFonts
'demoUser', 'canBulkAutoFetchMetadata', 'canBulkCustomFetchMetadata',
'canBulkEditMetadata', 'canBulkRegenerateCover', 'canMoveOrganizeFiles',
'canBulkLockUnlockMetadata'
];
const mockResponse: User = {
id: 1,
username: 'test',
name: 'Test',
email: 'test@test.com',
assignedLibraries: [],
permissions: {
admin: true,
canUpload: true,
canDownload: true,
canEmailBook: true,
canDeleteBook: true,
canEditMetadata: true,
canManageLibrary: true,
canManageMetadataConfig: true,
canSyncKoReader: true,
canSyncKobo: true,
canAccessOpds: true,
canAccessBookdrop: true,
canAccessLibraryStats: true,
canAccessUserStats: true,
canAccessTaskManager: true,
canManageEmailConfig: true,
canManageGlobalPreferences: true,
canManageIcons: true,
canManageFonts: true, // <-- Added to mock
demoUser: false,
canBulkAutoFetchMetadata: true,
canBulkCustomFetchMetadata: true,
canBulkEditMetadata: true,
canBulkRegenerateCover: true,
canMoveOrganizeFiles: true,
canBulkLockUnlockMetadata: true
},
userSettings: {
perBookSetting: {pdf: '', epub: '', cbx: ''},
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
sidebarLibrarySorting: {field: '', order: ''},
sidebarShelfSorting: {field: '', order: ''},
sidebarMagicShelfSorting: {field: '', order: ''},
filterMode: 'and',
filterSortingMode: 'alphabetical',
metadataCenterViewMode: 'route',
enableSeriesView: true,
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []},
koReaderEnabled: false,
autoSaveMetadata: false
}
};
httpClientMock.get.mockReturnValue(of(mockResponse));
service.getMyself().subscribe(user => {
requiredPermissions.forEach(permission => {
expect(user.permissions).toHaveProperty(permission);
expect(typeof user.permissions[permission as keyof typeof user.permissions]).toBe('boolean');
});
// Explicit test for canManageFonts
expect(user.permissions.canManageFonts).toBe(true);
});
});
it('should validate all required UserSettings fields exist', () => {
const requiredSettings = [
'perBookSetting', 'pdfReaderSetting', 'epubReaderSetting', 'cbxReaderSetting',
'newPdfReaderSetting', 'sidebarLibrarySorting', 'sidebarShelfSorting',
'sidebarMagicShelfSorting', 'filterMode', 'filterSortingMode',
'metadataCenterViewMode', 'enableSeriesView', 'entityViewPreferences', 'koReaderEnabled'
];
const mockResponse: User = {
id: 1,
username: 'test',
name: 'Test',
email: 'test@test.com',
assignedLibraries: [],
permissions: {
admin: false,
canUpload: false,
canDownload: false,
canEmailBook: false,
canDeleteBook: false,
canEditMetadata: false,
canManageLibrary: false,
canManageMetadataConfig: false,
canSyncKoReader: false,
canSyncKobo: false,
canAccessOpds: false,
canAccessBookdrop: false,
canAccessLibraryStats: false,
canAccessUserStats: false,
canAccessTaskManager: false,
canManageEmailConfig: false,
canManageGlobalPreferences: false,
canManageIcons: false,
canManageFonts: false,
demoUser: false,
canBulkAutoFetchMetadata: false,
canBulkCustomFetchMetadata: false,
canBulkEditMetadata: false,
canBulkRegenerateCover: false,
canMoveOrganizeFiles: false,
canBulkLockUnlockMetadata: false
},
userSettings: {
perBookSetting: {pdf: '', epub: '', cbx: ''},
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
sidebarLibrarySorting: {field: '', order: ''},
sidebarShelfSorting: {field: '', order: ''},
sidebarMagicShelfSorting: {field: '', order: ''},
filterMode: 'and',
filterSortingMode: 'alphabetical',
metadataCenterViewMode: 'route',
enableSeriesView: true,
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []},
koReaderEnabled: false,
autoSaveMetadata: false
}
};
httpClientMock.get.mockReturnValue(of(mockResponse));
service.getMyself().subscribe(user => {
requiredSettings.forEach(setting => {
expect(user.userSettings).toHaveProperty(setting);
expect(user.userSettings[setting as keyof typeof user.userSettings]).toBeDefined();
});
});
});
it('should fail if API returns User without required id field', () => {
const invalidResponse = {
username: 'test',
name: 'Test',
email: 'test@test.com',
assignedLibraries: [],
permissions: {},
userSettings: {}
};
httpClientMock.get.mockReturnValue(of(invalidResponse));
service.getMyself().subscribe(user => {
expect(user).not.toHaveProperty('id');
});
});
it('should fail if API returns User without permissions', () => {
const invalidResponse = {
id: 1,
username: 'test',
name: 'Test',
email: 'test@test.com',
assignedLibraries: [],
userSettings: {}
};
httpClientMock.get.mockReturnValue(of(invalidResponse));
service.getMyself().subscribe(user => {
expect(user).not.toHaveProperty('permissions');
});
});
it('should fail if API returns User without userSettings', () => {
const invalidResponse = {
id: 1,
username: 'test',
name: 'Test',
email: 'test@test.com',
assignedLibraries: [],
permissions: {}
};
httpClientMock.get.mockReturnValue(of(invalidResponse));
service.getMyself().subscribe(user => {
expect(user).not.toHaveProperty('userSettings');
});
});
});
describe('Enum value contract', () => {
it('should validate CbxPageSpread enum values from API', () => {
const validValues = [CbxPageSpread.EVEN, CbxPageSpread.ODD];
expect(validValues).toContain(CbxPageSpread.EVEN);
expect(validValues).toContain(CbxPageSpread.ODD);
expect(Object.keys(CbxPageSpread)).toHaveLength(2);
});
it('should validate CbxPageViewMode enum values from API', () => {
const validValues = [CbxPageViewMode.SINGLE_PAGE, CbxPageViewMode.TWO_PAGE];
expect(validValues).toContain(CbxPageViewMode.SINGLE_PAGE);
expect(validValues).toContain(CbxPageViewMode.TWO_PAGE);
expect(Object.keys(CbxPageViewMode)).toHaveLength(2);
});
it('should validate CbxFitMode enum values from API', () => {
const validValues = [
CbxFitMode.ACTUAL_SIZE,
CbxFitMode.FIT_PAGE,
CbxFitMode.FIT_WIDTH,
CbxFitMode.FIT_HEIGHT,
CbxFitMode.AUTO
];
validValues.forEach(value => {
expect(Object.values(CbxFitMode)).toContain(value);
});
expect(Object.keys(CbxFitMode)).toHaveLength(5);
});
it('should validate PdfPageSpread enum values from API', () => {
const validValues = [PdfPageSpread.EVEN, PdfPageSpread.ODD];
expect(validValues).toContain(PdfPageSpread.EVEN);
expect(validValues).toContain(PdfPageSpread.ODD);
expect(Object.keys(PdfPageSpread)).toHaveLength(2);
});
it('should validate PdfPageViewMode enum values from API', () => {
const validValues = [PdfPageViewMode.SINGLE_PAGE, PdfPageViewMode.TWO_PAGE];
expect(validValues).toContain(PdfPageViewMode.SINGLE_PAGE);
expect(validValues).toContain(PdfPageViewMode.TWO_PAGE);
expect(Object.keys(PdfPageViewMode)).toHaveLength(2);
});
});
describe('HTTP endpoint contract', () => {
it('should call correct endpoint for getMyself', () => {
httpClientMock.get.mockReturnValue(of({}));
service.getMyself().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/users\/me$/));
});
it('should call correct endpoint for getUsers', () => {
httpClientMock.get.mockReturnValue(of([]));
service.getUsers().subscribe();
expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/users$/));
});
it('should call correct endpoint for createUser', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const userData = {
username: 'new',
name: 'New User',
email: 'new@test.com',
assignedLibraries: [],
permissions: {
admin: false,
canUpload: false,
canDownload: false,
canEmailBook: false,
canDeleteBook: false,
canEditMetadata: false,
canManageLibrary: false,
canManageMetadataConfig: false,
canSyncKoReader: false,
canSyncKobo: false,
canAccessOpds: false,
canAccessBookdrop: false,
canAccessLibraryStats: false,
canAccessUserStats: false,
canAccessTaskManager: false,
canManageEmailConfig: false,
canManageGlobalPreferences: false,
canManageIcons: false,
canManageFonts: false,
demoUser: false,
canBulkAutoFetchMetadata: false,
canBulkCustomFetchMetadata: false,
canBulkEditMetadata: false,
canBulkRegenerateCover: false,
canMoveOrganizeFiles: false,
canBulkLockUnlockMetadata: false
},
userSettings: {
perBookSetting: {pdf: '', epub: '', cbx: ''},
pdfReaderSetting: {pageSpread: 'off' as const, pageZoom: '', showSidebar: false},
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
sidebarLibrarySorting: {field: '', order: ''},
sidebarShelfSorting: {field: '', order: ''},
sidebarMagicShelfSorting: {field: '', order: ''},
filterMode: 'and' as const,
filterSortingMode: 'alphabetical' as const,
metadataCenterViewMode: 'route' as const,
enableSeriesView: true,
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []},
koReaderEnabled: false,
autoSaveMetadata: false
}
};
service.createUser(userData).subscribe();
expect(httpClientMock.post).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/auth\/register$/),
userData
);
});
it('should call correct endpoint for updateUser', () => {
httpClientMock.put.mockReturnValue(of({}));
service.updateUser(123, {name: 'Updated'}).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/users\/123$/),
{name: 'Updated'}
);
});
it('should call correct endpoint for deleteUser', () => {
httpClientMock.delete.mockReturnValue(of(void 0));
service.deleteUser(123).subscribe();
expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/users\/123$/));
});
it('should call correct endpoint for changeUserPassword', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.changeUserPassword(123, 'newpass').subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/users\/change-user-password$/),
{userId: 123, newPassword: 'newpass'}
);
});
it('should call correct endpoint for changePassword', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.changePassword('oldpass', 'newpass').subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/users\/change-password$/),
{currentPassword: 'oldpass', newPassword: 'newpass'}
);
});
it('should call correct endpoint for updateUserSetting', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.updateUserSetting(123, 'koReaderEnabled', true);
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.stringMatching(/\/api\/v1\/users\/123\/settings$/),
{key: 'koReaderEnabled', value: true},
expect.anything()
);
});
});
describe('Request payload contract', () => {
it('should send UserUpdateRequest with correct structure', () => {
httpClientMock.put.mockReturnValue(of({}));
const updateRequest: UserUpdateRequest = {
name: 'New Name',
email: 'newemail@test.com',
permissions: {
admin: true,
canUpload: true,
canDownload: true,
canEmailBook: true,
canDeleteBook: true,
canEditMetadata: true,
canManageLibrary: true,
canManageMetadataConfig: true,
canSyncKoReader: true,
canSyncKobo: true,
canAccessOpds: true,
canAccessBookdrop: true,
canAccessLibraryStats: true,
canAccessUserStats: true,
canAccessTaskManager: true,
canManageEmailConfig: true,
canManageGlobalPreferences: true,
canManageIcons: true,
canManageFonts: false,
demoUser: false,
canBulkAutoFetchMetadata: true,
canBulkCustomFetchMetadata: true,
canBulkEditMetadata: true,
canBulkRegenerateCover: true,
canMoveOrganizeFiles: true,
canBulkLockUnlockMetadata: true
},
assignedLibraries: [1, 2, 3]
};
service.updateUser(1, updateRequest).subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.any(String),
updateRequest
);
});
it('should send change password payload with correct structure', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.changePassword('current', 'new').subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.any(String),
{currentPassword: 'current', newPassword: 'new'}
);
});
it('should send change user password payload with correct structure', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.changeUserPassword(456, 'newpassword').subscribe();
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.any(String),
{userId: 456, newPassword: 'newpassword'}
);
});
it('should send user setting payload with correct structure', () => {
httpClientMock.put.mockReturnValue(of(void 0));
service.updateUserSetting(789, 'enableSeriesView', false);
expect(httpClientMock.put).toHaveBeenCalledWith(
expect.any(String),
{key: 'enableSeriesView', value: false},
expect.anything()
);
});
});
describe('Response type contract', () => {
it('should expect User array from getUsers', () => {
const mockUsers: User[] = [{
id: 1,
username: 'user1',
name: 'User One',
email: 'user1@test.com',
assignedLibraries: [],
permissions: {
admin: false,
canUpload: false,
canDownload: false,
canEmailBook: false,
canDeleteBook: false,
canEditMetadata: false,
canManageLibrary: false,
canManageMetadataConfig: false,
canSyncKoReader: false,
canSyncKobo: false,
canAccessOpds: false,
canAccessBookdrop: false,
canAccessLibraryStats: false,
canAccessUserStats: false,
canAccessTaskManager: false,
canManageEmailConfig: false,
canManageGlobalPreferences: false,
canManageIcons: false,
canManageFonts: false,
demoUser: false,
canBulkAutoFetchMetadata: false,
canBulkCustomFetchMetadata: false,
canBulkEditMetadata: false,
canBulkRegenerateCover: false,
canMoveOrganizeFiles: false,
canBulkLockUnlockMetadata: false
},
userSettings: {
perBookSetting: {pdf: '', epub: '', cbx: ''},
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
sidebarLibrarySorting: {field: '', order: ''},
sidebarShelfSorting: {field: '', order: ''},
sidebarMagicShelfSorting: {field: '', order: ''},
filterMode: 'and',
filterSortingMode: 'alphabetical',
metadataCenterViewMode: 'route',
enableSeriesView: true,
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC', view: 'GRID', coverSize: 1, seriesCollapsed: false}, overrides: []},
koReaderEnabled: false,
autoSaveMetadata: false
}
}];
httpClientMock.get.mockReturnValue(of(mockUsers));
service.getUsers().subscribe(users => {
expect(Array.isArray(users)).toBe(true);
expect(users[0]).toHaveProperty('id');
expect(users[0]).toHaveProperty('username');
});
});
it('should expect User from updateUser', () => {
const mockUser: User = {
id: 1,
username: 'updated',
name: 'Updated User',
email: 'updated@test.com',
assignedLibraries: [],
permissions: {
admin: false,
canUpload: false,
canDownload: false,
canEmailBook: false,
canDeleteBook: false,
canEditMetadata: false,
canManageLibrary: false,
canManageMetadataConfig: false,
canSyncKoReader: false,
canSyncKobo: false,
canAccessOpds: false,
canAccessBookdrop: false,
canAccessLibraryStats: false,
canAccessUserStats: false,
canAccessTaskManager: false,
canManageEmailConfig: false,
canManageGlobalPreferences: false,
canManageIcons: false,
canManageFonts: false,
demoUser: false,
canBulkAutoFetchMetadata: false,
canBulkCustomFetchMetadata: false,
canBulkEditMetadata: false,
canBulkRegenerateCover: false,
canMoveOrganizeFiles: false,
canBulkLockUnlockMetadata: false
},
userSettings: {
perBookSetting: {pdf: '', epub: '', cbx: ''},
pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false},
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
sidebarLibrarySorting: {field: '', order: ''},
sidebarShelfSorting: {field: '', order: ''},
sidebarMagicShelfSorting: {field: '', order: ''},
filterMode: 'and',
filterSortingMode: 'alphabetical',
metadataCenterViewMode: 'route',
enableSeriesView: true,
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []},
koReaderEnabled: false,
autoSaveMetadata: false
}
};
httpClientMock.put.mockReturnValue(of(mockUser));
service.updateUser(1, {name: 'Updated User'}).subscribe(user => {
expect(user).toHaveProperty('id');
expect(user).toHaveProperty('username');
expect(user).toHaveProperty('permissions');
expect(user).toHaveProperty('userSettings');
});
});
it('should expect void from createUser', () => {
httpClientMock.post.mockReturnValue(of(void 0));
const userData = {
username: 'new',
name: 'New',
email: 'new@test.com',
assignedLibraries: [],
permissions: {
admin: false,
canUpload: false,
canDownload: false,
canEmailBook: false,
canDeleteBook: false,
canEditMetadata: false,
canManageLibrary: false,
canManageMetadataConfig: false,
canSyncKoReader: false,
canSyncKobo: false,
canAccessOpds: false,
canAccessBookdrop: false,
canAccessLibraryStats: false,
canAccessUserStats: false,
canAccessTaskManager: false,
canManageEmailConfig: false,
canManageGlobalPreferences: false,
canManageIcons: false,
canManageFonts: false,
demoUser: false,
canBulkAutoFetchMetadata: false,
canBulkCustomFetchMetadata: false,
canBulkEditMetadata: false,
canBulkRegenerateCover: false,
canMoveOrganizeFiles: false,
canBulkLockUnlockMetadata: false
},
userSettings: {
perBookSetting: {pdf: '', epub: '', cbx: ''},
pdfReaderSetting: {pageSpread: 'off' as const, pageZoom: '', showSidebar: false},
epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1},
cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE},
newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE},
sidebarLibrarySorting: {field: '', order: ''},
sidebarShelfSorting: {field: '', order: ''},
sidebarMagicShelfSorting: {field: '', order: ''},
filterMode: 'and' as const,
filterSortingMode: 'alphabetical' as const,
metadataCenterViewMode: 'route' as const,
enableSeriesView: true,
entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []},
koReaderEnabled: false,
autoSaveMetadata: false
}
};
service.createUser(userData).subscribe(result => {
expect(result).toBeUndefined();
});
});
});
});
@@ -18,6 +18,7 @@ export interface EntityViewPreference {
view: 'GRID' | 'TABLE';
coverSize: number;
seriesCollapsed: boolean;
overlayBookType: boolean;
}
export interface EntityViewPreferenceOverride {
@@ -96,6 +97,21 @@ export enum CbxScrollMode {
INFINITE = 'INFINITE'
}
export interface EbookReaderSetting {
lineHeight: number;
justify: boolean;
hyphenate: boolean;
maxColumnCount: number;
gap: number;
fontSize: number;
theme: string
maxInlineSize: number;
maxBlockSize: number;
fontFamily: string;
isDark: boolean;
flow: 'paginated' | 'scrolled';
}
export interface EpubReaderSetting {
theme: string;
font: string;
@@ -131,6 +147,7 @@ export interface UserSettings {
perBookSetting: PerBookSetting;
pdfReaderSetting: PdfReaderSetting;
epubReaderSetting: EpubReaderSetting;
ebookReaderSetting: EbookReaderSetting;
cbxReaderSetting: CbxReaderSetting;
newPdfReaderSetting: NewPdfReaderSetting;
sidebarLibrarySorting: SidebarLibrarySorting;
@@ -170,8 +170,8 @@ export class ViewPreferencesComponent implements OnInit, OnDestroy {
options.map(opt => ({...opt, entityType}));
return [...withEntityType(this.libraryOptions, 'LIBRARY'),
...withEntityType(this.shelfOptions, 'SHELF'),
...withEntityType(this.magicShelfOptions, 'MAGIC_SHELF')]
...withEntityType(this.shelfOptions, 'SHELF'),
...withEntityType(this.magicShelfOptions, 'MAGIC_SHELF')]
.filter(opt => !used.has(`${opt.entityType}_${opt.value}`));
}
@@ -217,7 +217,8 @@ export class ViewPreferencesComponent implements OnInit, OnDestroy {
sortDir: o.sortDir,
view: o.view,
coverSize: existing?.coverSize ?? 1.0,
seriesCollapsed: existing?.seriesCollapsed ?? false
seriesCollapsed: existing?.seriesCollapsed ?? false,
overlayBookType: existing?.overlayBookType ?? true
}
};
});
@@ -22,7 +22,10 @@ const BOOK_TYPE_COLORS = {
'CBZ': '#27a153',
'CBX': '#d4b50f',
'CBR': '#e67e22',
'CB7': '#9b59b6'
'CB7': '#9b59b6',
'FB2': '#1abc9c',
'MOBI': '#f39c12',
'AZW3': '#2ecc71'
} as const;
const CHART_DEFAULTS = {