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
+6
View File
@@ -25,6 +25,7 @@ import {BookdropGuard} from './core/security/guards/bookdrop.guard';
import {LibraryStatsGuard} from './core/security/guards/library-stats.guard';
import {UserStatsGuard} from './core/security/guards/user-stats.guard';
import {EditMetadataGuard} from './core/security/guards/edit-metdata.guard';
import {EbookReaderComponent} from './features/readers/ebook-reader/ebook-reader.component';
export const routes: Routes = [
{
@@ -68,6 +69,11 @@ export const routes: Routes = [
component: EpubReaderComponent,
canActivate: [AuthGuard]
},
{
path: 'ebook-reader/book/:bookId',
component: EbookReaderComponent,
canActivate: [AuthGuard]
},
{
path: 'cbx-reader/book/:bookId',
component: CbxReaderComponent,
@@ -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 = {
@@ -88,7 +88,7 @@
name="file"
[customUpload]="true"
[multiple]="true"
accept=".pdf,.epub,.cbz,.cbr,.cb7,.fb2"
accept=".pdf,.epub,.cbz,.cbr,.cb7,.fb2,.mobi,.azw,.azw3"
(onSelect)="onFilesSelect($event)"
(uploadHandler)="uploadFiles($event)"
[disabled]="value === 'library' ? (!selectedLibrary || !selectedPath) : false">
@@ -181,9 +181,9 @@ export class ReadingSessionService {
endTime: endTime.toISOString(),
durationSeconds,
durationFormatted: this.formatDuration(durationSeconds),
startProgress: session.startProgress,
endProgress: session.endProgress,
progressDelta: session.progressDelta,
startProgress: session.startProgress != null ? Math.round(session.startProgress * 100) / 100 : undefined,
endProgress: session.endProgress != null ? Math.round(session.endProgress * 100) / 100 : undefined,
progressDelta: session.progressDelta != null ? Math.round(session.progressDelta * 100) / 100 : undefined,
startLocation: session.startLocation,
endLocation: session.endLocation
};
@@ -0,0 +1,45 @@
export const makeComicBook = ({ entries, loadBlob, getSize }, file) => {
const cache = new Map()
const urls = new Map()
const load = async name => {
if (cache.has(name)) return cache.get(name)
const src = URL.createObjectURL(await loadBlob(name))
const page = URL.createObjectURL(
new Blob([`<!DOCTYPE html><html><head><meta charset="utf-8"></head><body style="margin: 0"><img src="${src}"></body></html>`], { type: 'text/html' }))
urls.set(name, [src, page])
cache.set(name, page)
return page
}
const unload = name => {
urls.get(name)?.forEach?.(url => URL.revokeObjectURL(url))
urls.delete(name)
cache.delete(name)
}
const exts = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg', '.jxl', '.avif']
const files = entries
.map(entry => entry.filename)
.filter(name => exts.some(ext => name.endsWith(ext)))
.sort()
if (!files.length) throw new Error('No supported image files in archive')
const book = {}
book.getCover = () => loadBlob(files[0])
book.metadata = { title: file.name }
book.sections = files.map(name => ({
id: name,
load: () => load(name),
unload: () => unload(name),
size: getSize(name),
}))
book.toc = files.map(name => ({ label: name, href: name }))
book.rendition = { layout: 'pre-paginated' }
book.resolveHref = href => ({ index: book.sections.findIndex(s => s.id === href) })
book.splitTOCHref = href => [href, null]
book.getTOCFragment = doc => doc.documentElement
book.destroy = () => {
for (const arr of urls.values())
for (const url of arr) URL.revokeObjectURL(url)
}
return book
}
+241
View File
@@ -0,0 +1,241 @@
const decoder = new TextDecoder()
const decode = decoder.decode.bind(decoder)
const concatTypedArray = (a, b) => {
const result = new a.constructor(a.length + b.length)
result.set(a)
result.set(b, a.length)
return result
}
const strcmp = (a, b) => {
a = a.toLowerCase(), b = b.toLowerCase()
return a < b ? -1 : a > b ? 1 : 0
}
class DictZip {
#chlen
#chunks
#compressed
inflate
async load(file) {
const header = new DataView(await file.slice(0, 12).arrayBuffer())
if (header.getUint8(0) !== 31 || header.getUint8(1) !== 139
|| header.getUint8(2) !== 8) throw new Error('Not a DictZip file')
const flg = header.getUint8(3)
if (!flg & 0b100) throw new Error('Missing FEXTRA flag')
const xlen = header.getUint16(10, true)
const extra = new DataView(await file.slice(12, 12 + xlen).arrayBuffer())
if (extra.getUint8(0) !== 82 || extra.getUint8(1) !== 65)
throw new Error('Subfield ID should be RA')
if (extra.getUint16(4, true) !== 1) throw new Error('Unsupported version')
this.#chlen = extra.getUint16(6, true)
const chcnt = extra.getUint16(8, true)
this.#chunks = []
for (let i = 0, chunkOffset = 0; i < chcnt; i++) {
const chunkSize = extra.getUint16(10 + 2 * i, true)
this.#chunks.push([chunkOffset, chunkSize])
chunkOffset = chunkOffset + chunkSize
}
// skip to compressed data
let offset = 12 + xlen
const max = Math.min(offset + 512, file.size)
const strArr = new Uint8Array(await file.slice(0, max).arrayBuffer())
if (flg & 0b1000) { // fname
const i = strArr.indexOf(0, offset)
if (i < 0) throw new Error('Header too long')
offset = i + 1
}
if (flg & 0b10000) { // fcomment
const i = strArr.indexOf(0, offset)
if (i < 0) throw new Error('Header too long')
offset = i + 1
}
if (flg & 0b10) offset += 2 // fhcrc
this.#compressed = file.slice(offset)
}
async read(offset, size) {
const chunks = this.#chunks
const startIndex = Math.trunc(offset / this.#chlen)
const endIndex = Math.trunc((offset + size) / this.#chlen)
const buf = await this.#compressed.slice(chunks[startIndex][0],
chunks[endIndex][0] + chunks[endIndex][1]).arrayBuffer()
let arr = new Uint8Array()
for (let pos = 0, i = startIndex; i <= endIndex; i++) {
const data = new Uint8Array(buf, pos, chunks[i][1])
arr = concatTypedArray(arr, await this.inflate(data))
pos += chunks[i][1]
}
const startOffset = offset - startIndex * this.#chlen
return arr.subarray(startOffset, startOffset + size)
}
}
class Index {
strcmp = strcmp
// binary search
bisect(query, start = 0, end = this.words.length - 1) {
if (end - start === 1) {
if (!this.strcmp(query, this.getWord(start))) return start
if (!this.strcmp(query, this.getWord(end))) return end
return null
}
const mid = Math.floor(start + (end - start) / 2)
const cmp = this.strcmp(query, this.getWord(mid))
if (cmp < 0) return this.bisect(query, start, mid)
if (cmp > 0) return this.bisect(query, mid, end)
return mid
}
// check for multiple definitions
checkAdjacent(query, i) {
if (i == null) return []
let j = i
const equals = i => {
const word = this.getWord(i)
return word ? this.strcmp(query, word) === 0 : false
}
while (equals(j - 1)) j--
let k = i
while (equals(k + 1)) k++
return j === k ? [i] : Array.from({ length: k + 1 - j }, (_, i) => j + i)
}
lookup(query) {
return this.checkAdjacent(query, this.bisect(query))
}
}
const decodeBase64Number = str => {
const { length } = str
let n = 0
for (let i = 0; i < length; i++) {
const c = str.charCodeAt(i)
n += (c === 43 ? 62 // "+"
: c === 47 ? 63 // "/"
: c < 58 ? c + 4 // 0-9 -> 52-61
: c < 91 ? c - 65 // A-Z -> 0-25
: c - 71 // a-z -> 26-51
) * 64 ** (length - 1 - i)
}
return n
}
class DictdIndex extends Index {
getWord(i) {
return this.words[i]
}
async load(file) {
const words = []
const offsets = []
const sizes = []
for (const line of decode(await file.arrayBuffer()).split('\n')) {
const a = line.split('\t')
words.push(a[0])
offsets.push(decodeBase64Number(a[1]))
sizes.push(decodeBase64Number(a[2]))
}
this.words = words
this.offsets = offsets
this.sizes = sizes
}
}
export class DictdDict {
#dict = new DictZip()
#idx = new DictdIndex()
loadDict(file, inflate) {
this.#dict.inflate = inflate
return this.#dict.load(file)
}
async #readWord(i) {
const word = this.#idx.getWord(i)
const offset = this.#idx.offsets[i]
const size = this.#idx.sizes[i]
return { word, data: ['m', this.#dict.read(offset, size)] }
}
#readWords(arr) {
return Promise.all(arr.map(this.#readWord.bind(this)))
}
lookup(query) {
return this.#readWords(this.#idx.lookup(query))
}
}
class StarDictIndex extends Index {
isSyn
#arr
getWord(i) {
const word = this.words[i]
if (!word) return
return decode(this.#arr.subarray(word[0], word[1]))
}
async load(file) {
const { isSyn } = this
const buf = await file.arrayBuffer()
const arr = new Uint8Array(buf)
this.#arr = arr
const view = new DataView(buf)
const words = []
const offsets = []
const sizes = []
for (let i = 0; i < arr.length;) {
const newI = arr.subarray(0, i + 256).indexOf(0, i)
if (newI < 0) throw new Error('Word too big')
words.push([i, newI])
offsets.push(view.getUint32(newI + 1))
if (isSyn) i = newI + 5
else {
sizes.push(view.getUint32(newI + 5))
i = newI + 9
}
}
this.words = words
this.offsets = offsets
this.sizes = sizes
}
}
export class StarDict {
#dict = new DictZip()
#idx = new StarDictIndex()
#syn = Object.assign(new StarDictIndex(), { isSyn: true })
async loadIfo(file) {
const str = decode(await file.arrayBuffer())
this.ifo = Object.fromEntries(str.split('\n').map(line => {
const sep = line.indexOf('=')
if (sep < 0) return
return [line.slice(0, sep), line.slice(sep + 1)]
}).filter(x => x))
}
loadDict(file, inflate) {
this.#dict.inflate = inflate
return this.#dict.load(file)
}
loadIdx(file) {
return this.#idx.load(file)
}
loadSyn(file) {
if (file) return this.#syn.load(file)
}
async #readWord(i) {
const word = this.#idx.getWord(i)
const offset = this.#idx.offsets[i]
const size = this.#idx.sizes[i]
const data = await this.#dict.read(offset, size)
const seq = this.ifo.sametypesequence
if (!seq) throw new Error('TODO')
if (seq.length === 1) return { word, data: [[seq[0], data]] }
throw new Error('TODO')
}
#readWords(arr) {
return Promise.all(arr.map(this.#readWord.bind(this)))
}
lookup(query) {
return this.#readWords(this.#idx.lookup(query))
}
synonyms(query) {
return this.#readWords(this.#syn.lookup(query).map(i => this.#syn.offsets[i]))
}
}
File diff suppressed because it is too large Load Diff
+345
View File
@@ -0,0 +1,345 @@
const findIndices = (arr, f) => arr
.map((x, i, a) => f(x, i, a) ? i : null).filter(x => x != null)
const splitAt = (arr, is) => [-1, ...is, arr.length].reduce(({ xs, a }, b) =>
({ xs: xs?.concat([arr.slice(a + 1, b)]) ?? [], a: b }), {}).xs
const concatArrays = (a, b) =>
a.slice(0, -1).concat([a[a.length - 1].concat(b[0])]).concat(b.slice(1))
const isNumber = /\d/
export const isCFI = /^epubcfi\((.*)\)$/
const escapeCFI = str => str.replace(/[\^[\](),;=]/g, '^$&')
const wrap = x => isCFI.test(x) ? x : `epubcfi(${x})`
const unwrap = x => x.match(isCFI)?.[1] ?? x
const lift = f => (...xs) =>
`epubcfi(${f(...xs.map(x => x.match(isCFI)?.[1] ?? x))})`
export const joinIndir = lift((...xs) => xs.join('!'))
const tokenizer = str => {
const tokens = []
let state, escape, value = ''
const push = x => (tokens.push(x), state = null, value = '')
const cat = x => (value += x, escape = false)
for (const char of Array.from(str.trim()).concat('')) {
if (char === '^' && !escape) {
escape = true
continue
}
if (state === '!') push(['!'])
else if (state === ',') push([','])
else if (state === '/' || state === ':') {
if (isNumber.test(char)) {
cat(char)
continue
} else push([state, parseInt(value)])
} else if (state === '~') {
if (isNumber.test(char) || char === '.') {
cat(char)
continue
} else push(['~', parseFloat(value)])
} else if (state === '@') {
if (char === ':') {
push(['@', parseFloat(value)])
state = '@'
continue
}
if (isNumber.test(char) || char === '.') {
cat(char)
continue
} else push(['@', parseFloat(value)])
} else if (state === '[') {
if (char === ';' && !escape) {
push(['[', value])
state = ';'
} else if (char === ',' && !escape) {
push(['[', value])
state = '['
} else if (char === ']' && !escape) push(['[', value])
else cat(char)
continue
} else if (state?.startsWith(';')) {
if (char === '=' && !escape) {
state = `;${value}`
value = ''
} else if (char === ';' && !escape) {
push([state, value])
state = ';'
} else if (char === ']' && !escape) push([state, value])
else cat(char)
continue
}
if (char === '/' || char === ':' || char === '~' || char === '@'
|| char === '[' || char === '!' || char === ',') state = char
}
return tokens
}
const findTokens = (tokens, x) => findIndices(tokens, ([t]) => t === x)
const parser = tokens => {
const parts = []
let state
for (const [type, val] of tokens) {
if (type === '/') parts.push({ index: val })
else {
const last = parts[parts.length - 1]
if (type === ':') last.offset = val
else if (type === '~') last.temporal = val
else if (type === '@') last.spatial = (last.spatial ?? []).concat(val)
else if (type === ';s') last.side = val
else if (type === '[') {
if (state === '/' && val) last.id = val
else {
last.text = (last.text ?? []).concat(val)
continue
}
}
}
state = type
}
return parts
}
// split at step indirections, then parse each part
const parserIndir = tokens =>
splitAt(tokens, findTokens(tokens, '!')).map(parser)
export const parse = cfi => {
const tokens = tokenizer(unwrap(cfi))
const commas = findTokens(tokens, ',')
if (!commas.length) return parserIndir(tokens)
const [parent, start, end] = splitAt(tokens, commas).map(parserIndir)
return { parent, start, end }
}
const partToString = ({ index, id, offset, temporal, spatial, text, side }) => {
const param = side ? `;s=${side}` : ''
return `/${index}`
+ (id ? `[${escapeCFI(id)}${param}]` : '')
// "CFI expressions [..] SHOULD include an explicit character offset"
+ (offset != null && index % 2 ? `:${offset}` : '')
+ (temporal ? `~${temporal}` : '')
+ (spatial ? `@${spatial.join(':')}` : '')
+ (text || (!id && side) ? '['
+ (text?.map(escapeCFI)?.join(',') ?? '')
+ param + ']' : '')
}
const toInnerString = parsed => parsed.parent
? [parsed.parent, parsed.start, parsed.end].map(toInnerString).join(',')
: parsed.map(parts => parts.map(partToString).join('')).join('!')
const toString = parsed => wrap(toInnerString(parsed))
export const collapse = (x, toEnd) => typeof x === 'string'
? toString(collapse(parse(x), toEnd))
: x.parent ? concatArrays(x.parent, x[toEnd ? 'end' : 'start']) : x
// create range CFI from two CFIs
const buildRange = (from, to) => {
if (typeof from === 'string') from = parse(from)
if (typeof to === 'string') to = parse(to)
from = collapse(from)
to = collapse(to, true)
// ranges across multiple documents are not allowed; handle local paths only
const localFrom = from[from.length - 1], localTo = to[to.length - 1]
const localParent = [], localStart = [], localEnd = []
let pushToParent = true
const len = Math.max(localFrom.length, localTo.length)
for (let i = 0; i < len; i++) {
const a = localFrom[i], b = localTo[i]
pushToParent &&= a?.index === b?.index && !a?.offset && !b?.offset
if (pushToParent) localParent.push(a)
else {
if (a) localStart.push(a)
if (b) localEnd.push(b)
}
}
// copy non-local paths from `from`
const parent = from.slice(0, -1).concat([localParent])
return toString({ parent, start: [localStart], end: [localEnd] })
}
export const compare = (a, b) => {
if (typeof a === 'string') a = parse(a)
if (typeof b === 'string') b = parse(b)
if (a.start || b.start) return compare(collapse(a), collapse(b))
|| compare(collapse(a, true), collapse(b, true))
for (let i = 0; i < Math.max(a.length, b.length); i++) {
const p = a[i] ?? [], q = b[i] ?? []
const maxIndex = Math.max(p.length, q.length) - 1
for (let i = 0; i <= maxIndex; i++) {
const x = p[i], y = q[i]
if (!x) return -1
if (!y) return 1
if (x.index > y.index) return 1
if (x.index < y.index) return -1
if (i === maxIndex) {
// TODO: compare temporal & spatial offsets
if (x.offset > y.offset) return 1
if (x.offset < y.offset) return -1
}
}
}
return 0
}
const isTextNode = ({ nodeType }) => nodeType === 3 || nodeType === 4
const isElementNode = ({ nodeType }) => nodeType === 1
const getChildNodes = (node, filter) => {
const nodes = Array.from(node.childNodes)
// "content other than element and character data is ignored"
.filter(node => isTextNode(node) || isElementNode(node))
return filter ? nodes.map(node => {
const accept = filter(node)
if (accept === NodeFilter.FILTER_REJECT) return null
else if (accept === NodeFilter.FILTER_SKIP) return getChildNodes(node, filter)
else return node
}).flat().filter(x => x) : nodes
}
// child nodes are organized such that the result is always
// [element, text, element, text, ..., element],
// regardless of the actual structure in the document;
// so multiple text nodes need to be combined, and nonexistent ones counted;
// see "Step Reference to Child Element or Character Data (/)" in EPUB CFI spec
const indexChildNodes = (node, filter) => {
const nodes = getChildNodes(node, filter)
.reduce((arr, node) => {
let last = arr[arr.length - 1]
if (!last) arr.push(node)
// "there is one chunk between each pair of child elements"
else if (isTextNode(node)) {
if (Array.isArray(last)) last.push(node)
else if (isTextNode(last)) arr[arr.length - 1] = [last, node]
else arr.push(node)
} else {
if (isElementNode(last)) arr.push(null, node)
else arr.push(node)
}
return arr
}, [])
// "the first chunk is located before the first child element"
if (isElementNode(nodes[0])) nodes.unshift('first')
// "the last chunk is located after the last child element"
if (isElementNode(nodes[nodes.length - 1])) nodes.push('last')
// "'virtual' elements"
nodes.unshift('before') // "0 is a valid index"
nodes.push('after') // "n+2 is a valid index"
return nodes
}
const partsToNode = (node, parts, filter) => {
const { id } = parts[parts.length - 1]
if (id) {
const el = node.ownerDocument.getElementById(id)
if (el) return { node: el, offset: 0 }
}
for (const { index } of parts) {
const newNode = node ? indexChildNodes(node, filter)[index] : null
// handle non-existent nodes
if (newNode === 'first') return { node: node.firstChild ?? node }
if (newNode === 'last') return { node: node.lastChild ?? node }
if (newNode === 'before') return { node, before: true }
if (newNode === 'after') return { node, after: true }
node = newNode
}
const { offset } = parts[parts.length - 1]
if (!Array.isArray(node)) return { node, offset }
// get underlying text node and offset from the chunk
let sum = 0
for (const n of node) {
const { length } = n.nodeValue
if (sum + length >= offset) return { node: n, offset: offset - sum }
sum += length
}
}
const nodeToParts = (node, offset, filter) => {
const { parentNode, id } = node
const indexed = indexChildNodes(parentNode, filter)
const index = indexed.findIndex(x =>
Array.isArray(x) ? x.some(x => x === node) : x === node)
// adjust offset as if merging the text nodes in the chunk
const chunk = indexed[index]
if (Array.isArray(chunk)) {
let sum = 0
for (const x of chunk) {
if (x === node) {
sum += offset
break
} else sum += x.nodeValue.length
}
offset = sum
}
const part = { id, index, offset }
return (parentNode !== node.ownerDocument.documentElement
? nodeToParts(parentNode, null, filter).concat(part) : [part])
// remove ignored nodes
.filter(x => x.index !== -1)
}
export const fromRange = (range, filter) => {
const { startContainer, startOffset, endContainer, endOffset } = range
const start = nodeToParts(startContainer, startOffset, filter)
if (range.collapsed) return toString([start])
const end = nodeToParts(endContainer, endOffset, filter)
return buildRange([start], [end])
}
export const toRange = (doc, parts, filter) => {
const startParts = collapse(parts)
const endParts = collapse(parts, true)
const root = doc.documentElement
const start = partsToNode(root, startParts[0], filter)
const end = partsToNode(root, endParts[0], filter)
const range = doc.createRange()
if (start.before) range.setStartBefore(start.node)
else if (start.after) range.setStartAfter(start.node)
else range.setStart(start.node, start.offset)
if (end.before) range.setEndBefore(end.node)
else if (end.after) range.setEndAfter(end.node)
else range.setEnd(end.node, end.offset)
return range
}
// faster way of getting CFIs for sorted elements in a single parent
export const fromElements = elements => {
const results = []
const { parentNode } = elements[0]
const parts = nodeToParts(parentNode)
for (const [index, node] of indexChildNodes(parentNode).entries()) {
const el = elements[results.length]
if (node === el)
results.push(toString([parts.concat({ id: el.id, index })]))
}
return results
}
export const toElement = (doc, parts) =>
partsToNode(doc.documentElement, collapse(parts)).node
// turn indices into standard CFIs when you don't have an actual package document
export const fake = {
fromIndex: index => wrap(`/6/${(index + 1) * 2}`),
toIndex: parts => parts?.at(-1).index / 2 - 1,
}
// get CFI from Calibre bookmarks
// see https://github.com/johnfactotum/foliate/issues/849
export const fromCalibrePos = pos => {
const [parts] = parse(pos)
const item = parts.shift()
parts.shift()
return toString([[{ index: 6 }, item], parts])
}
export const fromCalibreHighlight = ({ spine_index, start_cfi, end_cfi }) => {
const pre = fake.fromIndex(spine_index) + '!'
return buildRange(pre + start_cfi.slice(2), pre + end_cfi.slice(2))
}
+359
View File
@@ -0,0 +1,359 @@
const normalizeWhitespace = str => str ? str
.replace(/[\t\n\f\r ]+/g, ' ')
.replace(/^[\t\n\f\r ]+/, '')
.replace(/[\t\n\f\r ]+$/, '') : ''
const getElementText = el => normalizeWhitespace(el?.textContent)
const NS = {
XLINK: 'http://www.w3.org/1999/xlink',
EPUB: 'http://www.idpf.org/2007/ops',
}
const MIME = {
XML: 'application/xml',
XHTML: 'application/xhtml+xml',
}
const STYLE = {
'strong': ['strong', 'self'],
'emphasis': ['em', 'self'],
'style': ['span', 'self'],
'a': 'anchor',
'strikethrough': ['s', 'self'],
'sub': ['sub', 'self'],
'sup': ['sup', 'self'],
'code': ['code', 'self'],
'image': 'image',
}
const TABLE = {
'tr': ['tr', {
'th': ['th', STYLE, ['colspan', 'rowspan', 'align', 'valign']],
'td': ['td', STYLE, ['colspan', 'rowspan', 'align', 'valign']],
}, ['align']],
}
const POEM = {
'epigraph': ['blockquote'],
'subtitle': ['h2', STYLE],
'text-author': ['p', STYLE],
'date': ['p', STYLE],
'stanza': 'stanza',
}
const SECTION = {
'title': ['header', {
'p': ['h1', STYLE],
'empty-line': ['br'],
}],
'epigraph': ['blockquote', 'self'],
'image': 'image',
'annotation': ['aside'],
'section': ['section', 'self'],
'p': ['p', STYLE],
'poem': ['blockquote', POEM],
'subtitle': ['h2', STYLE],
'cite': ['blockquote', 'self'],
'empty-line': ['br'],
'table': ['table', TABLE],
'text-author': ['p', STYLE],
}
POEM['epigraph'].push(SECTION)
const BODY = {
'image': 'image',
'title': ['section', {
'p': ['h1', STYLE],
'empty-line': ['br'],
}],
'epigraph': ['section', SECTION],
'section': ['section', SECTION],
}
class FB2Converter {
constructor(fb2) {
this.fb2 = fb2
this.doc = document.implementation.createDocument(NS.XHTML, 'html')
// use this instead of `getElementById` to allow images like
// `<image l:href="#img1.jpg" id="img1.jpg" />`
this.bins = new Map(Array.from(this.fb2.getElementsByTagName('binary'),
el => [el.id, el]))
}
getImageSrc(el) {
const href = el.getAttributeNS(NS.XLINK, 'href')
if (!href) return 'data:,'
const [, id] = href.split('#')
if (!id) return href
const bin = this.bins.get(id)
return bin
? `data:${bin.getAttribute('content-type')};base64,${bin.textContent}`
: href
}
image(node) {
const el = this.doc.createElement('img')
el.alt = node.getAttribute('alt')
el.title = node.getAttribute('title')
el.setAttribute('src', this.getImageSrc(node))
return el
}
anchor(node) {
const el = this.convert(node, { 'a': ['a', STYLE] })
el.setAttribute('href', node.getAttributeNS(NS.XLINK, 'href'))
if (node.getAttribute('type') === 'note')
el.setAttributeNS(NS.EPUB, 'epub:type', 'noteref')
return el
}
stanza(node) {
const el = this.convert(node, {
'stanza': ['p', {
'title': ['header', {
'p': ['strong', STYLE],
'empty-line': ['br'],
}],
'subtitle': ['p', STYLE],
}],
})
for (const child of node.children) if (child.nodeName === 'v') {
el.append(this.doc.createTextNode(child.textContent))
el.append(this.doc.createElement('br'))
}
return el
}
convert(node, def) {
// not an element; return text content
if (node.nodeType === 3) return this.doc.createTextNode(node.textContent)
if (node.nodeType === 4) return this.doc.createCDATASection(node.textContent)
if (node.nodeType === 8) return this.doc.createComment(node.textContent)
const d = def?.[node.nodeName]
if (!d) return null
if (typeof d === 'string') return this[d](node)
const [name, opts, attrs] = d
const el = this.doc.createElement(name)
// copy the ID, and set class name from original element name
if (node.id) el.id = node.id
el.classList.add(node.nodeName)
// copy attributes
if (Array.isArray(attrs)) for (const attr of attrs) {
const value = node.getAttribute(attr)
if (value) el.setAttribute(attr, value)
}
// process child elements recursively
const childDef = opts === 'self' ? def : opts
let child = node.firstChild
while (child) {
const childEl = this.convert(child, childDef)
if (childEl) el.append(childEl)
child = child.nextSibling
}
return el
}
}
const parseXML = async blob => {
const buffer = await blob.arrayBuffer()
const str = new TextDecoder('utf-8').decode(buffer)
const parser = new DOMParser()
const doc = parser.parseFromString(str, MIME.XML)
const encoding = doc.xmlEncoding
// `Document.xmlEncoding` is deprecated, and already removed in Firefox
// so parse the XML declaration manually
|| str.match(/^<\?xml\s+version\s*=\s*["']1.\d+"\s+encoding\s*=\s*["']([A-Za-z0-9._-]*)["']/)?.[1]
if (encoding && encoding.toLowerCase() !== 'utf-8') {
const str = new TextDecoder(encoding).decode(buffer)
return parser.parseFromString(str, MIME.XML)
}
return doc
}
const style = URL.createObjectURL(new Blob([`
@namespace epub "http://www.idpf.org/2007/ops";
body > img, section > img {
display: block;
margin: auto;
}
.title h1 {
text-align: center;
}
body > section > .title, body.notesBodyType > .title {
margin: 3em 0;
}
body.notesBodyType > section .title h1 {
text-align: start;
}
body.notesBodyType > section .title {
margin: 1em 0;
}
p {
text-indent: 1em;
margin: 0;
}
:not(p) + p, p:first-child {
text-indent: 0;
}
.poem p {
text-indent: 0;
margin: 1em 0;
}
.text-author, .date {
text-align: end;
}
.text-author:before {
content: "—";
}
table {
border-collapse: collapse;
}
td, th {
padding: .25em;
}
a[epub|type~="noteref"] {
font-size: .75em;
vertical-align: super;
}
body:not(.notesBodyType) > .title, body:not(.notesBodyType) > .epigraph {
margin: 3em 0;
}
`], { type: 'text/css' }))
const template = html => `<?xml version="1.0" encoding="utf-8"?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><link href="${style}" rel="stylesheet" type="text/css"/></head>
<body>${html}</body>
</html>`
// name of custom ID attribute for TOC items
const dataID = 'data-foliate-id'
export const makeFB2 = async blob => {
const book = {}
const doc = await parseXML(blob)
const converter = new FB2Converter(doc)
const $ = x => doc.querySelector(x)
const $$ = x => [...doc.querySelectorAll(x)]
const getPerson = el => {
const nick = getElementText(el.querySelector('nickname'))
if (nick) return nick
const first = getElementText(el.querySelector('first-name'))
const middle = getElementText(el.querySelector('middle-name'))
const last = getElementText(el.querySelector('last-name'))
const name = [first, middle, last].filter(x => x).join(' ')
const sortAs = last
? [last, [first, middle].filter(x => x).join(' ')].join(', ')
: null
return { name, sortAs }
}
const getDate = el => el?.getAttribute('value') ?? getElementText(el)
const annotation = $('title-info annotation')
book.metadata = {
title: getElementText($('title-info book-title')),
identifier: getElementText($('document-info id')),
language: getElementText($('title-info lang')),
author: $$('title-info author').map(getPerson),
translator: $$('title-info translator').map(getPerson),
contributor: $$('document-info author').map(getPerson)
// techincially the program probably shouldn't get the `bkp` role
// but it has been so used by calibre, so ¯\_(ツ)_/¯
.concat($$('document-info program-used').map(getElementText))
.map(x => Object.assign(typeof x === 'string' ? { name: x } : x,
{ role: 'bkp' })),
publisher: getElementText($('publish-info publisher')),
published: getDate($('title-info date')),
modified: getDate($('document-info date')),
description: annotation ? converter.convert(annotation,
{ annotation: ['div', SECTION] }).innerHTML : null,
subject: $$('title-info genre').map(getElementText),
}
if ($('coverpage image')) {
const src = converter.getImageSrc($('coverpage image'))
book.getCover = () => fetch(src).then(res => res.blob())
} else book.getCover = () => null
// get convert each body
const bodyData = Array.from(doc.querySelectorAll('body'), body => {
const converted = converter.convert(body, { body: ['body', BODY] })
return [Array.from(converted.children, el => {
// get list of IDs in the section
const ids = [el, ...el.querySelectorAll('[id]')].map(el => el.id)
return { el, ids }
}), converted]
})
const urls = []
const sectionData = bodyData[0][0]
// make a separate section for each section in the first body
.map(({ el, ids }) => {
// set up titles for TOC
const titles = Array.from(
el.querySelectorAll(':scope > section > .title'),
(el, index) => {
el.setAttribute(dataID, index)
return { title: getElementText(el), index }
})
return { ids, titles, el }
})
// for additional bodies, only make one section for each body
.concat(bodyData.slice(1).map(([sections, body]) => {
const ids = sections.map(s => s.ids).flat()
body.classList.add('notesBodyType')
return { ids, el: body, linear: 'no' }
}))
.map(({ ids, titles, el, linear }) => {
const str = template(el.outerHTML)
const blob = new Blob([str], { type: MIME.XHTML })
const url = URL.createObjectURL(blob)
urls.push(url)
const title = normalizeWhitespace(
el.querySelector('.title, .subtitle, p')?.textContent
?? (el.classList.contains('title') ? el.textContent : ''))
return {
ids, title, titles, load: () => url,
createDocument: () => new DOMParser().parseFromString(str, MIME.XHTML),
// doo't count image data as it'd skew the size too much
size: blob.size - Array.from(el.querySelectorAll('[src]'),
el => el.getAttribute('src')?.length ?? 0)
.reduce((a, b) => a + b, 0),
linear,
}
})
const idMap = new Map()
book.sections = sectionData.map((section, index) => {
const { ids, load, createDocument, size, linear } = section
for (const id of ids) if (id) idMap.set(id, index)
return { id: index, load, createDocument, size, linear }
})
book.toc = sectionData.map(({ title, titles }, index) => {
const id = index.toString()
return {
label: title,
href: id,
subitems: titles?.length ? titles.map(({ title, index }) => ({
label: title,
href: `${id}#${index}`,
})) : null,
}
}).filter(item => item)
book.resolveHref = href => {
const [a, b] = href.split('#')
return a
// the link is from the TOC
? { index: Number(a), anchor: doc => doc.querySelector(`[${dataID}="${b}"]`) }
// link from within the page
: { index: idMap.get(b), anchor: doc => doc.getElementById(b) }
}
book.splitTOCHref = href => href?.split('#')?.map(x => Number(x)) ?? []
book.getTOCFragment = (doc, id) => doc.querySelector(`[${dataID}="${id}"]`)
book.destroy = () => {
for (const url of urls) URL.revokeObjectURL(url)
}
return book
}
@@ -0,0 +1,319 @@
const parseViewport = str => str
?.split(/[,;\s]/) // NOTE: technically, only the comma is valid
?.filter(x => x)
?.map(x => x.split('=').map(x => x.trim()))
const getViewport = (doc, viewport) => {
// use `viewBox` for SVG
if (doc.documentElement.localName === 'svg') {
const [, , width, height] = doc.documentElement
.getAttribute('viewBox')?.split(/\s/) ?? []
return { width, height }
}
// get `viewport` `meta` element
const meta = parseViewport(doc.querySelector('meta[name="viewport"]')
?.getAttribute('content'))
if (meta) return Object.fromEntries(meta)
// fallback to book's viewport
if (typeof viewport === 'string') return parseViewport(viewport)
if (viewport?.width && viewport.height) return viewport
// if no viewport (possibly with image directly in spine), get image size
const img = doc.querySelector('img')
if (img) return { width: img.naturalWidth, height: img.naturalHeight }
// just show *something*, i guess...
console.warn(new Error('Missing viewport properties'))
return { width: 1000, height: 2000 }
}
export class FixedLayout extends HTMLElement {
static observedAttributes = ['zoom']
#root = this.attachShadow({ mode: 'closed' })
#observer = new ResizeObserver(() => this.#render())
#spreads
#index = -1
defaultViewport
spread
#portrait = false
#left
#right
#center
#side
#zoom
constructor() {
super()
const sheet = new CSSStyleSheet()
this.#root.adoptedStyleSheets = [sheet]
sheet.replaceSync(`:host {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
overflow: auto;
}`)
this.#observer.observe(this)
}
attributeChangedCallback(name, _, value) {
switch (name) {
case 'zoom':
this.#zoom = value !== 'fit-width' && value !== 'fit-page'
? parseFloat(value) : value
this.#render()
break
}
}
async #createFrame({ index, src: srcOption }) {
const srcOptionIsString = typeof srcOption === 'string'
const src = srcOptionIsString ? srcOption : srcOption?.src
const onZoom = srcOptionIsString ? null : srcOption?.onZoom
const element = document.createElement('div')
element.setAttribute('dir', 'ltr')
const iframe = document.createElement('iframe')
element.append(iframe)
Object.assign(iframe.style, {
border: '0',
display: 'none',
overflow: 'hidden',
})
// `allow-scripts` is needed for events because of WebKit bug
// https://bugs.webkit.org/show_bug.cgi?id=218086
iframe.setAttribute('sandbox', 'allow-same-origin allow-scripts')
iframe.setAttribute('scrolling', 'no')
iframe.setAttribute('part', 'filter')
this.#root.append(element)
if (!src) return { blank: true, element, iframe }
return new Promise(resolve => {
iframe.addEventListener('load', () => {
const doc = iframe.contentDocument
this.dispatchEvent(new CustomEvent('load', { detail: { doc, index } }))
const { width, height } = getViewport(doc, this.defaultViewport)
resolve({
element, iframe,
width: parseFloat(width),
height: parseFloat(height),
onZoom,
})
}, { once: true })
iframe.src = src
})
}
#render(side = this.#side) {
if (!side) return
const left = this.#left ?? {}
const right = this.#center ?? this.#right ?? {}
const target = side === 'left' ? left : right
const { width, height } = this.getBoundingClientRect()
const portrait = this.spread !== 'both' && this.spread !== 'portrait'
&& height > width
this.#portrait = portrait
const blankWidth = left.width ?? right.width ?? 0
const blankHeight = left.height ?? right.height ?? 0
const scale = typeof this.#zoom === 'number' && !isNaN(this.#zoom)
? this.#zoom
: (this.#zoom === 'fit-width'
? (portrait || this.#center
? width / (target.width ?? blankWidth)
: width / ((left.width ?? blankWidth) + (right.width ?? blankWidth)))
: (portrait || this.#center
? Math.min(
width / (target.width ?? blankWidth),
height / (target.height ?? blankHeight))
: Math.min(
width / ((left.width ?? blankWidth) + (right.width ?? blankWidth)),
height / Math.max(
left.height ?? blankHeight,
right.height ?? blankHeight)))
) || 1
const transform = frame => {
let { element, iframe, width, height, blank, onZoom } = frame
if (!iframe) return
if (onZoom) onZoom({ doc: frame.iframe.contentDocument, scale })
const iframeScale = onZoom ? scale : 1
Object.assign(iframe.style, {
width: `${width * iframeScale}px`,
height: `${height * iframeScale}px`,
transform: onZoom ? 'none' : `scale(${scale})`,
transformOrigin: 'top left',
display: blank ? 'none' : 'block',
})
Object.assign(element.style, {
width: `${(width ?? blankWidth) * scale}px`,
height: `${(height ?? blankHeight) * scale}px`,
overflow: 'hidden',
display: 'block',
flexShrink: '0',
marginBlock: 'auto',
})
if (portrait && frame !== target) {
element.style.display = 'none'
}
}
if (this.#center) {
transform(this.#center)
} else {
transform(left)
transform(right)
}
}
async #showSpread({ left, right, center, side }) {
this.#root.replaceChildren()
this.#left = null
this.#right = null
this.#center = null
if (center) {
this.#center = await this.#createFrame(center)
this.#side = 'center'
this.#render()
} else {
this.#left = await this.#createFrame(left)
this.#right = await this.#createFrame(right)
this.#side = this.#left.blank ? 'right'
: this.#right.blank ? 'left' : side
this.#render()
}
}
#goLeft() {
if (this.#center || this.#left?.blank) return
if (this.#portrait && this.#left?.element?.style?.display === 'none') {
this.#side = 'left'
this.#render()
this.#reportLocation('page')
return true
}
}
#goRight() {
if (this.#center || this.#right?.blank) return
if (this.#portrait && this.#right?.element?.style?.display === 'none') {
this.#side = 'right'
this.#render()
this.#reportLocation('page')
return true
}
}
open(book) {
this.book = book
const { rendition } = book
this.spread = rendition?.spread
this.defaultViewport = rendition?.viewport
const rtl = book.dir === 'rtl'
const ltr = !rtl
this.rtl = rtl
if (rendition?.spread === 'none')
this.#spreads = book.sections.map(section => ({ center: section }))
else this.#spreads = book.sections.reduce((arr, section, i) => {
const last = arr[arr.length - 1]
const { pageSpread } = section
const newSpread = () => {
const spread = {}
arr.push(spread)
return spread
}
if (pageSpread === 'center') {
const spread = last.left || last.right ? newSpread() : last
spread.center = section
}
else if (pageSpread === 'left') {
const spread = last.center || last.left || ltr && i ? newSpread() : last
spread.left = section
}
else if (pageSpread === 'right') {
const spread = last.center || last.right || rtl && i ? newSpread() : last
spread.right = section
}
else if (ltr) {
if (last.center || last.right) newSpread().left = section
else if (last.left || !i) last.right = section
else last.left = section
}
else {
if (last.center || last.left) newSpread().right = section
else if (last.right || !i) last.left = section
else last.right = section
}
return arr
}, [{}])
}
get index() {
const spread = this.#spreads[this.#index]
const section = spread?.center ?? (this.#side === 'left'
? spread.left ?? spread.right : spread.right ?? spread.left)
return this.book.sections.indexOf(section)
}
#reportLocation(reason) {
this.dispatchEvent(new CustomEvent('relocate', { detail:
{ reason, range: null, index: this.index, fraction: 0, size: 1 } }))
}
getSpreadOf(section) {
const spreads = this.#spreads
for (let index = 0; index < spreads.length; index++) {
const { left, right, center } = spreads[index]
if (left === section) return { index, side: 'left' }
if (right === section) return { index, side: 'right' }
if (center === section) return { index, side: 'center' }
}
}
async goToSpread(index, side, reason) {
if (index < 0 || index > this.#spreads.length - 1) return
if (index === this.#index) {
this.#render(side)
return
}
this.#index = index
const spread = this.#spreads[index]
if (spread.center) {
const index = this.book.sections.indexOf(spread.center)
const src = await spread.center?.load?.()
await this.#showSpread({ center: { index, src } })
} else {
const indexL = this.book.sections.indexOf(spread.left)
const indexR = this.book.sections.indexOf(spread.right)
const srcL = await spread.left?.load?.()
const srcR = await spread.right?.load?.()
const left = { index: indexL, src: srcL }
const right = { index: indexR, src: srcR }
await this.#showSpread({ left, right, side })
}
this.#reportLocation(reason)
}
async select(target) {
await this.goTo(target)
// TODO
}
async goTo(target) {
const { book } = this
const resolved = await target
const section = book.sections[resolved.index]
if (!section) return
const { index, side } = this.getSpreadOf(section)
await this.goToSpread(index, side)
}
async next() {
const s = this.rtl ? this.#goLeft() : this.#goRight()
if (!s) return this.goToSpread(this.#index + 1, this.rtl ? 'right' : 'left', 'page')
}
async prev() {
const s = this.rtl ? this.#goRight() : this.#goLeft()
if (!s) return this.goToSpread(this.#index - 1, this.rtl ? 'left' : 'right', 'page')
}
getContents() {
return Array.from(this.#root.querySelectorAll('iframe'), frame => ({
doc: frame.contentDocument,
// TODO: index, overlayer
}))
}
destroy() {
this.#observer.unobserve(this)
}
}
customElements.define('foliate-fxl', FixedLayout)
File diff suppressed because it is too large Load Diff
+175
View File
@@ -0,0 +1,175 @@
const createSVGElement = tag =>
document.createElementNS('http://www.w3.org/2000/svg', tag)
export class Overlayer {
#svg = createSVGElement('svg')
#map = new Map()
constructor() {
Object.assign(this.#svg.style, {
position: 'absolute', top: '0', left: '0',
width: '100%', height: '100%',
pointerEvents: 'none',
})
}
get element() {
return this.#svg
}
add(key, range, draw, options) {
if (this.#map.has(key)) this.remove(key)
if (typeof range === 'function') range = range(this.#svg.getRootNode())
const rects = range.getClientRects()
const element = draw(rects, options)
this.#svg.append(element)
this.#map.set(key, { range, draw, options, element, rects })
}
remove(key) {
if (!this.#map.has(key)) return
this.#svg.removeChild(this.#map.get(key).element)
this.#map.delete(key)
}
redraw() {
for (const obj of this.#map.values()) {
const { range, draw, options, element } = obj
this.#svg.removeChild(element)
const rects = range.getClientRects()
const el = draw(rects, options)
this.#svg.append(el)
obj.element = el
obj.rects = rects
}
}
hitTest({ x, y }) {
const arr = Array.from(this.#map.entries())
// loop in reverse to hit more recently added items first
for (let i = arr.length - 1; i >= 0; i--) {
const [key, obj] = arr[i]
for (const { left, top, right, bottom } of obj.rects)
if (top <= y && left <= x && bottom > y && right > x)
return [key, obj.range]
}
return []
}
static underline(rects, options = {}) {
const { color = 'red', width: strokeWidth = 2, writingMode } = options
const g = createSVGElement('g')
g.setAttribute('fill', color)
if (writingMode === 'vertical-rl' || writingMode === 'vertical-lr')
for (const { right, top, height } of rects) {
const el = createSVGElement('rect')
el.setAttribute('x', right - strokeWidth)
el.setAttribute('y', top)
el.setAttribute('height', height)
el.setAttribute('width', strokeWidth)
g.append(el)
}
else for (const { left, bottom, width } of rects) {
const el = createSVGElement('rect')
el.setAttribute('x', left)
el.setAttribute('y', bottom - strokeWidth)
el.setAttribute('height', strokeWidth)
el.setAttribute('width', width)
g.append(el)
}
return g
}
static strikethrough(rects, options = {}) {
const { color = 'red', width: strokeWidth = 2, writingMode } = options
const g = createSVGElement('g')
g.setAttribute('fill', color)
if (writingMode === 'vertical-rl' || writingMode === 'vertical-lr')
for (const { right, left, top, height } of rects) {
const el = createSVGElement('rect')
el.setAttribute('x', (right + left) / 2)
el.setAttribute('y', top)
el.setAttribute('height', height)
el.setAttribute('width', strokeWidth)
g.append(el)
}
else for (const { left, top, bottom, width } of rects) {
const el = createSVGElement('rect')
el.setAttribute('x', left)
el.setAttribute('y', (top + bottom) / 2)
el.setAttribute('height', strokeWidth)
el.setAttribute('width', width)
g.append(el)
}
return g
}
static squiggly(rects, options = {}) {
const { color = 'red', width: strokeWidth = 2, writingMode } = options
const g = createSVGElement('g')
g.setAttribute('fill', 'none')
g.setAttribute('stroke', color)
g.setAttribute('stroke-width', strokeWidth)
const block = strokeWidth * 1.5
if (writingMode === 'vertical-rl' || writingMode === 'vertical-lr')
for (const { right, top, height } of rects) {
const el = createSVGElement('path')
const n = Math.round(height / block / 1.5)
const inline = height / n
const ls = Array.from({ length: n },
(_, i) => `l${i % 2 ? -block : block} ${inline}`).join('')
el.setAttribute('d', `M${right} ${top}${ls}`)
g.append(el)
}
else for (const { left, bottom, width } of rects) {
const el = createSVGElement('path')
const n = Math.round(width / block / 1.5)
const inline = width / n
const ls = Array.from({ length: n },
(_, i) => `l${inline} ${i % 2 ? block : -block}`).join('')
el.setAttribute('d', `M${left} ${bottom}${ls}`)
g.append(el)
}
return g
}
static highlight(rects, options = {}) {
const { color = 'red' } = options
const g = createSVGElement('g')
g.setAttribute('fill', color)
g.style.opacity = 'var(--overlayer-highlight-opacity, .3)'
g.style.mixBlendMode = 'var(--overlayer-highlight-blend-mode, normal)'
for (const { left, top, height, width } of rects) {
const el = createSVGElement('rect')
el.setAttribute('x', left)
el.setAttribute('y', top)
el.setAttribute('height', height)
el.setAttribute('width', width)
g.append(el)
}
return g
}
static outline(rects, options = {}) {
const { color = 'red', width: strokeWidth = 3, radius = 3 } = options
const g = createSVGElement('g')
g.setAttribute('fill', 'none')
g.setAttribute('stroke', color)
g.setAttribute('stroke-width', strokeWidth)
for (const { left, top, height, width } of rects) {
const el = createSVGElement('rect')
el.setAttribute('x', left)
el.setAttribute('y', top)
el.setAttribute('height', height)
el.setAttribute('width', width)
el.setAttribute('rx', radius)
g.append(el)
}
return g
}
// make an exact copy of an image in the overlay
// one can then apply filters to the entire element, without affecting them;
// it's a bit silly and probably better to just invert images twice
// (though the color will be off in that case if you do heu-rotate)
static copyImage([rect], options = {}) {
const { src } = options
const image = createSVGElement('image')
const { left, top, height, width } = rect
image.setAttribute('href', src)
image.setAttribute('x', left)
image.setAttribute('y', top)
image.setAttribute('height', height)
image.setAttribute('width', width)
return image
}
}
File diff suppressed because it is too large Load Diff
+113
View File
@@ -0,0 +1,113 @@
// assign a unique ID for each TOC item
const assignIDs = toc => {
let id = 0
const assignID = item => {
item.id = id++
if (item.subitems) for (const subitem of item.subitems) assignID(subitem)
}
for (const item of toc) assignID(item)
return toc
}
const flatten = items => items
.map(item => item.subitems?.length
? [item, flatten(item.subitems)].flat()
: item)
.flat()
export class TOCProgress {
async init({ toc, ids, splitHref, getFragment }) {
assignIDs(toc)
const items = flatten(toc)
const grouped = new Map()
for (const [i, item] of items.entries()) {
const [id, fragment] = await splitHref(item?.href) ?? []
const value = { fragment, item }
if (grouped.has(id)) grouped.get(id).items.push(value)
else grouped.set(id, { prev: items[i - 1], items: [value] })
}
const map = new Map()
for (const [i, id] of ids.entries()) {
if (grouped.has(id)) map.set(id, grouped.get(id))
else map.set(id, map.get(ids[i - 1]))
}
this.ids = ids
this.map = map
this.getFragment = getFragment
}
getProgress(index, range) {
if (!this.ids) return
const id = this.ids[index]
const obj = this.map.get(id)
if (!obj) return null
const { prev, items } = obj
if (!items) return prev
if (!range || items.length === 1 && !items[0].fragment) return items[0].item
const doc = range.startContainer.getRootNode()
for (const [i, { fragment }] of items.entries()) {
const el = this.getFragment(doc, fragment)
if (!el) continue
if (range.comparePoint(el, 0) > 0)
return (items[i - 1]?.item ?? prev)
}
return items[items.length - 1].item
}
}
export class SectionProgress {
constructor(sections, sizePerLoc, sizePerTimeUnit) {
this.sizes = sections.map(s => s.linear != 'no' && s.size > 0 ? s.size : 0)
this.sizePerLoc = sizePerLoc
this.sizePerTimeUnit = sizePerTimeUnit
this.sizeTotal = this.sizes.reduce((a, b) => a + b, 0)
this.sectionFractions = this.#getSectionFractions()
}
#getSectionFractions() {
const { sizeTotal } = this
const results = [0]
let sum = 0
for (const size of this.sizes) results.push((sum += size) / sizeTotal)
return results
}
// get progress given index of and fractions within a section
getProgress(index, fractionInSection, pageFraction = 0) {
const { sizes, sizePerLoc, sizePerTimeUnit, sizeTotal } = this
const sizeInSection = sizes[index] ?? 0
const sizeBefore = sizes.slice(0, index).reduce((a, b) => a + b, 0)
const size = sizeBefore + fractionInSection * sizeInSection
const nextSize = size + pageFraction * sizeInSection
const remainingTotal = sizeTotal - size
const remainingSection = (1 - fractionInSection) * sizeInSection
return {
fraction: nextSize / sizeTotal,
section: {
current: index,
total: sizes.length,
},
location: {
current: Math.floor(size / sizePerLoc),
next: Math.floor(nextSize / sizePerLoc),
total: Math.ceil(sizeTotal / sizePerLoc),
},
time: {
section: remainingSection / sizePerTimeUnit,
total: remainingTotal / sizePerTimeUnit,
},
}
}
// the inverse of `getProgress`
// get index of and fraction in section based on total fraction
getSection(fraction) {
if (fraction <= 0) return [0, 0]
if (fraction >= 1) return [this.sizes.length - 1, 1]
fraction = fraction + Number.EPSILON
const { sizeTotal } = this
let index = this.sectionFractions.findIndex(x => x > fraction) - 1
if (index < 0) return [0, 0]
while (!this.sizes[index]) index++
const fractionInSection = (fraction - this.sectionFractions[index])
/ (this.sizes[index] / sizeTotal)
return [index, fractionInSection]
}
}
+130
View File
@@ -0,0 +1,130 @@
// length for context in excerpts
const CONTEXT_LENGTH = 50
const normalizeWhitespace = str => str.replace(/\s+/g, ' ')
const makeExcerpt = (strs, { startIndex, startOffset, endIndex, endOffset }) => {
const start = strs[startIndex]
const end = strs[endIndex]
const match = start === end
? start.slice(startOffset, endOffset)
: start.slice(startOffset)
+ strs.slice(start + 1, end).join('')
+ end.slice(0, endOffset)
const trimmedStart = normalizeWhitespace(start.slice(0, startOffset)).trimStart()
const trimmedEnd = normalizeWhitespace(end.slice(endOffset)).trimEnd()
const ellipsisPre = trimmedStart.length < CONTEXT_LENGTH ? '' : '…'
const ellipsisPost = trimmedEnd.length < CONTEXT_LENGTH ? '' : '…'
const pre = `${ellipsisPre}${trimmedStart.slice(-CONTEXT_LENGTH)}`
const post = `${trimmedEnd.slice(0, CONTEXT_LENGTH)}${ellipsisPost}`
return { pre, match, post }
}
const simpleSearch = function* (strs, query, options = {}) {
const { locales = 'en', sensitivity } = options
const matchCase = sensitivity === 'variant'
const haystack = strs.join('')
const lowerHaystack = matchCase ? haystack : haystack.toLocaleLowerCase(locales)
const needle = matchCase ? query : query.toLocaleLowerCase(locales)
const needleLength = needle.length
let index = -1
let strIndex = -1
let sum = 0
do {
index = lowerHaystack.indexOf(needle, index + 1)
if (index > -1) {
while (sum <= index) sum += strs[++strIndex].length
const startIndex = strIndex
const startOffset = index - (sum - strs[strIndex].length)
const end = index + needleLength
while (sum <= end) sum += strs[++strIndex].length
const endIndex = strIndex
const endOffset = end - (sum - strs[strIndex].length)
const range = { startIndex, startOffset, endIndex, endOffset }
yield { range, excerpt: makeExcerpt(strs, range) }
}
} while (index > -1)
}
const segmenterSearch = function* (strs, query, options = {}) {
const { locales = 'en', granularity = 'word', sensitivity = 'base' } = options
let segmenter, collator
try {
segmenter = new Intl.Segmenter(locales, { usage: 'search', granularity })
collator = new Intl.Collator(locales, { sensitivity })
} catch (e) {
console.warn(e)
segmenter = new Intl.Segmenter('en', { usage: 'search', granularity })
collator = new Intl.Collator('en', { sensitivity })
}
const queryLength = Array.from(segmenter.segment(query)).length
const substrArr = []
let strIndex = 0
let segments = segmenter.segment(strs[strIndex])[Symbol.iterator]()
main: while (strIndex < strs.length) {
while (substrArr.length < queryLength) {
const { done, value } = segments.next()
if (done) {
// the current string is exhausted
// move on to the next string
strIndex++
if (strIndex < strs.length) {
segments = segmenter.segment(strs[strIndex])[Symbol.iterator]()
continue
} else break main
}
const { index, segment } = value
// ignore formatting characters
if (!/[^\p{Format}]/u.test(segment)) continue
// normalize whitespace
if (/\s/u.test(segment)) {
if (!/\s/u.test(substrArr[substrArr.length - 1]?.segment))
substrArr.push({ strIndex, index, segment: ' ' })
continue
}
value.strIndex = strIndex
substrArr.push(value)
}
const substr = substrArr.map(x => x.segment).join('')
if (collator.compare(query, substr) === 0) {
const endIndex = strIndex
const lastSeg = substrArr[substrArr.length - 1]
const endOffset = lastSeg.index + lastSeg.segment.length
const startIndex = substrArr[0].strIndex
const startOffset = substrArr[0].index
const range = { startIndex, startOffset, endIndex, endOffset }
yield { range, excerpt: makeExcerpt(strs, range) }
}
substrArr.shift()
}
}
export const search = (strs, query, options) => {
const { granularity = 'grapheme', sensitivity = 'base' } = options
if (!Intl?.Segmenter || granularity === 'grapheme'
&& (sensitivity === 'variant' || sensitivity === 'accent'))
return simpleSearch(strs, query, options)
return segmenterSearch(strs, query, options)
}
export const searchMatcher = (textWalker, opts) => {
const { defaultLocale, matchCase, matchDiacritics, matchWholeWords, acceptNode } = opts
return function* (doc, query) {
const iter = textWalker(doc, function* (strs, makeRange) {
for (const result of search(strs, query, {
locales: doc.body.lang || doc.documentElement.lang || defaultLocale || 'en',
granularity: matchWholeWords ? 'word' : 'grapheme',
sensitivity: matchDiacritics && matchCase ? 'variant'
: matchDiacritics && !matchCase ? 'accent'
: !matchDiacritics && matchCase ? 'case'
: 'base',
})) {
const { startIndex, startOffset, endIndex, endOffset } = result.range
result.range = makeRange(startIndex, startOffset, endIndex, endOffset)
yield result
}
}, acceptNode)
for (const result of iter) yield result
}
}
@@ -0,0 +1,43 @@
const walkRange = (range, walker) => {
const nodes = []
for (let node = walker.currentNode; node; node = walker.nextNode()) {
const compare = range.comparePoint(node, 0)
if (compare === 0) nodes.push(node)
else if (compare > 0) break
}
return nodes
}
const walkDocument = (_, walker) => {
const nodes = []
for (let node = walker.nextNode(); node; node = walker.nextNode())
nodes.push(node)
return nodes
}
const filter = NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT
| NodeFilter.SHOW_CDATA_SECTION
const acceptNode = node => {
if (node.nodeType === 1) {
const name = node.tagName.toLowerCase()
if (name === 'script' || name === 'style') return NodeFilter.FILTER_REJECT
return NodeFilter.FILTER_SKIP
}
return NodeFilter.FILTER_ACCEPT
}
export const textWalker = function* (x, func, filterFunc) {
const root = x.commonAncestorContainer ?? x.body ?? x
const walker = document.createTreeWalker(root, filter, { acceptNode: filterFunc || acceptNode })
const walk = x.commonAncestorContainer ? walkRange : walkDocument
const nodes = walk(x, walker)
const strs = nodes.map(node => node.nodeValue)
const makeRange = (startIndex, startOffset, endIndex, endOffset) => {
const range = document.createRange()
range.setStart(nodes[startIndex], startOffset)
range.setEnd(nodes[endIndex], endOffset)
return range
}
for (const match of func(strs, makeRange)) yield match
}
+278
View File
@@ -0,0 +1,278 @@
const NS = {
XML: 'http://www.w3.org/XML/1998/namespace',
SSML: 'http://www.w3.org/2001/10/synthesis',
}
const blockTags = new Set([
'article', 'aside', 'audio', 'blockquote', 'caption',
'details', 'dialog', 'div', 'dl', 'dt', 'dd',
'figure', 'footer', 'form', 'figcaption',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'li',
'main', 'math', 'nav', 'ol', 'p', 'pre', 'section', 'tr',
])
const getLang = el => {
const x = el.lang || el?.getAttributeNS?.(NS.XML, 'lang')
return x ? x : el.parentElement ? getLang(el.parentElement) : null
}
const getAlphabet = el => {
const x = el?.getAttributeNS?.(NS.XML, 'lang')
return x ? x : el.parentElement ? getAlphabet(el.parentElement) : null
}
const getSegmenter = (lang = 'en', granularity = 'word') => {
const segmenter = new Intl.Segmenter(lang, { granularity })
const granularityIsWord = granularity === 'word'
return function* (strs, makeRange) {
const str = strs.join('')
let name = 0
let strIndex = -1
let sum = 0
for (const { index, segment, isWordLike } of segmenter.segment(str)) {
if (granularityIsWord && !isWordLike) continue
while (sum <= index) sum += strs[++strIndex].length
const startIndex = strIndex
const startOffset = index - (sum - strs[strIndex].length)
const end = index + segment.length - 1
if (end < str.length) while (sum <= end) sum += strs[++strIndex].length
const endIndex = strIndex
const endOffset = end - (sum - strs[strIndex].length) + 1
yield [(name++).toString(),
makeRange(startIndex, startOffset, endIndex, endOffset)]
}
}
}
const fragmentToSSML = (fragment, inherited) => {
const ssml = document.implementation.createDocument(NS.SSML, 'speak')
const { lang } = inherited
if (lang) ssml.documentElement.setAttributeNS(NS.XML, 'lang', lang)
const convert = (node, parent, inheritedAlphabet) => {
if (!node) return
if (node.nodeType === 3) return ssml.createTextNode(node.textContent)
if (node.nodeType === 4) return ssml.createCDATASection(node.textContent)
if (node.nodeType !== 1) return
let el
const nodeName = node.nodeName.toLowerCase()
if (nodeName === 'foliate-mark') {
el = ssml.createElementNS(NS.SSML, 'mark')
el.setAttribute('name', node.dataset.name)
}
else if (nodeName === 'br')
el = ssml.createElementNS(NS.SSML, 'break')
else if (nodeName === 'em' || nodeName === 'strong')
el = ssml.createElementNS(NS.SSML, 'emphasis')
const lang = node.lang || node.getAttributeNS(NS.XML, 'lang')
if (lang) {
if (!el) el = ssml.createElementNS(NS.SSML, 'lang')
el.setAttributeNS(NS.XML, 'lang', lang)
}
const alphabet = node.getAttributeNS(NS.SSML, 'alphabet') || inheritedAlphabet
if (!el) {
const ph = node.getAttributeNS(NS.SSML, 'ph')
if (ph) {
el = ssml.createElementNS(NS.SSML, 'phoneme')
if (alphabet) el.setAttribute('alphabet', alphabet)
el.setAttribute('ph', ph)
}
}
if (!el) el = parent
let child = node.firstChild
while (child) {
const childEl = convert(child, el, alphabet)
if (childEl && el !== childEl) el.append(childEl)
child = child.nextSibling
}
return el
}
convert(fragment.firstChild, ssml.documentElement, inherited.alphabet)
return ssml
}
const getFragmentWithMarks = (range, textWalker, granularity) => {
const lang = getLang(range.commonAncestorContainer)
const alphabet = getAlphabet(range.commonAncestorContainer)
const segmenter = getSegmenter(lang, granularity)
const fragment = range.cloneContents()
// we need ranges on both the original document (for highlighting)
// and the document fragment (for inserting marks)
// so unfortunately need to do it twice, as you can't copy the ranges
const entries = [...textWalker(range, segmenter)]
const fragmentEntries = [...textWalker(fragment, segmenter)]
for (const [name, range] of fragmentEntries) {
const mark = document.createElement('foliate-mark')
mark.dataset.name = name
range.insertNode(mark)
}
const ssml = fragmentToSSML(fragment, { lang, alphabet })
return { entries, ssml }
}
const rangeIsEmpty = range => !range.toString().trim()
function* getBlocks(doc) {
let last
const walker = doc.createTreeWalker(doc.body, NodeFilter.SHOW_ELEMENT)
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
const name = node.tagName.toLowerCase()
if (blockTags.has(name)) {
if (last) {
last.setEndBefore(node)
if (!rangeIsEmpty(last)) yield last
}
last = doc.createRange()
last.setStart(node, 0)
}
}
if (!last) {
last = doc.createRange()
last.setStart(doc.body.firstChild ?? doc.body, 0)
}
last.setEndAfter(doc.body.lastChild ?? doc.body)
if (!rangeIsEmpty(last)) yield last
}
class ListIterator {
#arr = []
#iter
#index = -1
#f
constructor(iter, f = x => x) {
this.#iter = iter
this.#f = f
}
current() {
if (this.#arr[this.#index]) return this.#f(this.#arr[this.#index])
}
first() {
const newIndex = 0
if (this.#arr[newIndex]) {
this.#index = newIndex
return this.#f(this.#arr[newIndex])
}
}
prev() {
const newIndex = this.#index - 1
if (this.#arr[newIndex]) {
this.#index = newIndex
return this.#f(this.#arr[newIndex])
}
}
next() {
const newIndex = this.#index + 1
if (this.#arr[newIndex]) {
this.#index = newIndex
return this.#f(this.#arr[newIndex])
}
while (true) {
const { done, value } = this.#iter.next()
if (done) break
this.#arr.push(value)
if (this.#arr[newIndex]) {
this.#index = newIndex
return this.#f(this.#arr[newIndex])
}
}
}
find(f) {
const index = this.#arr.findIndex(x => f(x))
if (index > -1) {
this.#index = index
return this.#f(this.#arr[index])
}
while (true) {
const { done, value } = this.#iter.next()
if (done) break
this.#arr.push(value)
if (f(value)) {
this.#index = this.#arr.length - 1
return this.#f(value)
}
}
}
}
export class TTS {
#list
#ranges
#lastMark
#serializer = new XMLSerializer()
constructor(doc, textWalker, highlight, granularity) {
this.doc = doc
this.highlight = highlight
this.#list = new ListIterator(getBlocks(doc), range => {
const { entries, ssml } = getFragmentWithMarks(range, textWalker, granularity)
this.#ranges = new Map(entries)
return [ssml, range]
})
}
#getMarkElement(doc, mark) {
if (!mark) return null
return doc.querySelector(`mark[name="${CSS.escape(mark)}"`)
}
#speak(doc, getNode) {
if (!doc) return
if (!getNode) return this.#serializer.serializeToString(doc)
const ssml = document.implementation.createDocument(NS.SSML, 'speak')
ssml.documentElement.replaceWith(ssml.importNode(doc.documentElement, true))
let node = getNode(ssml)?.previousSibling
while (node) {
const next = node.previousSibling ?? node.parentNode?.previousSibling
node.parentNode.removeChild(node)
node = next
}
return this.#serializer.serializeToString(ssml)
}
start() {
this.#lastMark = null
const [doc] = this.#list.first() ?? []
if (!doc) return this.next()
return this.#speak(doc, ssml => this.#getMarkElement(ssml, this.#lastMark))
}
resume() {
const [doc] = this.#list.current() ?? []
if (!doc) return this.next()
return this.#speak(doc, ssml => this.#getMarkElement(ssml, this.#lastMark))
}
prev(paused) {
this.#lastMark = null
const [doc, range] = this.#list.prev() ?? []
if (paused && range) this.highlight(range.cloneRange())
return this.#speak(doc)
}
next(paused) {
this.#lastMark = null
const [doc, range] = this.#list.next() ?? []
if (paused && range) this.highlight(range.cloneRange())
return this.#speak(doc)
}
from(range) {
this.#lastMark = null
const [doc] = this.#list.find(range_ =>
range.compareBoundaryPoints(Range.END_TO_START, range_) <= 0)
let mark
for (const [name, range_] of this.#ranges.entries())
if (range.compareBoundaryPoints(Range.START_TO_START, range_) <= 0) {
mark = name
break
}
return this.#speak(doc, ssml => this.#getMarkElement(ssml, mark))
}
setMark(mark) {
const range = this.#ranges.get(mark)
if (range) {
this.#lastMark = mark
this.highlight(range.cloneRange())
}
}
}
+1
View File
@@ -0,0 +1 @@
var r=Uint8Array,a=Uint16Array,e=Int32Array,n=new r([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new r([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),t=new r([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),f=function(r,n){for(var i=new a(31),t=0;t<31;++t)i[t]=n+=1<<r[t-1];var f=new e(i[30]);for(t=1;t<30;++t)for(var o=i[t];o<i[t+1];++o)f[o]=o-i[t]<<5|t;return{b:i,r:f}},o=f(n,2),v=o.b,l=o.r;v[28]=258,l[258]=28;for(var u=f(i,0).b,c=new a(32768),d=0;d<32768;++d){var w=(43690&d)>>1|(21845&d)<<1;w=(61680&(w=(52428&w)>>2|(13107&w)<<2))>>4|(3855&w)<<4,c[d]=((65280&w)>>8|(255&w)<<8)>>1}var b=function(r,e,n){for(var i=r.length,t=0,f=new a(e);t<i;++t)r[t]&&++f[r[t]-1];var o,v=new a(e);for(t=1;t<e;++t)v[t]=v[t-1]+f[t-1]<<1;if(n){o=new a(1<<e);var l=15-e;for(t=0;t<i;++t)if(r[t])for(var u=t<<4|r[t],d=e-r[t],w=v[r[t]-1]++<<d,b=w|(1<<d)-1;w<=b;++w)o[c[w]>>l]=u}else for(o=new a(i),t=0;t<i;++t)r[t]&&(o[t]=c[v[r[t]-1]++]>>15-r[t]);return o},s=new r(288);for(d=0;d<144;++d)s[d]=8;for(d=144;d<256;++d)s[d]=9;for(d=256;d<280;++d)s[d]=7;for(d=280;d<288;++d)s[d]=8;var h=new r(32);for(d=0;d<32;++d)h[d]=5;var y=b(s,9,1),g=b(h,5,1),p=function(r){for(var a=r[0],e=1;e<r.length;++e)r[e]>a&&(a=r[e]);return a},k=function(r,a,e){var n=a/8|0;return(r[n]|r[n+1]<<8)>>(7&a)&e},m=function(r,a){var e=a/8|0;return(r[e]|r[e+1]<<8|r[e+2]<<16)>>(7&a)},x=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],T=function(r,a,e){var n=new Error(a||x[r]);if(n.code=r,Error.captureStackTrace&&Error.captureStackTrace(n,T),!e)throw n;return n},E=function(a,e,f,o){var l=a.length,c=o?o.length:0;if(!l||e.f&&!e.l)return f||new r(0);var d=!f,w=d||2!=e.i,s=e.i;d&&(f=new r(3*l));var h=function(a){var e=f.length;if(a>e){var n=new r(Math.max(2*e,a));n.set(f),f=n}},x=e.f||0,E=e.p||0,z=e.b||0,A=e.l,U=e.d,D=e.m,F=e.n,M=8*l;do{if(!A){x=k(a,E,1);var S=k(a,E+1,3);if(E+=3,!S){var I=a[(N=4+((E+7)/8|0))-4]|a[N-3]<<8,O=N+I;if(O>l){s&&T(0);break}w&&h(z+I),f.set(a.subarray(N,O),z),e.b=z+=I,e.p=E=8*O,e.f=x;continue}if(1==S)A=y,U=g,D=9,F=5;else if(2==S){var j=k(a,E,31)+257,q=k(a,E+10,15)+4,B=j+k(a,E+5,31)+1;E+=14;for(var C=new r(B),G=new r(19),H=0;H<q;++H)G[t[H]]=k(a,E+3*H,7);E+=3*q;var J=p(G),K=(1<<J)-1,L=b(G,J,1);for(H=0;H<B;){var N,P=L[k(a,E,K)];if(E+=15&P,(N=P>>4)<16)C[H++]=N;else{var Q=0,R=0;for(16==N?(R=3+k(a,E,3),E+=2,Q=C[H-1]):17==N?(R=3+k(a,E,7),E+=3):18==N&&(R=11+k(a,E,127),E+=7);R--;)C[H++]=Q}}var V=C.subarray(0,j),W=C.subarray(j);D=p(V),F=p(W),A=b(V,D,1),U=b(W,F,1)}else T(1);if(E>M){s&&T(0);break}}w&&h(z+131072);for(var X=(1<<D)-1,Y=(1<<F)-1,Z=E;;Z=E){var $=(Q=A[m(a,E)&X])>>4;if((E+=15&Q)>M){s&&T(0);break}if(Q||T(2),$<256)f[z++]=$;else{if(256==$){Z=E,A=null;break}var _=$-254;if($>264){var rr=n[H=$-257];_=k(a,E,(1<<rr)-1)+v[H],E+=rr}var ar=U[m(a,E)&Y],er=ar>>4;ar||T(3),E+=15&ar;W=u[er];if(er>3){rr=i[er];W+=m(a,E)&(1<<rr)-1,E+=rr}if(E>M){s&&T(0);break}w&&h(z+131072);var nr=z+_;if(z<W){var ir=c-W,tr=Math.min(W,nr);for(ir+z<0&&T(3);z<tr;++z)f[z]=o[ir+z]}for(;z<nr;++z)f[z]=f[z-W]}}e.l=A,e.p=Z,e.b=z,e.f=x,A&&(x=1,e.m=D,e.d=U,e.n=F)}while(!x);return z!=f.length&&d?function(a,e,n){return(null==n||n>a.length)&&(n=a.length),new r(a.subarray(e,n))}(f,0,z):f.subarray(0,z)},z=new r(0);function A(r,a){return E(r.subarray((e=r,n=a&&a.dictionary,(8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31)&&T(6,"invalid zlib data"),(e[1]>>5&1)==+!n&&T(6,"invalid zlib data: "+(32&e[1]?"need":"unexpected")+" dictionary"),2+(e[1]>>3&4)),-4),{i:2},a&&a.out,a&&a.dictionary);var e,n}var U="undefined"!=typeof TextDecoder&&new TextDecoder;try{U.decode(z,{stream:!0})}catch(r){}export{A as unzlibSync};
File diff suppressed because one or more lines are too long
+655
View File
@@ -0,0 +1,655 @@
import * as CFI from './epubcfi.js'
import {SectionProgress, TOCProgress} from './progress.js'
import {Overlayer} from './overlayer.js'
import {textWalker} from './text-walker.js'
const SEARCH_PREFIX = 'foliate-search:'
const isZip = async file => {
const arr = new Uint8Array(await file.slice(0, 4).arrayBuffer())
return arr[0] === 0x50 && arr[1] === 0x4b && arr[2] === 0x03 && arr[3] === 0x04
}
const isPDF = async file => {
const arr = new Uint8Array(await file.slice(0, 5).arrayBuffer())
return arr[0] === 0x25
&& arr[1] === 0x50 && arr[2] === 0x44 && arr[3] === 0x46
&& arr[4] === 0x2d
}
const isCBZ = ({name, type}) =>
type === 'application/vnd.comicbook+zip' || name.endsWith('.cbz')
const isFB2 = async file => {
const {name, type} = file
console.log('[isFB2] name:', name, 'type:', type)
if (type === 'application/x-fictionbook+xml' || (name && name.endsWith('.fb2'))) {
return true
}
// Check file content for FB2 XML signature
try {
const arr = new Uint8Array(await file.slice(0, 5).arrayBuffer())
// '<?xml' in UTF-8: 60 63 120 109 108
const isXml = arr[0] === 0x3c && arr[1] === 0x3f && arr[2] === 0x78 && arr[3] === 0x6d && arr[4] === 0x6c
if (isXml) {
console.log('[isFB2] Detected FB2 XML signature in file content')
return true
}
} catch (e) {
console.error('[isFB2] Error reading file content:', e)
}
return false
}
const isFBZ = ({name, type}) =>
type === 'application/x-zip-compressed-fb2'
|| name.endsWith('.fb2.zip') || name.endsWith('.fbz')
const makeZipLoader = async file => {
const {configure, ZipReader, BlobReader, TextWriter, BlobWriter} =
await import('./vendor/zip.js')
configure({useWebWorkers: false})
const reader = new ZipReader(new BlobReader(file))
const entries = await reader.getEntries()
const map = new Map(entries.map(entry => [entry.filename, entry]))
const load = f => (name, ...args) =>
map.has(name) ? f(map.get(name), ...args) : null
const loadText = load(entry => entry.getData(new TextWriter()))
const loadBlob = load((entry, type) => entry.getData(new BlobWriter(type)))
const getSize = name => map.get(name)?.uncompressedSize ?? 0
return {entries, loadText, loadBlob, getSize}
}
const getFileEntries = async entry => entry.isFile ? entry
: (await Promise.all(Array.from(
await new Promise((resolve, reject) => entry.createReader()
.readEntries(entries => resolve(entries), error => reject(error))),
getFileEntries))).flat()
const makeDirectoryLoader = async entry => {
const entries = await getFileEntries(entry)
const files = await Promise.all(
entries.map(entry => new Promise((resolve, reject) =>
entry.file(file => resolve([file, entry.fullPath]),
error => reject(error)))))
const map = new Map(files.map(([file, path]) =>
[path.replace(entry.fullPath + '/', ''), file]))
const decoder = new TextDecoder()
const decode = x => x ? decoder.decode(x) : null
const getBuffer = name => map.get(name)?.arrayBuffer() ?? null
const loadText = async name => decode(await getBuffer(name))
const loadBlob = name => map.get(name)
const getSize = name => map.get(name)?.size ?? 0
return {loadText, loadBlob, getSize}
}
export class ResponseError extends Error {
}
export class NotFoundError extends Error {
}
export class UnsupportedTypeError extends Error {
}
const fetchFile = async url => {
const res = await fetch(url)
if (!res.ok) throw new ResponseError(
`${res.status} ${res.statusText}`, {cause: res})
return new File([await res.blob()], new URL(res.url).pathname)
}
export const makeBook = async file => {
if (typeof file === 'string') file = await fetchFile(file)
let book
if (file.isDirectory) {
const loader = await makeDirectoryLoader(file)
const {EPUB} = await import('./epub.js')
book = await new EPUB(loader).init()
} else if (!file.size) throw new NotFoundError('File not found')
else if (await isZip(file)) {
const loader = await makeZipLoader(file)
if (isCBZ(file)) {
const {makeComicBook} = await import('./comic-book.js')
book = makeComicBook(loader, file)
} else if (isFBZ(file)) {
const {makeFB2} = await import('./fb2.js')
const {entries} = loader
const entry = entries.find(entry => entry.filename.endsWith('.fb2'))
const blob = await loader.loadBlob((entry ?? entries[0]).filename)
book = await makeFB2(blob)
} else {
const {EPUB} = await import('./epub.js')
book = await new EPUB(loader).init()
}
} else if (await isPDF(file)) {
const {makePDF} = await import('./pdf.js')
book = await makePDF(file)
} else {
const {isMOBI, MOBI} = await import('./mobi.js')
if (await isMOBI(file)) {
const fflate = await import('./vendor/fflate.js')
book = await new MOBI({unzlib: fflate.unzlibSync}).open(file)
} else if (isFB2(file)) {
const {makeFB2} = await import('./fb2.js')
book = await makeFB2(file)
}
}
if (!book) throw new UnsupportedTypeError('File type not supported')
return book
}
class CursorAutohider {
#timeout
#el
#check
#state
constructor(el, check, state = {}) {
this.#el = el
this.#check = check
this.#state = state
if (this.#state.hidden) this.hide()
this.#el.addEventListener('mousemove', ({screenX, screenY}) => {
// check if it actually moved
if (screenX === this.#state.x && screenY === this.#state.y) return
this.#state.x = screenX, this.#state.y = screenY
this.show()
if (this.#timeout) clearTimeout(this.#timeout)
if (check()) this.#timeout = setTimeout(this.hide.bind(this), 1000)
}, false)
}
cloneFor(el) {
return new CursorAutohider(el, this.#check, this.#state)
}
hide() {
this.#el.style.cursor = 'none'
this.#state.hidden = true
}
show() {
this.#el.style.removeProperty('cursor')
this.#state.hidden = false
}
}
class History extends EventTarget {
#arr = []
#index = -1
pushState(x) {
const last = this.#arr[this.#index]
if (last === x || last?.fraction && last.fraction === x.fraction) return
this.#arr[++this.#index] = x
this.#arr.length = this.#index + 1
this.dispatchEvent(new Event('index-change'))
}
replaceState(x) {
const index = this.#index
this.#arr[index] = x
}
back() {
const index = this.#index
if (index <= 0) return
const detail = {state: this.#arr[index - 1]}
this.#index = index - 1
this.dispatchEvent(new CustomEvent('popstate', {detail}))
this.dispatchEvent(new Event('index-change'))
}
forward() {
const index = this.#index
if (index >= this.#arr.length - 1) return
const detail = {state: this.#arr[index + 1]}
this.#index = index + 1
this.dispatchEvent(new CustomEvent('popstate', {detail}))
this.dispatchEvent(new Event('index-change'))
}
get canGoBack() {
return this.#index > 0
}
get canGoForward() {
return this.#index < this.#arr.length - 1
}
clear() {
this.#arr = []
this.#index = -1
}
}
const languageInfo = lang => {
if (!lang) return {}
try {
const canonical = Intl.getCanonicalLocales(lang)[0]
const locale = new Intl.Locale(canonical)
const isCJK = ['zh', 'ja', 'kr'].includes(locale.language)
const direction = (locale.getTextInfo?.() ?? locale.textInfo)?.direction
return {canonical, locale, isCJK, direction}
} catch (e) {
console.warn(e)
return {}
}
}
export class View extends HTMLElement {
#root = this.attachShadow({mode: 'closed'})
#sectionProgress
#tocProgress
#pageProgress
#searchResults = new Map()
#cursorAutohider = new CursorAutohider(this, () =>
this.hasAttribute('autohide-cursor'))
isFixedLayout = false
lastLocation
history = new History()
constructor() {
super()
this.history.addEventListener('popstate', ({detail}) => {
const resolved = this.resolveNavigation(detail.state)
this.renderer.goTo(resolved)
})
}
async open(book) {
if (typeof book === 'string'
|| typeof book.arrayBuffer === 'function'
|| book.isDirectory) book = await makeBook(book)
this.book = book
this.language = languageInfo(book.metadata?.language)
if (book.splitTOCHref && book.getTOCFragment) {
const ids = book.sections.map(s => s.id)
this.#sectionProgress = new SectionProgress(book.sections, 1500, 1600)
const splitHref = book.splitTOCHref.bind(book)
const getFragment = book.getTOCFragment.bind(book)
this.#tocProgress = new TOCProgress()
await this.#tocProgress.init({
toc: book.toc ?? [], ids, splitHref, getFragment
})
this.#pageProgress = new TOCProgress()
await this.#pageProgress.init({
toc: book.pageList ?? [], ids, splitHref, getFragment
})
}
this.isFixedLayout = this.book.rendition?.layout === 'pre-paginated'
if (this.isFixedLayout) {
await import('./fixed-layout.js')
this.renderer = document.createElement('foliate-fxl')
} else {
await import('./paginator.js')
this.renderer = document.createElement('foliate-paginator')
}
this.renderer.setAttribute('exportparts', 'head,foot,filter')
this.renderer.addEventListener('load', e => this.#onLoad(e.detail))
this.renderer.addEventListener('relocate', e => this.#onRelocate(e.detail))
this.renderer.addEventListener('create-overlayer', e =>
e.detail.attach(this.#createOverlayer(e.detail)))
this.renderer.open(book)
this.#root.append(this.renderer)
if (book.sections.some(section => section.mediaOverlay)) {
const activeClass = book.media.activeClass
const playbackActiveClass = book.media.playbackActiveClass
this.mediaOverlay = book.getMediaOverlay()
let lastActive
this.mediaOverlay.addEventListener('highlight', e => {
const resolved = this.resolveNavigation(e.detail.text)
this.renderer.goTo(resolved)
.then(() => {
const {doc} = this.renderer.getContents()
.find(x => x.index = resolved.index)
const el = resolved.anchor(doc)
el.classList.add(activeClass)
if (playbackActiveClass) el.ownerDocument
.documentElement.classList.add(playbackActiveClass)
lastActive = new WeakRef(el)
})
})
this.mediaOverlay.addEventListener('unhighlight', () => {
const el = lastActive?.deref()
if (el) {
el.classList.remove(activeClass)
if (playbackActiveClass) el.ownerDocument
.documentElement.classList.remove(playbackActiveClass)
}
})
}
}
close() {
this.renderer?.destroy()
this.renderer?.remove()
this.#sectionProgress = null
this.#tocProgress = null
this.#pageProgress = null
this.#searchResults = new Map()
this.lastLocation = null
this.history.clear()
this.tts = null
this.mediaOverlay = null
}
goToTextStart() {
return this.goTo(this.book.landmarks
?.find(m => m.type.includes('bodymatter') || m.type.includes('text'))
?.href ?? this.book.sections.findIndex(s => s.linear !== 'no'))
}
async init({lastLocation, showTextStart}) {
const resolved = lastLocation ? this.resolveNavigation(lastLocation) : null
if (resolved) {
await this.renderer.goTo(resolved)
this.history.pushState(lastLocation)
} else if (showTextStart) await this.goToTextStart()
else {
this.history.pushState(0)
await this.next()
}
}
#emit(name, detail, cancelable) {
return this.dispatchEvent(new CustomEvent(name, {detail, cancelable}))
}
#onRelocate({reason, range, index, fraction, size}) {
const progress = this.#sectionProgress?.getProgress(index, fraction, size) ?? {}
const tocItem = this.#tocProgress?.getProgress(index, range)
const pageItem = this.#pageProgress?.getProgress(index, range)
const cfi = this.getCFI(index, range)
this.lastLocation = {...progress, tocItem, pageItem, cfi, range}
if (reason === 'snap' || reason === 'page' || reason === 'scroll')
this.history.replaceState(cfi)
this.#emit('relocate', this.lastLocation)
}
#onLoad({doc, index}) {
// set language and dir if not already set
doc.documentElement.lang ||= this.language.canonical ?? ''
if (!this.language.isCJK)
doc.documentElement.dir ||= this.language.direction ?? ''
this.#handleLinks(doc, index)
this.#cursorAutohider.cloneFor(doc.documentElement)
this.#emit('load', {doc, index})
}
#handleLinks(doc, index) {
const {book} = this
const section = book.sections[index]
doc.addEventListener('click', e => {
const a = e.target.closest('a[href]')
if (!a) return
e.preventDefault()
const href_ = a.getAttribute('href')
const href = section?.resolveHref?.(href_) ?? href_
if (book?.isExternal?.(href))
Promise.resolve(this.#emit('external-link', {a, href}, true))
.then(x => x ? globalThis.open(href, '_blank') : null)
.catch(e => console.error(e))
else Promise.resolve(this.#emit('link', {a, href}, true))
.then(x => x ? this.goTo(href) : null)
.catch(e => console.error(e))
})
}
async addAnnotation(annotation, remove) {
const {value} = annotation
if (value.startsWith(SEARCH_PREFIX)) {
const cfi = value.replace(SEARCH_PREFIX, '')
const {index, anchor} = await this.resolveNavigation(cfi)
const obj = this.#getOverlayer(index)
if (obj) {
const {overlayer, doc} = obj
if (remove) {
overlayer.remove(value)
return
}
const range = doc ? anchor(doc) : anchor
overlayer.add(value, range, Overlayer.outline)
}
return
}
const {index, anchor} = await this.resolveNavigation(value)
const obj = this.#getOverlayer(index)
if (obj) {
const {overlayer, doc} = obj
overlayer.remove(value)
if (!remove) {
const range = doc ? anchor(doc) : anchor
const draw = (func, opts) => overlayer.add(value, range, func, opts)
this.#emit('draw-annotation', {draw, annotation, doc, range})
}
}
const label = this.#tocProgress.getProgress(index)?.label ?? ''
return {index, label}
}
deleteAnnotation(annotation) {
return this.addAnnotation(annotation, true)
}
#getOverlayer(index) {
return this.renderer.getContents()
.find(x => x.index === index && x.overlayer)
}
#createOverlayer({doc, index}) {
const overlayer = new Overlayer()
doc.addEventListener('click', e => {
const [value, range] = overlayer.hitTest(e)
if (value && !value.startsWith(SEARCH_PREFIX)) {
this.#emit('show-annotation', {value, index, range})
}
}, false)
const list = this.#searchResults.get(index)
if (list) for (const item of list) this.addAnnotation(item)
this.#emit('create-overlay', {index})
return overlayer
}
async showAnnotation(annotation) {
const {value} = annotation
const resolved = await this.goTo(value)
if (resolved) {
const {index, anchor} = resolved
const {doc} = this.#getOverlayer(index)
const range = anchor(doc)
this.#emit('show-annotation', {value, index, range})
}
}
getCFI(index, range) {
const baseCFI = this.book.sections[index].cfi ?? CFI.fake.fromIndex(index)
if (!range) return baseCFI
return CFI.joinIndir(baseCFI, CFI.fromRange(range))
}
resolveCFI(cfi) {
if (this.book.resolveCFI)
return this.book.resolveCFI(cfi)
else {
const parts = CFI.parse(cfi)
const index = CFI.fake.toIndex((parts.parent ?? parts).shift())
const anchor = doc => CFI.toRange(doc, parts)
return {index, anchor}
}
}
resolveNavigation(target) {
try {
if (typeof target === 'number') return {index: target}
if (typeof target.fraction === 'number') {
const [index, anchor] = this.#sectionProgress.getSection(target.fraction)
return {index, anchor}
}
if (CFI.isCFI.test(target)) return this.resolveCFI(target)
return this.book.resolveHref(target)
} catch (e) {
console.error(e)
console.error(`Could not resolve target ${target}`)
}
}
async goTo(target) {
const resolved = this.resolveNavigation(target)
try {
await this.renderer.goTo(resolved)
this.history.pushState(target)
return resolved
} catch (e) {
console.error(e)
console.error(`Could not go to ${target}`)
}
}
async goToFraction(frac) {
const [index, anchor] = this.#sectionProgress.getSection(frac)
await this.renderer.goTo({index, anchor})
this.history.pushState({fraction: frac})
}
async select(target) {
try {
const obj = await this.resolveNavigation(target)
await this.renderer.goTo({...obj, select: true})
this.history.pushState(target)
} catch (e) {
console.error(e)
console.error(`Could not go to ${target}`)
}
}
deselect() {
for (const {doc} of this.renderer.getContents())
doc.defaultView.getSelection().removeAllRanges()
}
getSectionFractions() {
return (this.#sectionProgress?.sectionFractions ?? [])
.map(x => x + Number.EPSILON)
}
getProgressOf(index, range) {
const tocItem = this.#tocProgress?.getProgress(index, range)
const pageItem = this.#pageProgress?.getProgress(index, range)
return {tocItem, pageItem}
}
async getTOCItemOf(target) {
try {
const {index, anchor} = await this.resolveNavigation(target)
const doc = await this.book.sections[index].createDocument()
const frag = anchor(doc)
const isRange = frag instanceof Range
const range = isRange ? frag : doc.createRange()
if (!isRange) range.selectNodeContents(frag)
return this.#tocProgress.getProgress(index, range)
} catch (e) {
console.error(e)
console.error(`Could not get ${target}`)
}
}
async prev(distance) {
await this.renderer.prev(distance)
}
async next(distance) {
await this.renderer.next(distance)
}
goLeft() {
return this.book.dir === 'rtl' ? this.next() : this.prev()
}
goRight() {
return this.book.dir === 'rtl' ? this.prev() : this.next()
}
async* #searchSection(matcher, query, index) {
const doc = await this.book.sections[index].createDocument()
for (const {range, excerpt} of matcher(doc, query))
yield {cfi: this.getCFI(index, range), excerpt}
}
async* #searchBook(matcher, query) {
const {sections} = this.book
for (const [index, {createDocument}] of sections.entries()) {
if (!createDocument) continue
const doc = await createDocument()
const subitems = Array.from(matcher(doc, query), ({range, excerpt}) =>
({cfi: this.getCFI(index, range), excerpt}))
const progress = (index + 1) / sections.length
yield {progress}
if (subitems.length) yield {index, subitems}
}
}
async* search(opts) {
this.clearSearch()
const {searchMatcher} = await import('./search.js')
const {query, index} = opts
const matcher = searchMatcher(textWalker,
{defaultLocale: this.language, ...opts})
const iter = index != null
? this.#searchSection(matcher, query, index)
: this.#searchBook(matcher, query)
const list = []
this.#searchResults.set(index, list)
for await (const result of iter) {
if (result.subitems) {
const list = result.subitems
.map(({cfi}) => ({value: SEARCH_PREFIX + cfi}))
this.#searchResults.set(result.index, list)
for (const item of list) this.addAnnotation(item)
yield {
label: this.#tocProgress.getProgress(result.index)?.label ?? '',
subitems: result.subitems,
}
} else {
if (result.cfi) {
const item = {value: SEARCH_PREFIX + result.cfi}
list.push(item)
this.addAnnotation(item)
}
yield result
}
}
yield 'done'
}
clearSearch() {
for (const list of this.#searchResults.values())
for (const item of list) this.deleteAnnotation(item)
this.#searchResults.clear()
}
async initTTS(granularity = 'word', highlight) {
const doc = this.renderer.getContents()[0].doc
if (this.tts && this.tts.doc === doc) return
const {TTS} = await import('./tts.js')
this.tts = new TTS(doc, textWalker, highlight || (range =>
this.renderer.scrollToAnchor(range, true)), granularity)
}
startMediaOverlay() {
const {index} = this.renderer.getContents()[0]
return this.mediaOverlay.start(index)
}
}
customElements.define('foliate-view', View)