feat(pdf-reader): PDF reader for vertical/infinite scroll layouts and improved responsiveness (#841)

This commit is contained in:
brios
2026-05-03 09:50:37 +02:00
committed by GitHub
parent 1c9902448f
commit 64945c0f99
15 changed files with 959 additions and 405 deletions
@@ -1,8 +1,9 @@
import { Component, ElementRef, inject, Injector, NgZone, OnDestroy, OnInit, afterNextRender, viewChild, DestroyRef, signal, computed } from '@angular/core';
import { ChangeDetectionStrategy, Component, ElementRef, inject, Injector, NgZone, OnDestroy, OnInit, afterNextRender, viewChild, DestroyRef, signal, computed } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ActivatedRoute, Router } from '@angular/router';
import { PageTitleService } from "../../../shared/service/page-title.service";
import { BookService } from '../../book/service/book.service';
import { forkJoin, from, Observable, of, Subject, Subscription } from "rxjs";
import { forkJoin, from, Observable, of, Subject } from "rxjs";
import { debounceTime, filter, map, switchMap, take } from 'rxjs/operators';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { BookSetting } from '../../book/model/book.model';
@@ -12,7 +13,7 @@ import { API_CONFIG } from '../../../core/config/api-config';
import { PdfAnnotationService } from '../../../shared/service/pdf-annotation.service';
import { ReaderIconComponent } from '../../readers/ebook-reader/shared/icon.component';
import { BookMark } from '../../../shared/service/book-mark.service';
import { EmbedPdfBookService, PdfOutlineItem } from './services/embedpdf-book.service';
import { EmbedPdfBookService, PdfOutlineItem, PdfScrollLayout } from './services/embedpdf-book.service';
import type { AnnotationTransferItem } from '@embedpdf/snippet';
import { PdfBookmarkService } from './services/pdf-bookmark.service';
import { PdfSidebarComponent, PdfAnnotationListItem } from './components/pdf-sidebar.component';
@@ -39,10 +40,11 @@ type EmbedPdfMessage =
@Component({
selector: 'app-pdf-reader',
standalone: true,
imports: [ProgressSpinner, TranslocoPipe, ReaderIconComponent, FormsModule, PdfSidebarComponent],
imports: [CommonModule, ProgressSpinner, TranslocoPipe, ReaderIconComponent, FormsModule, PdfSidebarComponent],
providers: [EmbedPdfBookService, PdfBookmarkService],
templateUrl: './pdf-reader.component.html',
styleUrl: './pdf-reader.component.scss',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class PdfReaderComponent implements OnInit, OnDestroy {
@@ -67,6 +69,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
readonly isZoomMenuOpen = signal(false);
readonly activeAnnotationTool = signal<string | null>(null);
readonly spreadMode = signal<'none' | 'odd' | 'even'>('none');
readonly scrollLayout = signal<PdfScrollLayout>('vertical');
readonly goToPageInput = signal<number | null>(null);
readonly outline = signal<PdfOutlineItem[]>([]);
readonly pdfBookmarks = signal<BookMark[]>([]);
@@ -122,6 +125,11 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
private pdfFetchAbortController?: AbortController;
private cachedPdfBuffer: ArrayBuffer | null = null;
private suppressProgressSave = false;
private initialPage = 1;
private pendingDocTargetPage: number | null = null;
private docProgressReleaseTimer?: ReturnType<typeof setTimeout>;
private closeReaderPromise: Promise<void> | null = null;
readonly isClosingReader = signal(false);
// Book mode state
private bookViewerInitialized = false;
@@ -157,11 +165,8 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
private dbAnnotationIds = new Set<string>();
private altBookType?: string;
private appSettingsSubscription!: Subscription;
private annotationSaveSubject = new Subject<void>();
private annotationCacheSubject = new Subject<void>();
private annotationSaveSubscription!: Subscription;
private annotationCacheSubscription!: Subscription;
private annotationsLoaded = false;
private isImportingAnnotations = false;
private lastAnnotationData: string | null = null;
@@ -318,8 +323,11 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
};
});
this.annotationSaveSubscription = this.annotationSaveSubject
.pipe(debounceTime(1500))
this.annotationSaveSubject
.pipe(
debounceTime(1500),
takeUntilDestroyed(this.destroyRef)
)
.subscribe(() => this.persistAnnotations());
// Debounced search
@@ -335,8 +343,11 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// Keep lastAnnotationData warm so persistAnnotationsSync() always has fresh data
this.annotationCacheSubscription = this.annotationCacheSubject
.pipe(debounceTime(500))
this.annotationCacheSubject
.pipe(
debounceTime(500),
takeUntilDestroyed(this.destroyRef)
)
.subscribe(() => this.cacheAnnotationData());
this.route.paramMap.pipe(
@@ -378,19 +389,26 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
const globalOrIndividual = myself.userSettings.perBookSetting.pdf;
let zoomVal: string;
let spreadVal: 'none' | 'even' | 'odd';
let scrollLayoutVal: PdfScrollLayout;
if (globalOrIndividual === 'Global') {
zoomVal = myself.userSettings.pdfReaderSetting.pageZoom || 'page-fit';
spreadVal = (myself.userSettings.pdfReaderSetting.pageSpread || 'none') === 'off' ? 'none' : (myself.userSettings.pdfReaderSetting.pageSpread as 'none' | 'even' | 'odd') || 'none';
scrollLayoutVal = myself.userSettings.pdfReaderSetting.scrollLayout || 'vertical';
} else {
zoomVal = pdfPrefs.pdfSettings?.zoom || myself.userSettings.pdfReaderSetting.pageZoom || 'page-fit';
const rawSpread = pdfPrefs.pdfSettings?.spread || myself.userSettings.pdfReaderSetting.pageSpread || 'none';
spreadVal = rawSpread === 'off' ? 'none' : rawSpread as 'none' | 'even' | 'odd';
scrollLayoutVal = pdfPrefs.pdfSettings?.scrollLayout
|| myself.userSettings.pdfReaderSetting.scrollLayout
|| 'vertical';
this.isDarkTheme.set(pdfPrefs.pdfSettings?.isDarkTheme ?? true);
}
this.spread = spreadVal;
this.spreadMode.set(spreadVal);
this.scrollLayout.set(scrollLayoutVal);
this.canPrint = myself.permissions.canDownload || myself.permissions.admin;
this.page.set(pdfMeta.pdfProgress?.page || 1);
this.initialPage = pdfMeta.pdfProgress?.page || 1;
this.page.set(this.initialPage);
this.zoom.set(this.normalizeZoom(zoomVal));
this.bookData = bookData;
this.isInitialScrollDone.set(false);
@@ -450,6 +468,8 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
return;
}
this.suppressProgressSave = true;
await this.embedPdfBook.init(
targetEl,
pdfUrl,
@@ -457,6 +477,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
this.t.getActiveLang()
);
this.bookViewerInitialized = true;
this.embedPdfBook.setScrollLayout(this.scrollLayout());
if (this.isPanActive()) {
this.embedPdfBook.setPanMode(true);
@@ -538,6 +559,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
this.embedPdfBook.setSpreadMode(this.spread);
this.spreadMode.set(this.spread);
}
this.embedPdfBook.setScrollLayout(this.scrollLayout());
});
// Use onLayoutReady for initial page scroll (fires when document layout is calculated)
@@ -545,7 +567,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
takeUntilDestroyed(this.destroyRef),
take(1)
).subscribe(() => {
const currentPage = this.page();
const currentPage = this.initialPage;
if (currentPage > 1) {
this.embedPdfBook.scrollToPage(currentPage, 'instant');
@@ -556,17 +578,24 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
filter(ev => ev.pageNumber >= currentPage - 1),
take(1)
).subscribe(() => {
this.ngZone.run(() => this.isInitialScrollDone.set(true));
this.ngZone.run(() => {
this.isInitialScrollDone.set(true);
this.releaseProgressPersistence();
});
});
// Fallback in case pageChange$ doesn't fire (e.g. single-page PDF)
setTimeout(() => {
if (!this.isInitialScrollDone()) {
scrollSub.unsubscribe();
this.ngZone.run(() => this.isInitialScrollDone.set(true));
this.ngZone.run(() => {
this.isInitialScrollDone.set(true);
this.releaseProgressPersistence();
});
}
}, 800);
} else {
this.isInitialScrollDone.set(true);
this.releaseProgressPersistence();
}
// Load outline, bookmarks, and annotations after layout is ready and settled
@@ -577,6 +606,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
} catch (err) {
console.error('[BookViewer] Init failed:', err);
this.suppressProgressSave = false;
this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
@@ -723,6 +753,9 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
if (this.bookViewerInitialized) {
this.embedPdfBook.setPanMode(active);
}
if (this.viewerMode() === 'document' && this.embedPdfIframe?.contentWindow) {
this.embedPdfIframe.contentWindow.postMessage({ type: 'setPanMode', enable: active }, location.origin);
}
}
@@ -768,6 +801,26 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
this.embedPdfBook.stopSearch();
}
performAction(id: string): void {
switch (id) {
case 'sidebar': this.toggleSidebar(); break;
case 'search': this.toggleSearch(); break;
case 'highlight': this.toggleAnnotationTool('highlight'); break;
case 'freeText': this.toggleAnnotationTool('freeText'); break;
case 'ink': this.toggleAnnotationTool('ink'); break;
case 'pan': this.togglePanMode(); break;
case 'bookmark': this.toggleBookmark(); break;
case 'zoomOut': this.embedPdfBook.zoomOut(); break;
case 'zoomIn': this.embedPdfBook.zoomIn(); break;
case 'spreadMode': this.cycleSpreadMode(); break;
case 'scrollLayout': this.cycleScrollLayout(); break;
case 'rotate': this.rotateClockwise(); break;
case 'theme': this.toggleDarkTheme(); break;
case 'fullscreen': this.toggleFullscreen(); break;
case 'overflow': this.toggleToolbarOverflow(); break;
}
}
onSearchQueryChange(value: string): void {
this.searchQuery.set(value);
this.searchQuery$.next(value);
@@ -806,6 +859,17 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
this.updateViewerSetting();
}
cycleScrollLayout(): void {
const nextLayout: PdfScrollLayout = this.scrollLayout() === 'vertical' ? 'horizontal' : 'vertical';
this.scrollLayout.set(nextLayout);
if (this.viewerMode() === 'book') {
this.embedPdfBook.setScrollLayout(nextLayout);
} else if (this.embedPdfIframe?.contentWindow) {
this.embedPdfIframe.contentWindow.postMessage({ type: 'setScrollLayout', layout: nextLayout }, location.origin);
}
this.updateViewerSetting();
}
// --- Rotate ---
rotateClockwise(): void {
@@ -863,13 +927,18 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
async setViewerMode(mode: 'book' | 'document') {
if (mode === this.viewerMode()) return;
this.persistProgress(true);
this.docViewerReady.set(false);
if (this.initTimeout) {
clearTimeout(this.initTimeout);
this.initTimeout = undefined;
}
this.clearDocProgressReleaseTimer();
if (mode === 'document') {
this.initialPage = this.page();
this.pendingDocTargetPage = this.initialPage > 1 ? this.initialPage : null;
this.suppressProgressSave = true;
// Ensure annotations are captured before destroying the book viewer
await this.persistAnnotations();
@@ -880,6 +949,8 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
this.initDocViewerIframe();
}, 100);
} else {
this.initialPage = this.page();
this.pendingDocTargetPage = null;
// Switching from doc to book — save in background, don't block the switch
if (this.embedPdfIframe) {
this.saveEmbedPdfDocument().finally(() => this.destroyDocViewerIframe());
@@ -981,14 +1052,17 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
}
break;
case 'documentOpened':
// Scroll to the page the user was on in book mode and re-enable progress saving
if (this.embedPdfIframe?.contentWindow && this.page() > 1) {
// Scroll to the page the user was on in book mode and release progress saving when navigation settles
if (typeof msg.pageCount === 'number' && msg.pageCount > 0) {
this.totalPages.set(msg.pageCount);
}
if (this.embedPdfIframe?.contentWindow && this.initialPage > 1) {
this.embedPdfIframe.contentWindow.postMessage(
{ type: 'scrollToPage', pageNumber: this.page() },
{ type: 'scrollToPage', pageNumber: this.initialPage },
location.origin
);
}
setTimeout(() => { this.suppressProgressSave = false; }, 500);
this.startDocProgressReleaseFallback();
break;
case 'documentError':
console.error('[EmbedPDF] Document error:', msg.error);
@@ -1003,6 +1077,13 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
this.embedPdfSaveResolve = undefined;
break;
case 'pageChange':
if (this.viewerMode() === 'document' && this.suppressProgressSave) {
const shouldRelease = this.pendingDocTargetPage == null || msg.pageNumber >= this.pendingDocTargetPage - 1;
if (shouldRelease) {
this.pendingDocTargetPage = null;
this.releaseProgressPersistence();
}
}
this.onPageChange(msg.pageNumber);
this.totalPages.set(msg.totalPages);
break;
@@ -1081,7 +1162,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// --- Common viewer methods ---
onPageChange(page: number | undefined): void {
if (page == null || page === this.page()) {
if (page == null || page === this.page() || !this.isInitialScrollDone()) {
return;
}
this.page.set(page);
@@ -1111,6 +1192,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
pdfSettings: {
spread: this.spread,
zoom: this.zoom(),
scrollLayout: this.scrollLayout(),
isDarkTheme: this.isDarkTheme(),
}
}
@@ -1118,15 +1200,42 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
}
updateProgress(): void {
if (this.suppressProgressSave) return;
this.persistProgress();
}
private persistProgress(force = false): void {
if (this.suppressProgressSave && !force) return;
const currentPage = this.page();
const total = this.totalPages();
const percentage = total > 0 ? Math.round((currentPage / total) * 1000) / 10 : 0;
this.bookService.savePdfProgress(this.bookId, currentPage, percentage, this.bookFileId).subscribe();
}
private releaseProgressPersistence(): void {
this.clearDocProgressReleaseTimer();
this.suppressProgressSave = false;
this.persistProgress(true);
}
private startDocProgressReleaseFallback(): void {
this.clearDocProgressReleaseTimer();
this.docProgressReleaseTimer = setTimeout(() => {
if (this.viewerMode() !== 'document') return;
if (this.suppressProgressSave) {
this.releaseProgressPersistence();
}
}, 1500);
}
private clearDocProgressReleaseTimer(): void {
if (!this.docProgressReleaseTimer) return;
clearTimeout(this.docProgressReleaseTimer);
this.docProgressReleaseTimer = undefined;
}
ngOnDestroy(): void {
if (this.initTimeout) clearTimeout(this.initTimeout);
this.clearDocProgressReleaseTimer();
if (this.pdfFetchAbortController) this.pdfFetchAbortController.abort();
this.wakeLockService.disable();
if (this.chromeAutoHideTimer) clearTimeout(this.chromeAutoHideTimer);
@@ -1141,16 +1250,11 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
this.readingSessionService.endSession(currentPage.toString(), percentage);
}
this.annotationSaveSubscription?.unsubscribe();
this.annotationCacheSubscription?.unsubscribe();
// Cannot await async export in ngOnDestroy — use cached annotation data
this.persistAnnotationsSync();
this.destroyBookViewer();
this.destroyDocViewerIframe();
if (this.appSettingsSubscription) {
this.appSettingsSubscription.unsubscribe();
}
document.removeEventListener('fullscreenchange', this.onFullscreenChange);
this.mouseMoveCleanup?.();
this.documentClickCleanup?.();
@@ -1270,6 +1374,17 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
this.isToolbarOverflowOpen.set(false);
}
onCloseReaderPointerDown(event: PointerEvent): void {
if (event.pointerType === 'mouse') return;
event.preventDefault();
this.requestCloseReader();
}
onCloseReaderClick(event?: Event): void {
event?.preventDefault();
this.requestCloseReader();
}
// --- Fullscreen ---
toggleFullscreen(): void {
@@ -1356,31 +1471,52 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
}
}
private requestCloseReader(): void {
if (this.isClosingReader()) return;
this.isClosingReader.set(true);
void this.closeReader();
}
closeReader = async (): Promise<void> => {
if (this.closeReaderPromise) return this.closeReaderPromise;
this.closeReaderPromise = this.performCloseReader();
return this.closeReaderPromise;
}
private async performCloseReader(): Promise<void> {
try {
if (this.viewerMode() === 'document' && this.embedPdfIframe) {
await this.saveEmbedPdfDocument();
await this.destroyDocViewerIframe();
} else {
await this.persistAnnotations();
try {
if (this.viewerMode() === 'document' && this.embedPdfIframe) {
await this.saveEmbedPdfDocument();
await this.destroyDocViewerIframe();
} else {
await this.persistAnnotations();
}
} catch (e) {
console.error('[PDF Reader] Error saving on close:', e);
}
} catch (e) {
console.error('[PDF Reader] Error saving on close:', e);
}
if (this.readingSessionService.isSessionActive()) {
const currentPage = this.page();
const total = this.totalPages();
const percentage = total > 0 ? Math.round((currentPage / total) * 1000) / 10 : 0;
this.readingSessionService.endSession(currentPage.toString(), percentage);
}
// Navigate back within the SPA; fall back to home if there's no history
if (window.history.length > 1) {
this.location.back();
} else {
this.router.navigate(['/']);
if (this.readingSessionService.isSessionActive()) {
const currentPage = this.page();
const total = this.totalPages();
const percentage = total > 0 ? Math.round((currentPage / total) * 1000) / 10 : 0;
this.readingSessionService.endSession(currentPage.toString(), percentage);
}
// Navigate back within the SPA; fall back to home if there's no history
if (window.history.length > 1) {
this.location.back();
} else {
this.router.navigate(['/']);
}
} finally {
this.resetCloseReaderState();
}
}
private resetCloseReaderState(): void {
this.closeReaderPromise = null;
this.isClosingReader.set(false);
}
private getBookData(
bookId: string,
fileType: string | undefined,