Build a lazy-loading PDF viewer for large files

This commit is contained in:
aditya.chandel
2025-06-01 16:25:14 -06:00
committed by Aditya Chandel
parent 38487f8e5d
commit fce5ccf22c
29 changed files with 536 additions and 63 deletions
@@ -1,7 +1,13 @@
<div class="comic-reader-container">
<div class="navigation">
<div class="goto-page-controls" style="display: flex; align-items: center; margin-right: auto;">
<input type="number" [(ngModel)]="goToPageInput" [min]="1" [max]="pages.length" placeholder="Page">
<input
type="number"
[(ngModel)]="goToPageInput"
[min]="1"
[max]="pages.length"
placeholder="Page"
/>
<button
(click)="goToPageInput !== null && goToPage(goToPageInput)"
[disabled]="goToPageInput === null || goToPageInput < 1 || goToPageInput > pages.length">
@@ -13,7 +19,8 @@
<button class="mr-2" (click)="goToPage(1)" [disabled]="currentPage === 0">&lt;&lt;</button>
<button (click)="previousPage()" [disabled]="currentPage === 0">&lt;</button>
<span>
Page {{ currentPage + 1 }}{{ isTwoPageView && imageUrls.length > 1 ? '-' + (currentPage + 2) : '' }} of {{ pages.length }}
Page {{ currentPage + 1 }}
{{ isTwoPageView && imageUrls.length > 1 ? '-' + (currentPage + 2) : '' }} of {{ pages.length }}
</span>
<button (click)="nextPage()" [disabled]="currentPage >= pages.length - 1">&gt;</button>
<button class="ml-2" (click)="goToPage(pages.length)" [disabled]="currentPage >= pages.length - 1">&gt;&gt;</button>
@@ -32,15 +39,16 @@
<div class="image-container" [class.two-page-view]="isTwoPageView">
<ng-container *ngIf="!isLoading; else loading">
<ng-container *ngIf="pages.length > 0; else noPages">
<img *ngFor="let url of imageUrls" [src]="url" alt="Comic Page"/>
<img *ngFor="let url of imageUrls" [src]="url" alt="Page Image"/>
</ng-container>
</ng-container>
<ng-template #noPages>
<p>No pages available.</p>
</ng-template>
<ng-template #loading>
<div style="display: flex; justify-content: center; align-items: center; height: 100%;">
<div style="display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100%;">
<p-progressSpinner></p-progressSpinner>
<p style="margin-top: 1rem; color: #ccc;">Processing pages... This may take a few seconds on first load. Future loads will be significantly faster.</p>
</div>
</ng-template>
</div>
@@ -6,9 +6,10 @@ import {BookService} from '../../service/book.service';
import {UserService} from '../../../settings/user-management/user.service';
import {MessageService} from 'primeng/api';
import {forkJoin} from 'rxjs';
import {BookSetting, CbxPageSpread, CbxPageViewMode} from '../../model/book.model';
import {BookSetting, BookType, CbxPageSpread, CbxPageViewMode, PdfPageSpread, PdfPageViewMode} from '../../model/book.model';
import {ProgressSpinner} from 'primeng/progressspinner';
import {FormsModule} from "@angular/forms";
import {NewPdfReaderService} from '../../service/new-pdf-reader.service';
@Component({
selector: 'app-cbx-reader',
@@ -18,20 +19,24 @@ import {FormsModule} from "@angular/forms";
styleUrl: './cbx-reader.component.scss'
})
export class CbxReaderComponent implements OnInit {
bookType!: BookType;
goToPageInput: number | null = null;
bookId!: number;
pages: number[] = [];
currentPage = 0;
isLoading = true;
pageSpread: CbxPageSpread = CbxPageSpread.ODD;
pageViewMode: CbxPageViewMode = CbxPageViewMode.SINGLE_PAGE;
pageSpread: CbxPageSpread | PdfPageSpread = CbxPageSpread.ODD;
pageViewMode: CbxPageViewMode | PdfPageViewMode = CbxPageViewMode.SINGLE_PAGE;
private touchStartX = 0;
private touchEndX = 0;
private route = inject(ActivatedRoute);
private cbxReaderService = inject(CbxReaderService);
private pdfReaderService = inject(NewPdfReaderService);
private bookService = inject(BookService);
private userService = inject(UserService);
private messageService = inject(MessageService);
@@ -44,25 +49,54 @@ export class CbxReaderComponent implements OnInit {
forkJoin([
this.bookService.getBookByIdFromAPI(this.bookId, false),
this.bookService.getBookSetting(this.bookId),
this.userService.getMyself(),
this.cbxReaderService.getAvailablePages(this.bookId)
this.userService.getMyself()
]).subscribe({
next: ([cbxMeta, bookSettings, myself, pages]) => {
next: ([book, bookSettings, myself]) => {
const userSettings = myself.userSettings;
const global = userSettings.perBookSetting.cbx === 'Global';
this.bookType = book.bookType;
this.pageViewMode = global
? userSettings.cbxReaderSetting.pageViewMode || CbxPageViewMode.SINGLE_PAGE
: bookSettings.cbxSettings?.pageViewMode || userSettings.cbxReaderSetting.pageViewMode || CbxPageViewMode.SINGLE_PAGE;
const pagesObservable = this.bookType === 'PDF'
? this.pdfReaderService.getAvailablePages(this.bookId)
: this.cbxReaderService.getAvailablePages(this.bookId);
this.pageSpread = global
? userSettings.cbxReaderSetting.pageSpread || CbxPageSpread.ODD
: bookSettings.cbxSettings?.pageSpread || userSettings.cbxReaderSetting.pageSpread || CbxPageSpread.ODD;
pagesObservable.subscribe({
next: (pages) => {
this.pages = pages;
this.currentPage = (cbxMeta.cbxProgress?.page || 1) - 1;
this.alignCurrentPageToParity();
this.isLoading = false;
this.pages = pages;
if (this.bookType === 'CBX') {
const global = userSettings.perBookSetting.cbx === 'Global';
this.pageViewMode = global
? userSettings.cbxReaderSetting.pageViewMode || CbxPageViewMode.SINGLE_PAGE
: bookSettings.cbxSettings?.pageViewMode || userSettings.cbxReaderSetting.pageViewMode || CbxPageViewMode.SINGLE_PAGE;
this.pageSpread = global
? userSettings.cbxReaderSetting.pageSpread || CbxPageSpread.ODD
: bookSettings.cbxSettings?.pageSpread || userSettings.cbxReaderSetting.pageSpread || CbxPageSpread.ODD;
this.currentPage = (book.cbxProgress?.page || 1) - 1;
}
if (this.bookType === 'PDF') {
const global = userSettings.perBookSetting.pdf === 'Global';
this.pageViewMode = global
? userSettings.newPdfReaderSetting.pageViewMode || PdfPageViewMode.SINGLE_PAGE
: bookSettings.newPdfSettings?.pageViewMode || userSettings.newPdfReaderSetting.pageViewMode || PdfPageViewMode.SINGLE_PAGE;
this.pageSpread = global
? userSettings.newPdfReaderSetting.pageSpread || PdfPageSpread.ODD
: bookSettings.newPdfSettings?.pageSpread || userSettings.newPdfReaderSetting.pageSpread || PdfPageSpread.ODD;
this.currentPage = (book.pdfProgress?.page || 1) - 1;
}
this.alignCurrentPageToParity();
this.isLoading = false;
},
error: (err) => {
const errorMessage = err?.error?.message || 'Failed to load pages';
this.messageService.add({severity: 'error', summary: 'Error', detail: errorMessage});
this.isLoading = false;
}
});
},
error: (err) => {
const errorMessage = err?.error?.message || 'Failed to load the book';
@@ -74,18 +108,22 @@ export class CbxReaderComponent implements OnInit {
}
get isTwoPageView(): boolean {
return this.pageViewMode === CbxPageViewMode.TWO_PAGE;
return this.pageViewMode === CbxPageViewMode.TWO_PAGE || this.pageViewMode === PdfPageViewMode.TWO_PAGE;
}
toggleView() {
if (!this.isTwoPageView && this.isPhonePortrait()) return;
this.pageViewMode = this.isTwoPageView ? CbxPageViewMode.SINGLE_PAGE : CbxPageViewMode.TWO_PAGE;
this.pageViewMode = this.isTwoPageView ? (this.bookType === "CBX" ? CbxPageViewMode.SINGLE_PAGE : PdfPageViewMode.SINGLE_PAGE) : (this.bookType === "CBX" ? CbxPageViewMode.TWO_PAGE : PdfPageViewMode.TWO_PAGE);
this.alignCurrentPageToParity();
this.updateViewerSetting();
}
toggleSpreadDirection() {
this.pageSpread = this.pageSpread === CbxPageSpread.ODD ? CbxPageSpread.EVEN : CbxPageSpread.ODD;
if (this.pageSpread === CbxPageSpread.ODD || this.pageSpread === PdfPageSpread.ODD) {
this.pageSpread = this.bookType === "CBX" ? CbxPageSpread.EVEN : PdfPageSpread.EVEN;
} else {
this.pageSpread = this.bookType === "CBX" ? CbxPageSpread.ODD : PdfPageSpread.ODD;
}
this.alignCurrentPageToParity();
this.updateViewerSetting();
}
@@ -120,7 +158,7 @@ export class CbxReaderComponent implements OnInit {
private alignCurrentPageToParity() {
if (!this.pages.length || !this.isTwoPageView) return;
const desiredOdd = this.pageSpread === CbxPageSpread.ODD;
const desiredOdd = this.pageSpread === CbxPageSpread.ODD || this.pageSpread === PdfPageSpread.ODD;
for (let i = this.currentPage; i >= 0; i--) {
if ((this.pages[i] % 2 === 1) === desiredOdd) {
this.currentPage = i;
@@ -166,7 +204,7 @@ export class CbxReaderComponent implements OnInit {
private enforcePortraitSinglePageView() {
if (this.isPhonePortrait() && this.isTwoPageView) {
this.pageViewMode = CbxPageViewMode.SINGLE_PAGE;
this.pageViewMode = this.bookType === "CBX" ? CbxPageViewMode.SINGLE_PAGE : PdfPageViewMode.SINGLE_PAGE;
this.updateViewerSetting();
}
}
@@ -175,24 +213,37 @@ export class CbxReaderComponent implements OnInit {
return window.innerWidth < 768 && window.innerHeight > window.innerWidth;
}
private getPageImageUrl(pageIndex: number): string {
return this.bookType === 'PDF'
? this.pdfReaderService.getPageImageUrl(this.bookId, this.pages[pageIndex])
: this.cbxReaderService.getPageImageUrl(this.bookId, this.pages[pageIndex]);
}
get imageUrls(): string[] {
if (!this.pages.length) return [];
const urls = [this.cbxReaderService.getPageImageUrl(this.bookId, this.pages[this.currentPage])];
const urls = [this.getPageImageUrl(this.currentPage)];
if (this.isTwoPageView && this.currentPage + 1 < this.pages.length) {
urls.push(this.cbxReaderService.getPageImageUrl(this.bookId, this.pages[this.currentPage + 1]));
urls.push(this.getPageImageUrl(this.currentPage + 1));
}
return urls;
}
private updateViewerSetting(): void {
const bookSetting: BookSetting = {
cbxSettings: {
pageSpread: this.pageSpread,
pageViewMode: this.pageViewMode,
}
}
const bookSetting: BookSetting = this.bookType === "CBX"
? {
cbxSettings: {
pageSpread: this.pageSpread as CbxPageSpread,
pageViewMode: this.pageViewMode as CbxPageViewMode,
}
}
: {
newPdfSettings: {
pageSpread: this.pageSpread as PdfPageSpread,
pageViewMode: this.pageViewMode as PdfPageViewMode,
}
};
this.bookService.updateViewerSetting(bookSetting, this.bookId).subscribe();
}
@@ -201,7 +252,12 @@ export class CbxReaderComponent implements OnInit {
? Math.round(((this.currentPage + 1) / this.pages.length) * 1000) / 10
: 0;
this.bookService.saveCbxProgress(this.bookId, this.currentPage + 1, percentage).subscribe();
if(this.bookType === 'CBX') {
this.bookService.saveCbxProgress(this.bookId, this.currentPage + 1, percentage).subscribe();
}
if(this.bookType === 'PDF') {
this.bookService.savePdfProgress(this.bookId, this.currentPage + 1, percentage).subscribe();
}
}
goToPage(page: number): void {
if (page < 1 || page > this.pages.length) return;
@@ -129,7 +129,7 @@
</div>
<div *ngIf="userService.userState$ | async as userData" class="pl-6 pt-4 flex flex-row w-full gap-4">
<p-button label="Read" icon="pi pi-book" severity="info" (onClick)="read(metadata.bookId)"></p-button>
<p-splitbutton label="Read" icon="pi pi-book" [model]="readMenuItems" (onClick)="read(metadata.bookId, 'ngx')" severity="info"/>
<p-button label="Assign Shelf" icon="pi pi-folder" severity="info" outlined (onClick)="assignShelf(metadata.bookId)"></p-button>
<p-button *ngIf="userData.permissions.canDownload || userData.permissions.admin" label="Download" icon="pi pi-download" severity="info" outlined
(onClick)="download(metadata.bookId)"></p-button>
@@ -54,6 +54,7 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
metadata$: Observable<BookMetadata | null> = this.metadataCenterService.currentMetadata$;
emailMenuItems: MenuItem[] | undefined;
readMenuItems: MenuItem[] | undefined;
refreshMenuItems: MenuItem[] | undefined;
bookInSeries: Book[] = [];
isExpanded = false;
@@ -102,6 +103,15 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
}
];
this.readMenuItems = [
{
label: 'Streaming Reader',
command: () => {
this.read(this.book?.id, "streaming")
},
}
];
this.metadata$
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((metadata) => {
@@ -144,8 +154,8 @@ export class MetadataViewerComponent implements OnInit, OnChanges {
this.isExpanded = !this.isExpanded;
}
read(bookId: number): void {
this.bookService.readBook(bookId);
read(bookId: number | undefined, reader: "ngx" | "streaming"): void {
this.bookService.readPdf(bookId!, reader);
}
getAuthorNames(authors: string[]): string {
@@ -1,4 +1,5 @@
import {Shelf} from './shelf.model';
import {NewPdfReaderSetting} from '../../settings/user-management/user.service';
export type BookType = "PDF" | "EPUB" | "CBX";
@@ -121,6 +122,7 @@ export interface BookSetting {
pdfSettings?: PdfViewerSetting;
epubSettings?: EpubViewerSetting;
cbxSettings?: CbxViewerSetting;
newPdfSettings?: NewPdfReaderSetting;
[key: string]: any;
}
@@ -139,3 +141,13 @@ export const enum CbxPageSpread {
EVEN = 'EVEN',
ODD = 'ODD',
}
export const enum PdfPageViewMode {
SINGLE_PAGE = 'SINGLE_PAGE',
TWO_PAGE = 'TWO_PAGE',
}
export const enum PdfPageSpread {
EVEN = 'EVEN',
ODD = 'ODD',
}
@@ -116,6 +116,25 @@ export class BookService {
this.bookStateSubject.next({...currentState, books: updatedBooks});
}
readPdf(bookId: number, reader: "ngx" | "streaming") {
const currentBooks = this.bookStateSubject.value.books;
const book = currentBooks?.find(book => book.id === bookId);
if (book) {
if (book.bookType === "PDF") {
if (reader === "ngx") {
const url = `/pdf-viewer/book/${book.id}`;
window.open(url, '_blank');
} else {
const url = `/cbx-viewer/book/${book.id}`;
window.open(url, '_blank');
}
this.updateLastReadTime(book.id);
}
} else {
console.error('Book not found');
}
}
readBook(bookId: number): void {
const currentBooks = this.bookStateSubject.value.books;
const book = currentBooks?.find(book => book.id === bookId);
@@ -377,9 +396,9 @@ export class BookService {
const currentState = this.bookStateSubject.value;
const updatedBooks = (currentState.books || []).map(book => {
const updatedMetadata = updatedMetadataList.find(meta => meta.bookId === book.id);
return updatedMetadata ? { ...book, metadata: updatedMetadata } : book;
return updatedMetadata ? {...book, metadata: updatedMetadata} : book;
});
this.bookStateSubject.next({ ...currentState, books: updatedBooks });
this.bookStateSubject.next({...currentState, books: updatedBooks});
}),
map(() => void 0),
catchError((error) => {
@@ -0,0 +1,21 @@
import { Injectable } from '@angular/core';
import {API_CONFIG} from '../../config/api-config';
import {HttpClient} from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class NewPdfReaderService {
private readonly url = `${API_CONFIG.BASE_URL}/api/v1/pdf`;
constructor(private http: HttpClient) {}
getAvailablePages(bookId: number) {
return this.http.get<number[]>(`${this.url}/${bookId}/pages`);
}
getPageImageUrl(bookId: number, page: number): string {
return `${this.url}/${bookId}/pages/${page}`;
}
}
@@ -5,7 +5,7 @@ import {API_CONFIG} from '../../config/api-config';
import {RxStompService} from '../../shared/websocket/rx-stomp.service';
import {Library} from '../../book/model/library.model';
import {catchError} from 'rxjs/operators';
import {CbxPageSpread, CbxPageViewMode} from '../../book/model/book.model';
import {CbxPageSpread, CbxPageViewMode, PdfPageSpread, PdfPageViewMode} from '../../book/model/book.model';
export interface EntityViewPreferences {
global: EntityViewPreference;
@@ -60,11 +60,17 @@ export interface CbxReaderSetting {
pageViewMode: CbxPageViewMode;
}
export interface NewPdfReaderSetting {
pageSpread: PdfPageSpread;
pageViewMode: PdfPageViewMode;
}
export interface UserSettings {
perBookSetting: PerBookSetting;
pdfReaderSetting: PdfReaderSetting;
epubReaderSetting: EpubReaderSetting;
cbxReaderSetting: CbxReaderSetting;
newPdfReaderSetting: NewPdfReaderSetting;
sidebarLibrarySorting: SidebarLibrarySorting;
sidebarShelfSorting: SidebarShelfSorting;
entityViewPreferences: EntityViewPreferences;