Implement streaming EPUB reader with on-demand loading (#2350)

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-01-19 18:07:57 -07:00
committed by GitHub
co-authored by acx10
parent da83a70281
commit 7efb0e138d
36 changed files with 2237 additions and 106 deletions
@@ -1,6 +1,5 @@
import { inject } from '@angular/core';
import { CanActivateFn } from '@angular/router';
import { Router } from '@angular/router';
import {inject} from '@angular/core';
import {CanActivateFn, Router} from '@angular/router';
import {AuthService} from '../../shared/service/auth.service';
import {OAuthService} from 'angular-oauth2-oidc';
@@ -235,14 +235,14 @@ describe('BookService', () => {
describe('Reading & Viewer Settings', () => {
it('should navigate to correct reader and update last read time', () => {
service.readBook(1, 'ngx');
expect(routerMock.navigate).toHaveBeenCalledWith(['/pdf-reader/book/1']);
service.readBook(1);
expect(routerMock.navigate).toHaveBeenCalledWith(['/pdf-reader/book/1'], undefined);
expect(bookPatchServiceMock.updateLastReadTime).toHaveBeenCalledWith(1);
});
it('should not navigate if book not found', () => {
bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [], loaded: true, error: null});
service.readBook(999, 'ngx');
service.readBook(999);
expect(routerMock.navigate).not.toHaveBeenCalled();
});
@@ -244,7 +244,7 @@ export class BookService {
/*------------------ Reading & Viewer Settings ------------------*/
readBook(bookId: number, reader: 'ngx' | 'streaming' = 'ngx'): void {
readBook(bookId: number, reader?: 'pdf-streaming' | 'epub-streaming'): void {
const book = this.bookStateService
.getCurrentBookState()
.books?.find(b => b.id === bookId);
@@ -254,23 +254,39 @@ export class BookService {
return;
}
const baseUrl =
book.bookType === 'PDF'
? reader === 'ngx'
? 'pdf-reader'
: 'cbx-reader'
: book.bookType === 'EPUB' || book.bookType === 'FB2' || book.bookType === 'MOBI' || book.bookType === 'AZW3'
? 'ebook-reader'
: book.bookType === 'CBX'
? 'cbx-reader'
: null;
let baseUrl: string | null = null;
let queryParams: Record<string, any> | undefined;
switch (book.bookType) {
case 'PDF':
baseUrl = reader === 'pdf-streaming' ? 'cbx-reader' : 'pdf-reader';
break;
case 'EPUB':
baseUrl = 'ebook-reader';
if (reader === 'epub-streaming') {
queryParams = { streaming: true };
}
break;
case 'FB2':
case 'MOBI':
case 'AZW3':
baseUrl = 'ebook-reader';
break;
case 'CBX':
baseUrl = 'cbx-reader';
break;
}
if (!baseUrl) {
console.error('Unsupported book type:', book.bookType);
return;
}
this.router.navigate([`/${baseUrl}/book/${book.id}`]);
this.router.navigate([`/${baseUrl}/book/${book.id}`], queryParams ? { queryParams } : undefined);
this.updateLastReadTime(book.id);
}
@@ -555,13 +555,19 @@
<p-divider layout="vertical" class="action-divider"></p-divider>
}
@if (book!.bookType === 'PDF') {
@if (readMenuItems$ | async; as readItems) {
<p-splitbutton label="Read" icon="pi pi-book" [model]="readItems" (onClick)="read(book.id, 'ngx')" severity="primary"/>
@if (pdfReadMenuItems$ | async; as readItems) {
<p-splitbutton label="Read" outlined icon="pi pi-book" [model]="readItems" (onClick)="read(book.id)" severity="primary"/>
}
}
@if (book!.bookType !== 'PDF') {
<p-button label="Read" icon="pi pi-book" (onClick)="read(book?.metadata!.bookId, undefined)" severity="primary"/>
@if (book!.bookType === 'EPUB') {
@if (epubReadMenuItems$ | async; as readItems) {
<p-splitbutton label="Read" outlined icon="pi pi-book" [model]="readItems" (onClick)="read(book.id)" severity="primary"/>
}
}
@if (book!.bookType !== 'PDF' && book!.bookType !== 'EPUB') {
<p-button label="Read" outlined icon="pi pi-book" (onClick)="read(book?.metadata!.bookId, undefined)" severity="primary"/>
}
<p-divider layout="vertical"></p-divider>
<p-button label="Shelf" icon="pi pi-folder" severity="info" outlined (onClick)="assignShelf(book.id)" class="mobile-icon-only"></p-button>
@if (userState.user!.permissions.canDownload || userState.user!.permissions.admin) {
@if ((book!.alternativeFormats && book!.alternativeFormats.length > 0) || (book!.supplementaryFiles && book!.supplementaryFiles.length > 0)) {
@@ -575,7 +581,7 @@
@if (userState.user!.permissions.canEditMetadata || userState.user!.permissions.admin) {
@if (refreshMenuItems$ | async; as refreshItems) {
<p-splitbutton
[label]="isAutoFetching ? 'Fetching...' : 'Auto Fetch'"
[label]="isAutoFetching ? 'Fetching...' : 'Fetch'"
[icon]="isAutoFetching ? 'pi pi-spin pi-spinner' : 'pi pi-bolt'"
[outlined]="true"
[model]="refreshItems"
@@ -584,13 +590,13 @@
[disabled]="isAutoFetching"
pTooltip="Automatically fetch metadata using default sources"
tooltipPosition="top"
styleClass="mobile-icon-only">
class="mobile-icon-only">
</p-splitbutton>
}
}
@if (otherItems$ | async; as otherItems) {
@if (otherItems.length > 0) {
<p-button icon="pi pi-ellipsis-v" outlined severity="primary" (click)="entitymenu.toggle($event)"></p-button>
<p-button icon="pi pi-ellipsis-v" outlined severity="danger" (click)="entitymenu.toggle($event)"></p-button>
<p-tieredMenu #entitymenu [model]="otherItems" [popup]="true" appendTo="body"></p-tieredMenu>
}
}
@@ -472,7 +472,6 @@
.action-buttons {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
align-items: center;
}
@@ -70,7 +70,8 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
private destroyRef = inject(DestroyRef);
private dialogRef?: DynamicDialogRef;
readMenuItems$!: Observable<MenuItem[]>;
pdfReadMenuItems$!: Observable<MenuItem[]>;
epubReadMenuItems$!: Observable<MenuItem[]>;
refreshMenuItems$!: Observable<MenuItem[]>;
otherItems$!: Observable<MenuItem[]>;
downloadMenuItems$!: Observable<MenuItem[]>;
@@ -116,12 +117,22 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
])
);
this.readMenuItems$ = this.book$.pipe(
this.pdfReadMenuItems$ = this.book$.pipe(
filter((book): book is Book => book !== null),
map((book): MenuItem[] => [
{
label: 'Streaming Reader',
command: () => this.read(book.id, 'streaming')
command: () => this.read(book.id, 'pdf-streaming')
}
])
);
this.epubReadMenuItems$ = this.book$.pipe(
filter((book): book is Book => book !== null),
map((book): MenuItem[] => [
{
label: 'Streaming Reader (Beta)',
command: () => this.read(book.id, 'epub-streaming')
}
])
);
@@ -369,7 +380,7 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
this.isExpanded = !this.isExpanded;
}
read(bookId: number | undefined, reader: "ngx" | "streaming" | undefined): void {
read(bookId: number | undefined, reader?: "pdf-streaming" | "epub-streaming"): void {
if (bookId) this.bookService.readBook(bookId, reader);
}
@@ -88,9 +88,11 @@
</div>
}
} @else {
<div class="loading-container">
<p-progressSpinner class="custom-spinner"></p-progressSpinner>
<p class="loading-text">Processing pages... This may take a few seconds on first load. Future loads will be significantly faster.</p>
<div class="loader-overlay">
<div class="loader-content">
<div class="spinner"></div>
<p class="loader-text">Loading book...</p>
</div>
</div>
}
</div>
@@ -458,3 +458,45 @@
}
}
}
.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);
}
}
@@ -313,11 +313,14 @@ $transition-fast: 150ms ease;
display: none;
}
.page-nav-left,
.page-nav-right {
.page-nav-left {
gap: 4px;
}
.page-nav-right {
display: none;
}
.page-nav-left {
margin: 0 auto;
justify-content: center;
@@ -1,21 +1,25 @@
<div class="cbx-header" [class.visible]="isVisible">
<button class="icon-btn" (click)="onOpenSidebar()" title="Contents">
<app-reader-icon name="menu" [size]="20" />
</button>
<button class="icon-btn" (click)="onToggleBookmark()" [title]="isCurrentPageBookmarked ? 'Remove Bookmark' : 'Add Bookmark'" [class.active]="isCurrentPageBookmarked">
<app-reader-icon name="bookmark" [size]="20" />
</button>
<button class="icon-btn" (click)="onOpenNoteDialog()" [title]="currentPageHasNotes ? 'Page has notes - Add another' : 'Add Note'" [class.has-notes]="currentPageHasNotes">
<app-reader-icon name="note" [size]="20" />
@if (currentPageHasNotes) {
<span class="indicator-dot"></span>
}
</button>
<div class="header-left">
<button class="icon-btn" (click)="onOpenSidebar()" title="Contents">
<app-reader-icon name="menu" [size]="20" />
</button>
<button class="icon-btn" (click)="onToggleBookmark()" [title]="isCurrentPageBookmarked ? 'Remove Bookmark' : 'Add Bookmark'" [class.active]="isCurrentPageBookmarked">
<app-reader-icon name="bookmark" [size]="20" />
</button>
<button class="icon-btn" (click)="onOpenNoteDialog()" [title]="currentPageHasNotes ? 'Page has notes - Add another' : 'Add Note'" [class.has-notes]="currentPageHasNotes">
<app-reader-icon name="note" [size]="20" />
@if (currentPageHasNotes) {
<span class="indicator-dot"></span>
}
</button>
</div>
<span class="book-title">{{ bookTitle }}</span>
<button class="icon-btn" (click)="onOpenSettings()" title="Settings">
<app-reader-icon name="settings" [size]="20" />
</button>
<button class="icon-btn close-btn" (click)="onClose(); $event.stopPropagation()" title="Close Reader">
<app-reader-icon name="close" [size]="20" />
</button>
<div class="header-right">
<button class="icon-btn" (click)="onOpenSettings()" title="Settings">
<app-reader-icon name="settings" [size]="20" />
</button>
<button class="icon-btn close-btn" (click)="onClose(); $event.stopPropagation()" title="Close Reader">
<app-reader-icon name="close" [size]="20" />
</button>
</div>
</div>
@@ -25,6 +25,13 @@
transform: translateY(-100%);
}
.header-left,
.header-right {
display: flex;
align-items: center;
z-index: 1;
}
.icon-btn {
background: none;
border: none;
@@ -47,7 +54,7 @@
background: rgba(255, 255, 255, 0.12);
}
&:last-of-type {
&:last-child {
margin-right: 0;
}
@@ -85,7 +92,10 @@
}
.book-title {
flex: 1;
position: absolute;
left: 50%;
transform: translateX(-50%);
max-width: calc(100% - 240px);
text-align: center;
font-size: 14px;
font-weight: 500;
@@ -96,21 +106,25 @@
overflow: hidden;
text-overflow: ellipsis;
min-height: 1.2em;
padding: 0 16px;
}
}
@media (max-width: 600px) {
.cbx-header {
padding: 0 8px;
padding: 0 4px;
.icon-btn {
padding: 10px;
padding: 5px;
margin-right: 6px;
app-reader-icon {
transform: scale(0.9);
}
}
.book-title {
font-size: 13px;
padding: 0 8px;
font-size: 12px;
max-width: calc(100% - 160px);
}
}
}
@@ -2,7 +2,7 @@ import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {CbxHeaderService} from './cbx-header.service';
import {ReaderIconComponent} from '../../../ebook-reader/shared/icon.component';
import {ReaderIconComponent} from '../../../ebook-reader';
import {CommonModule} from '@angular/common';
@Component({
@@ -0,0 +1,57 @@
import {Injectable, inject} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../../../core/config/api-config';
import {AuthService} from '../../../../shared/service/auth.service';
export interface EpubSpineItem {
idref: string;
href: string;
mediaType: string;
linear: boolean;
}
export interface EpubManifestItem {
id: string;
href: string;
mediaType: string;
properties?: string[];
size: number;
}
export interface EpubTocItem {
label: string;
href: string;
children?: EpubTocItem[];
}
export interface EpubBookInfo {
containerPath: string;
rootPath: string;
spine: EpubSpineItem[];
manifest: EpubManifestItem[];
toc: EpubTocItem;
metadata: Record<string, any>;
coverPath?: string;
}
@Injectable({
providedIn: 'root'
})
export class EpubStreamingService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/epub`;
private http = inject(HttpClient);
private authService = inject(AuthService);
getBookInfo(bookId: number): Observable<EpubBookInfo> {
return this.http.get<EpubBookInfo>(`${this.baseUrl}/${bookId}/info`);
}
getBaseUrl(): string {
return this.baseUrl;
}
getAuthToken(): string | null {
return this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
}
}
@@ -4,6 +4,7 @@ import {catchError, map, switchMap} from 'rxjs/operators';
import {ReaderAnnotationService, Annotation} from '../features/annotations/annotation-renderer.service';
import {ReaderEventService, ViewEvent, TextSelection} from './event.service';
import {PageInfo, ThemeInfo, PageDecorator} from '../shared/header-footer.util';
import {EpubStreamingService, EpubBookInfo} from './epub-streaming.service';
export type {ViewEvent, TextSelection} from './event.service';
export type {PageInfo, ThemeInfo} from '../shared/header-footer.util';
@@ -32,6 +33,7 @@ export interface BookMetadata {
export class ReaderViewManagerService {
private annotationService = inject(ReaderAnnotationService);
private eventService = inject(ReaderEventService);
private epubStreamingService = inject(EpubStreamingService);
private view: any;
public get events$(): Observable<ViewEvent> {
@@ -77,6 +79,29 @@ export class ReaderViewManagerService {
);
}
loadEpubStreaming(bookId: number): Observable<void> {
if (!this.view) {
return throwError(() => new Error('View not created'));
}
return this.epubStreamingService.getBookInfo(bookId).pipe(
switchMap(bookInfo => from(this.openStreamingBook(bookId, bookInfo))),
map(() => undefined),
catchError(err => throwError(() => err))
);
}
private async openStreamingBook(bookId: number, bookInfo: EpubBookInfo): Promise<void> {
const makeStreamingBook = (window as any).makeStreamingBook;
if (!makeStreamingBook) {
throw new Error('makeStreamingBook not available - Foliate script may not be loaded');
}
const baseUrl = this.epubStreamingService.getBaseUrl();
const authToken = this.epubStreamingService.getAuthToken();
const book = await makeStreamingBook(bookId, baseUrl, bookInfo, authToken);
await this.view.open(book);
}
destroy(): void {
this.eventService.destroy();
this.view?.remove();
@@ -2,6 +2,13 @@
class="reader"
[style.background-color]="stateService.currentState.theme.bg ?? ''">
<div class="header-trigger-zone"
[class.inactive]="headerVisible"
(mouseenter)="onHeaderTriggerZoneEnter()"></div>
<div class="footer-trigger-zone"
[class.inactive]="forceNavbarVisible"
(mouseenter)="onFooterTriggerZoneEnter()"></div>
@if (isLoading) {
<div class="loader-overlay">
<div class="loader-content">
@@ -11,6 +11,34 @@
flex-direction: column;
}
.header-trigger-zone {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 20px;
z-index: 9998;
pointer-events: auto;
&.inactive {
pointer-events: none;
}
}
.footer-trigger-zone {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 30px;
z-index: 9998;
pointer-events: auto;
&.inactive {
pointer-events: none;
}
}
.reader-content {
position: relative;
flex: 1;
@@ -96,6 +96,7 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
showMetadata = false;
isCurrentCfiBookmarked = false;
forceNavbarVisible = false;
headerVisible = false;
book: Book | null = null;
sectionFractions: number[] = [];
@@ -115,6 +116,7 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
ngOnInit() {
this.visibilityManager = new ReaderHeaderFooterVisibilityManager(window.innerHeight);
this.visibilityManager.onStateChange((state) => {
this.headerVisible = state.headerVisible;
this.headerService.setForceVisible(state.headerVisible);
this.forceNavbarVisible = state.footerVisible;
});
@@ -209,19 +211,22 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
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)
book: this.bookService.getBookByIdFromAPI(this.bookId, false)
})),
switchMap(({book, fileBlob}) => {
switchMap(({book}) => {
this.book = book;
const fileUrl = URL.createObjectURL(fileBlob);
this._fileUrl = fileUrl;
this.progressService.initialize(this.bookId, book.bookType!);
this.selectionService.initialize(this.bookId, this.destroy$);
this.headerService.initialize(this.bookId, book.metadata?.title || '', this.destroy$);
return this.viewManager.loadEpub(fileUrl).pipe(
// Use streaming for EPUB if query param is set, blob loading otherwise (default)
const useStreaming = this.route.snapshot.queryParamMap.get('streaming') === 'true';
const loadBook$ = book.bookType === 'EPUB' && useStreaming
? this.viewManager.loadEpubStreaming(this.bookId)
: this.loadBookBlob();
return loadBook$.pipe(
tap(() => {
this.applyStyles();
this.sidebarService.initialize(this.bookId, book, this.destroy$);
@@ -241,6 +246,16 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
);
}
private loadBookBlob(): Observable<void> {
return this.bookService.getFileContent(this.bookId).pipe(
switchMap(fileBlob => {
const fileUrl = URL.createObjectURL(fileBlob);
this._fileUrl = fileUrl;
return this.viewManager.loadEpub(fileUrl);
})
);
}
private subscribeToStateChanges(): void {
this.stateService.state$
.pipe(takeUntil(this.destroy$))
@@ -291,6 +306,7 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
this.isCurrentCfiBookmarked = currentCfi
? bookmarks.some(b => b.cfi === currentCfi)
: false;
this.headerService.setCurrentCfiBookmarked(this.isCurrentCfiBookmarked);
});
}
@@ -329,6 +345,14 @@ export class EbookReaderComponent implements OnInit, OnDestroy {
this.visibilityManager.updateWindowHeight(window.innerHeight);
}
onHeaderTriggerZoneEnter(): void {
this.visibilityManager.handleHeaderZoneEnter();
}
onFooterTriggerZoneEnter(): void {
this.visibilityManager.handleFooterZoneEnter();
}
handleSelectionAction(action: TextSelectionAction): void {
if (action.type === 'note') {
this.noteService.openNewNoteDialog();
@@ -2,13 +2,16 @@
<button class="icon-btn" (click)="onShowChapters()" title="Chapters">
<app-reader-icon name="menu" [size]="20"></app-reader-icon>
</button>
<button class="icon-btn" (click)="onCreateBookmark()" title="Create Bookmark">
<button class="icon-btn" (click)="onCreateBookmark()" [title]="isCurrentCfiBookmarked ? 'Remove Bookmark' : 'Add Bookmark'" [class.active]="isCurrentCfiBookmarked">
<app-reader-icon name="bookmark"></app-reader-icon>
</button>
<span class="chapter-title">{{ bookTitle }}</span>
<button class="icon-btn" (click)="onOpenSearch()" title="Search">
<app-reader-icon name="search"></app-reader-icon>
</button>
<span class="chapter-title">{{ bookTitle }}</span>
<button class="icon-btn" (click)="onOpenNotes()" title="Notes">
<app-reader-icon name="note"></app-reader-icon>
</button>
<button class="icon-btn" (click)="onShowControls()" title="Settings">
<app-reader-icon name="settings"></app-reader-icon>
</button>
@@ -29,23 +29,28 @@
border: none;
color: inherit;
cursor: pointer;
padding: 6px;
border-radius: 50%;
transition: background 0.15s, box-shadow 0.15s;
padding: 8px;
border-radius: 4px;
transition: color 0.15s, opacity 0.15s;
display: flex;
align-items: center;
justify-content: center;
margin-right: 8px;
margin-right: 4px;
opacity: 0.85;
&:hover {
background: rgba(255, 255, 255, 0.14);
box-shadow: 0 2px 8px 0 rgba(0,0,0,0.10);
opacity: 1;
}
&:last-of-type {
margin-right: 0;
}
&.active {
color: #ef4444;
opacity: 1;
}
.pi {
font-size: 16px;
}
@@ -68,10 +73,11 @@
@media (max-width: 600px) {
.reader-header {
padding: 0 6px;
padding: 0 2px;
.icon-btn {
padding: 10px;
margin-right: 2px;
}
}
}
@@ -3,6 +3,7 @@ import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {ReaderHeaderService} from './header.service';
import {ReaderIconComponent} from '../../shared/icon.component';
import {Router} from '@angular/router';
@Component({
selector: 'app-reader-header',
@@ -13,9 +14,11 @@ import {ReaderIconComponent} from '../../shared/icon.component';
})
export class ReaderHeaderComponent implements OnInit, OnDestroy {
private headerService = inject(ReaderHeaderService);
private router = inject(Router);
private destroy$ = new Subject<void>();
isVisible = false;
isCurrentCfiBookmarked = false;
get bookTitle(): string {
return this.headerService.title;
@@ -29,6 +32,10 @@ export class ReaderHeaderComponent implements OnInit, OnDestroy {
this.headerService.forceVisible$
.pipe(takeUntil(this.destroy$))
.subscribe(visible => this.isVisible = visible);
this.headerService.isCurrentCfiBookmarked$
.pipe(takeUntil(this.destroy$))
.subscribe(bookmarked => this.isCurrentCfiBookmarked = bookmarked);
}
ngOnDestroy(): void {
@@ -40,6 +47,10 @@ export class ReaderHeaderComponent implements OnInit, OnDestroy {
this.headerService.openSidebar();
}
onOpenNotes(): void {
this.headerService.openLeftSidebar('notes');
}
onOpenSearch(): void {
this.headerService.openLeftSidebar('search');
}
@@ -53,6 +64,10 @@ export class ReaderHeaderComponent implements OnInit, OnDestroy {
}
onClose(): void {
this.headerService.close();
if (window.history.length <= 2) {
this.router.navigate(['/dashboard']);
} else {
this.headerService.close();
}
}
}
@@ -23,6 +23,9 @@ export class ReaderHeaderService {
private _forceVisible = new BehaviorSubject<boolean>(false);
forceVisible$ = this._forceVisible.asObservable();
private _isCurrentCfiBookmarked = new BehaviorSubject<boolean>(false);
isCurrentCfiBookmarked$ = this._isCurrentCfiBookmarked.asObservable();
private _showControls = new Subject<void>();
private _showMetadata = new Subject<void>();
showControls$ = this._showControls.asObservable();
@@ -50,6 +53,10 @@ export class ReaderHeaderService {
this._forceVisible.next(visible);
}
setCurrentCfiBookmarked(bookmarked: boolean): void {
this._isCurrentCfiBookmarked.next(bookmarked);
}
openSidebar(): void {
this.sidebarService.open();
}
@@ -59,7 +66,7 @@ export class ReaderHeaderService {
}
createBookmark(): void {
this.sidebarService.createBookmark();
this.sidebarService.toggleBookmark();
}
openControls(): void {
@@ -84,26 +91,6 @@ export class ReaderHeaderService {
this.syncSettingsToBackend();
}
decreaseFontSize(): void {
this.stateService.updateFontSize(-1);
this.syncSettingsToBackend();
}
increaseLineHeight(): void {
this.stateService.updateLineHeight(0.1);
this.syncSettingsToBackend();
}
decreaseLineHeight(): void {
this.stateService.updateLineHeight(-0.1);
this.syncSettingsToBackend();
}
setFlow(flow: 'paginated' | 'scrolled'): void {
this.stateService.setFlow(flow);
this.syncSettingsToBackend();
}
private syncSettingsToBackend(): void {
const state = this.stateService.currentState;
const setting: EbookViewerSetting = {
@@ -129,6 +116,7 @@ export class ReaderHeaderService {
reset(): void {
this._forceVisible.next(false);
this._isCurrentCfiBookmarked.next(false);
this.bookTitle = '';
}
}
@@ -234,6 +234,18 @@ export class ReaderSidebarService {
});
}
toggleBookmark(): void {
const currentCfi = this.progressService.currentCfi;
if (!currentCfi) return;
const existingBookmark = this._bookmarks.value.find(b => b.cfi === currentCfi);
if (existingBookmark) {
this.deleteBookmark(existingBookmark.id!);
} else {
this.createBookmark();
}
}
deleteBookmark(bookmarkId: number): void {
this.bookMarkHttpService.deleteBookmark(bookmarkId)
.pipe(takeUntil(this.destroy$))
@@ -41,6 +41,20 @@ export class ReaderHeaderFooterVisibilityManager {
}
}
handleHeaderZoneEnter(): void {
if (!this.isPinned) {
this.setHeaderVisible(true);
this.notifyStateChange();
}
}
handleFooterZoneEnter(): void {
if (!this.isPinned) {
this.setFooterVisible(true);
this.notifyStateChange();
}
}
togglePinned(): void {
this.isPinned = !this.isPinned;
this.updateVisibility();
+109 -7
View File
@@ -706,15 +706,35 @@ class Loader {
#cache = new Map()
#children = new Map()
#refCount = new Map()
#getDirectUrl = null // Function to get direct streaming URLs for lazy loading
eventTarget = new EventTarget()
constructor({ loadText, loadBlob, resources }) {
constructor({ loadText, loadBlob, resources, getDirectUrl }) {
this.loadText = loadText
this.loadBlob = loadBlob
this.manifest = resources.manifest
this.assets = resources.manifest
this.#getDirectUrl = getDirectUrl ?? null
// needed only when replacing in (X)HTML w/o parsing (see below)
//.filter(({ mediaType }) => ![MIME.XHTML, MIME.HTML].includes(mediaType))
}
// Check if a media type is an image
#isImage(mediaType) {
return mediaType?.startsWith('image/') ?? false
}
// Check if a media type is a font
#isFont(mediaType) {
return mediaType?.includes('font') ||
mediaType === 'application/vnd.ms-opentype' ||
mediaType === 'application/x-font-ttf' ||
mediaType === 'application/x-font-otf' ||
mediaType === 'application/x-font-woff' ||
mediaType === 'font/otf' ||
mediaType === 'font/ttf' ||
mediaType === 'font/woff' ||
mediaType === 'font/woff2'
}
async createURL(href, data, type, parent) {
if (!data) return ''
const detail = { data, type }
@@ -838,13 +858,59 @@ class Loader {
// replace hrefs (excluding anchors)
const replace = async (el, attr) => el.setAttribute(attr,
await this.loadHref(el.getAttribute(attr), href, parents))
// Helper to check if element is an image that should use direct URL
const shouldUseDirectUrl = (el, attr) => {
if (!this.#getDirectUrl) return false
const srcAttr = el.getAttribute(attr)
if (!srcAttr || isExternal(srcAttr)) return false
const path = resolveURL(srcAttr, href)
const item = this.manifest.find(item => item.href === path)
return item && this.#isImage(item.mediaType)
}
// Replace with direct URL (for images) - browser loads on-demand
const replaceWithDirectUrl = (el, attr) => {
const srcAttr = el.getAttribute(attr)
const path = resolveURL(srcAttr, href)
const directUrl = this.#getDirectUrl(path)
if (directUrl) {
el.setAttribute(attr, directUrl)
el.setAttribute('loading', 'lazy') // Native lazy loading hint
return true
}
return false
}
// Process link elements (stylesheets, etc.)
for (const el of doc.querySelectorAll('link[href]')) await replace(el, 'href')
for (const el of doc.querySelectorAll('[src]')) await replace(el, 'src')
for (const el of doc.querySelectorAll('[poster]')) await replace(el, 'poster')
// Process elements with src attribute
// For images: use direct URLs so browser can load on-demand
// For others: load and create blob URL
for (const el of doc.querySelectorAll('[src]')) {
if (shouldUseDirectUrl(el, 'src')) {
replaceWithDirectUrl(el, 'src')
} else {
await replace(el, 'src')
}
}
// Process poster attributes (videos)
for (const el of doc.querySelectorAll('[poster]')) {
if (shouldUseDirectUrl(el, 'poster')) {
replaceWithDirectUrl(el, 'poster')
} else {
await replace(el, 'poster')
}
}
for (const el of doc.querySelectorAll('object[data]')) await replace(el, 'data')
for (const el of doc.querySelectorAll('[*|href]:not([href])'))
el.setAttributeNS(NS.XLINK, 'href', await this.loadHref(
el.getAttributeNS(NS.XLINK, 'href'), href, parents))
// Process srcset attributes
for (const el of doc.querySelectorAll('[srcset]'))
el.setAttribute('srcset', await replaceSeries(el.getAttribute('srcset'),
/(\s*)(.+?)\s*((?:\s[\d.]+[wx])+\s*(?:,|$)|,\s+|$)/g,
@@ -868,15 +934,48 @@ class Loader {
return this.createURL(href, result, mediaType, parent)
}
async replaceCSS(str, href, parents = []) {
// For url() references, use direct URLs for fonts and images (lazy loading)
// This avoids fetching all fonts/images upfront - browser fetches on-demand
const replacedUrls = await replaceSeries(str,
/url\(\s*["']?([^'"\n]*?)\s*["']?\s*\)/gi,
(_, url) => this.loadHref(url, href, parents)
.then(url => `url("${url}")`))
async (_, url) => {
if (isExternal(url)) return `url("${url}")`
const path = resolveURL(url, href)
const item = this.manifest.find(item => item.href === path)
// If we have getDirectUrl and this is a font or image, use direct URL
// This lets the browser fetch on-demand instead of us prefetching everything
if (this.#getDirectUrl && item && (this.#isFont(item.mediaType) || this.#isImage(item.mediaType))) {
const directUrl = this.#getDirectUrl(path)
if (directUrl) return `url("${directUrl}")`
}
// For other resources (like CSS), load them normally
const loadedUrl = await this.loadHref(url, href, parents)
return `url("${loadedUrl}")`
})
// apart from `url()`, strings can be used for `@import` (but why?!)
return replaceSeries(replacedUrls,
// CSS imports need to be loaded and processed
const replacedImports = await replaceSeries(replacedUrls,
/@import\s*["']([^"'\n]*?)["']/gi,
(_, url) => this.loadHref(url, href, parents)
.then(url => `@import "${url}"`))
// Add font-display: swap to @font-face rules that don't have it
// This ensures text is visible immediately while fonts load
return replacedImports.replace(
/@font-face\s*\{([^}]*)\}/gi,
(match, content) => {
// Check if font-display is already set
if (/font-display\s*:/i.test(content)) {
return match
}
// Add font-display: swap before the closing brace
return `@font-face {${content}font-display: swap;}`
}
)
}
// find & replace all possible relative paths for all assets without parsing
replaceString(str, href, parents = []) {
@@ -932,10 +1031,12 @@ export class EPUB {
parser = new DOMParser()
#loader
#encryption
constructor({ loadText, loadBlob, getSize, sha1 }) {
#getDirectUrl = null
constructor({ loadText, loadBlob, getSize, getDirectUrl, sha1 }) {
this.loadText = loadText
this.loadBlob = loadBlob
this.getSize = getSize
this.#getDirectUrl = getDirectUrl ?? null
this.#encryption = new Encryption(deobfuscators(sha1))
}
async #loadXML(uri) {
@@ -973,6 +1074,7 @@ ${doc.querySelector('parsererror').innerText}`)
loadBlob: uri => Promise.resolve(this.loadBlob(uri))
.then(this.#encryption.getDecoder(uri)),
resources: this.resources,
getDirectUrl: this.#getDirectUrl,
})
this.transformTarget = this.#loader.eventTarget
this.sections = this.resources.spine.map((spineItem, index) => {
@@ -0,0 +1,121 @@
/**
* Creates a streaming loader that fetches EPUB files from the server on-demand
* instead of loading the entire ZIP file into memory.
*
* @param {number} bookId - The book ID for API requests
* @param {string} baseUrl - API base URL (e.g., '/api/v1/epub')
* @param {Object} bookInfo - Pre-fetched EPUB metadata from /info endpoint
* @param {string} [authToken] - Optional authentication token
* @returns {Object} Loader interface compatible with Foliate's EPUB class
*/
export const makeStreamingLoader = (bookId, baseUrl, bookInfo, authToken = null) => {
// Build a map of file paths to their manifest info for quick lookup
const manifestMap = new Map(
bookInfo.manifest.map(item => [item.href, item])
)
// Build URL for fetching a file
const getFileUrl = (name) => {
if (!name) return null
// URL encode the path but preserve slashes
const encodedPath = name.split('/').map(encodeURIComponent).join('/')
return `${baseUrl}/${bookId}/file/${encodedPath}`
}
// Build fetch options with auth header
const getFetchOptions = () => {
if (!authToken) return {}
return {
headers: {
'Authorization': `Bearer ${authToken}`
}
}
}
// Build URL with token for browser-initiated requests (fonts, images in CSS)
const getDirectFileUrl = (name) => {
if (!name) return null
const encodedPath = name.split('/').map(encodeURIComponent).join('/')
let url = `${baseUrl}/${bookId}/file/${encodedPath}`
if (authToken) {
url += `?token=${encodeURIComponent(authToken)}`
}
return url
}
/**
* Load file as text
*/
const loadText = async (name) => {
if (!name) return null
try {
const url = getFileUrl(name)
const response = await fetch(url, getFetchOptions())
if (!response.ok) {
console.warn(`Failed to load text: ${name}`, response.status)
return null
}
return await response.text()
} catch (e) {
console.error(`Error loading text ${name}:`, e)
return null
}
}
/**
* Load file as Blob with optional MIME type
*/
const loadBlob = async (name, type) => {
if (!name) return null
try {
const url = getFileUrl(name)
const response = await fetch(url, getFetchOptions())
if (!response.ok) {
console.warn(`Failed to load blob: ${name}`, response.status)
return null
}
const blob = await response.blob()
// Return with specified type or detected type
if (type) {
return new Blob([blob], {type})
}
return blob
} catch (e) {
console.error(`Error loading blob ${name}:`, e)
return null
}
}
/**
* Get uncompressed size of a file
*/
const getSize = (name) => {
if (!name) return 0
const item = manifestMap.get(name)
return item?.size ?? 0
}
/**
* Get direct URL for a file without fetching it.
* This allows the browser to fetch resources on-demand (fonts, images).
* Note: Uses token in URL since browser-initiated requests can't use headers.
* @param {string} name - File path within the EPUB
* @returns {string|null} Direct URL to the file
*/
const getDirectUrl = (name) => {
if (!name) return null
return getDirectFileUrl(name)
}
return {
loadText,
loadBlob,
getSize,
getDirectUrl, // For lazy loading of fonts/images in CSS
// Expose for debugging
_bookInfo: bookInfo,
_manifestMap: manifestMap
}
}
export default makeStreamingLoader
+20
View File
@@ -2,6 +2,7 @@ import * as CFI from './epubcfi.js'
import {SectionProgress, TOCProgress} from './progress.js'
import {Overlayer} from './overlayer.js'
import {textWalker} from './text-walker.js'
import {makeStreamingLoader} from './streaming-loader.js'
const SEARCH_PREFIX = 'foliate-search:'
@@ -139,6 +140,22 @@ export const makeBook = async file => {
return book
}
/**
* Create an EPUB book using streaming loader instead of ZIP extraction.
* This avoids loading the entire EPUB into memory.
*
* @param {number} bookId - Book ID for API requests
* @param {string} baseUrl - API base URL for EPUB endpoints
* @param {Object} bookInfo - Pre-fetched metadata from /api/v1/epub/{bookId}/info
* @param {string} [authToken] - Optional authentication token
* @returns {Promise<EPUB>} Initialized EPUB book object
*/
export const makeStreamingBook = async (bookId, baseUrl, bookInfo, authToken = null) => {
const loader = makeStreamingLoader(bookId, baseUrl, bookInfo, authToken)
const {EPUB} = await import('./epub.js')
return new EPUB(loader).init()
}
class CursorAutohider {
#timeout
#el
@@ -653,3 +670,6 @@ export class View extends HTMLElement {
}
customElements.define('foliate-view', View)
// Export makeStreamingBook to window for use from Angular
window.makeStreamingBook = makeStreamingBook