From 64945c0f992c926a7b32aa637a873dbe7f93ab34 Mon Sep 17 00:00:00 2001 From: brios <127139797+balazs-szucs@users.noreply.github.com> Date: Sun, 3 May 2026 09:50:37 +0200 Subject: [PATCH] feat(pdf-reader): PDF reader for vertical/infinite scroll layouts and improved responsiveness (#841) --- .../org/booklore/model/dto/BookLoreUser.java | 1 + .../src/app/features/book/model/book.model.ts | 1 + .../ebook-reader/shared/icon.component.ts | 89 +++- .../pdf-reader/pdf-reader.component.html | 475 +++++++++--------- .../pdf-reader/pdf-reader.component.scss | 54 +- .../pdf-reader/pdf-reader.component.ts | 226 +++++++-- .../services/embedpdf-book.service.ts | 199 +++++--- .../utils/annotation-converter.spec.ts | 81 +++ .../pdf-reader/utils/annotation-converter.ts | 79 ++- .../pdf-reader-preferences-component.html | 25 + .../pdf-reader-preferences-component.ts | 14 + .../settings/user-management/user.service.ts | 1 + frontend/src/assets/embedpdf-frame.html | 111 +++- frontend/src/i18n/en/reader-pdf.json | 4 + frontend/src/i18n/en/settings-reader.json | 4 + 15 files changed, 959 insertions(+), 405 deletions(-) create mode 100644 frontend/src/app/features/readers/pdf-reader/utils/annotation-converter.spec.ts diff --git a/backend/src/main/java/org/booklore/model/dto/BookLoreUser.java b/backend/src/main/java/org/booklore/model/dto/BookLoreUser.java index 321d95dc9..ec1f1ec2b 100644 --- a/backend/src/main/java/org/booklore/model/dto/BookLoreUser.java +++ b/backend/src/main/java/org/booklore/model/dto/BookLoreUser.java @@ -190,6 +190,7 @@ public class BookLoreUser { public static class PdfReaderSetting { private String pageSpread; private String pageZoom; + private String scrollLayout; } @Data diff --git a/frontend/src/app/features/book/model/book.model.ts b/frontend/src/app/features/book/model/book.model.ts index 64ef3568c..f7d2a6716 100644 --- a/frontend/src/app/features/book/model/book.model.ts +++ b/frontend/src/app/features/book/model/book.model.ts @@ -307,6 +307,7 @@ export interface MetadataUpdateWrapper { export interface PdfViewerSetting { zoom: string; spread: 'none' | 'even' | 'odd'; + scrollLayout?: 'vertical' | 'horizontal'; isDarkTheme?: boolean; } diff --git a/frontend/src/app/features/readers/ebook-reader/shared/icon.component.ts b/frontend/src/app/features/readers/ebook-reader/shared/icon.component.ts index cc625f697..6dbc45dfe 100644 --- a/frontend/src/app/features/readers/ebook-reader/shared/icon.component.ts +++ b/frontend/src/app/features/readers/ebook-reader/shared/icon.component.ts @@ -35,7 +35,22 @@ export type ReaderIconName = | 'direction-ltr' | 'direction-rtl' | 'magnifier' - | 'link'; + | 'link' + | 'sidebar' + | 'highlight' + | 'free-text' + | 'draw' + | 'pan' + | 'spread-none' + | 'spread-double' + | 'scroll-horizontal' + | 'scroll-vertical' + | 'rotate' + | 'sun' + | 'moon' + | 'dots-horizontal' + | 'zoom-in' + | 'zoom-out'; interface IconPath { d: string; @@ -203,6 +218,78 @@ const ICONS: Record = { 'link': [ {d: 'M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71'}, {d: 'M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71'} + ], + 'sidebar': [ + {d: 'M3 3h18v18H3z'}, + {d: 'M9 3v18'} + ], + 'highlight': [ + {d: 'm9 11-6 6v3h9l3-3'}, + {d: 'm22 12-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4'} + ], + 'free-text': [ + {d: 'M17 6.1H3'}, + {d: 'M21 12.1H3'}, + {d: 'M15.1 18H3'} + ], + 'draw': [ + {d: 'M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z'} + ], + 'pan': [ + {d: 'M18 11V6a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v0'}, + {d: 'M14 10V4a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v10'}, + {d: 'M10 10.5V6a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v8'}, + {d: 'M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.8-6.6-3.3l-4.7-5.3a2 2 0 0 1 0-2.8l.3-.3a2 2 0 0 1 2.8 0L8 14'} + ], + 'spread-none': [ + {d: 'M3 3h18v18H3z'} + ], + 'spread-double': [ + {d: 'M2 3h9v18H2z'}, + {d: 'M13 3h9v18H13z'} + ], + 'scroll-horizontal': [ + {d: 'M4 12h16'}, + {d: 'm16 8 4 4-4 4'}, + {d: 'M2 3h3v18H2z'} + ], + 'scroll-vertical': [ + {d: 'M3 2h18v9H3z'}, + {d: 'M3 13h18v9H3z'} + ], + 'rotate': [ + {d: 'M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8'}, + {d: '21,3 21,8 16,8', type: 'polyline'} + ], + 'sun': [ + {d: 'M12 12m-4 0a4 4 0 1 0 8 0a4 4 0 1 0-8 0', type: 'path'}, + {d: 'M12 2v2'}, + {d: 'M12 20v2'}, + {d: 'm4.93 4.93 1.41 1.41'}, + {d: 'm17.66 17.66 1.41 1.41'}, + {d: 'M2 12h2'}, + {d: 'M20 12h2'}, + {d: 'm6.34 17.66-1.41 1.41'}, + {d: 'm19.07 4.93-1.41 1.41'} + ], + 'moon': [ + {d: 'M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z'} + ], + 'dots-horizontal': [ + {d: 'M12,12 m-1,0 a1,1 0 1,0 2,0 a1,1 0 1,0 -2,0', type: 'path'}, + {d: 'M19,12 m-1,0 a1,1 0 1,0 2,0 a1,1 0 1,0 -2,0', type: 'path'}, + {d: 'M5,12 m-1,0 a1,1 0 1,0 2,0 a1,1 0 1,0 -2,0', type: 'path'} + ], + 'zoom-in': [ + {d: 'M11 11m-8 0a8 8 0 1 0 16 0a8 8 0 1 0-16 0', type: 'path'}, + {d: 'M21 21l-4.35-4.35'}, + {d: 'M11 8v6'}, + {d: 'M8 11h6'} + ], + 'zoom-out': [ + {d: 'M11 11m-8 0a8 8 0 1 0 16 0a8 8 0 1 0-16 0', type: 'path'}, + {d: 'M21 21l-4.35-4.35'}, + {d: 'M8 11h6'} ] }; diff --git a/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.html b/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.html index 4e1083326..6c8c56945 100644 --- a/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.html +++ b/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.html @@ -16,13 +16,6 @@ } @if (viewerMode() === 'document') { - @if (docViewerReady()) { - - } - @if (isDocViewerInfoVisible()) {
{{ 'readerPdf.docViewer.changesSavedInfo' | transloco }} @@ -41,13 +34,7 @@
- +
{{ bookTitle() }} @@ -55,79 +42,21 @@
- - - +
- - - - - - + + + +
- - - +
- - +
- @if (isZoomMenuOpen()) { @@ -140,101 +69,28 @@
}
- - +
- - - - - - + + +
- - - - - - + +
- +
- - - + +
-
@@ -244,83 +100,32 @@ @if (isToolbarOverflowOpen()) {
- - - - + + + + + + +
- - - - -
} @@ -329,10 +134,7 @@ @if (isSearchOpen()) { @@ -431,3 +233,176 @@
} + + + + @let size = iconSize || 18; + @switch (id) { + @case ('sidebar') { + + } + @case ('search') { + + } + @case ('highlight') { + + } + @case ('freeText') { + + } + @case ('ink') { + + } + @case ('pan') { + + } + @case ('bookmark') { + + } + @case ('zoomOut') { + + } + @case ('zoomIn') { + + } + @case ('spreadMode') { + + } + @case ('scrollLayout') { + + } + @case ('rotate') { + + } + @case ('theme') { + + } + @case ('fullscreen') { + + } + @case ('overflow') { + + } + } + + + + @if (isOverflow) { + + } @else { + + } + diff --git a/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.scss b/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.scss index 739c18706..6873c733e 100644 --- a/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.scss +++ b/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.scss @@ -150,6 +150,8 @@ $transition-fast: 150ms ease; display: flex; align-items: center; justify-content: center; + touch-action: manipulation; + -webkit-tap-highlight-color: rgb(255 255 255 / 12%); &:hover { background: $hover-bg; @@ -160,6 +162,11 @@ $transition-fast: 150ms ease; color: #ef4444; } + &:disabled { + opacity: 0.65; + cursor: default; + } + &.annotation-tool-btn.active { color: $active-color; background: rgb(74 144 226 / 15%); @@ -287,7 +294,13 @@ $transition-fast: 150ms ease; inset: 0; width: 100%; height: 100%; - overflow: hidden; + overflow-x: hidden; + overflow-y: auto; + + &.horizontal-scroll { + overflow-x: auto; + overflow-y: hidden; + } embedpdf-container { width: 100%; @@ -547,27 +560,35 @@ $transition-fast: 150ms ease; .embed-close-btn { position: fixed; top: 0; - right: 0; + right: 10px; z-index: 11000; color: #fff; - width: 44px; - height: 38px; + width: 38px; + height: $header-height; display: flex; align-items: center; justify-content: center; - background: #2d2d2d; + background: transparent; border: none; - border-bottom: 1px solid #404040; + border-left: none; cursor: pointer; padding: 0; transition: background $transition-fast; + touch-action: manipulation; + -webkit-tap-highlight-color: rgb(255 255 255 / 12%); + border-radius: 0; &:hover { - background: #3a3a3a; + background: rgb(255 255 255 / 10%); } &:active { - background: #444; + background: rgb(255 255 255 / 16%); + } + + &:disabled { + opacity: 0.8; + cursor: default; } } @@ -764,6 +785,23 @@ $transition-fast: 150ms ease; padding-top: env(safe-area-inset-top); } + .icon-btn.close-btn { + min-width: 46px; + min-height: 46px; + border-radius: 8px; + } + + .embed-close-btn { + top: calc(env(safe-area-inset-top) + 2px); + right: 10px; + width: 38px; + height: $header-height; + min-width: 38px; + min-height: $header-height; + border-radius: 0; + border-left: none; + } + .desktop-actions { display: none; } diff --git a/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.ts b/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.ts index 7b1c2574d..e43fa4faf 100644 --- a/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.ts +++ b/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.ts @@ -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(null); readonly spreadMode = signal<'none' | 'odd' | 'even'>('none'); + readonly scrollLayout = signal('vertical'); readonly goToPageInput = signal(null); readonly outline = signal([]); readonly pdfBookmarks = signal([]); @@ -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; + private closeReaderPromise: Promise | 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(); private altBookType?: string; - private appSettingsSubscription!: Subscription; private annotationSaveSubject = new Subject(); private annotationCacheSubject = new Subject(); - 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 => { + if (this.closeReaderPromise) return this.closeReaderPromise; + this.closeReaderPromise = this.performCloseReader(); + return this.closeReaderPromise; + } + + private async performCloseReader(): Promise { 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, diff --git a/frontend/src/app/features/readers/pdf-reader/services/embedpdf-book.service.ts b/frontend/src/app/features/readers/pdf-reader/services/embedpdf-book.service.ts index f08b95b51..76482e96e 100644 --- a/frontend/src/app/features/readers/pdf-reader/services/embedpdf-book.service.ts +++ b/frontend/src/app/features/readers/pdf-reader/services/embedpdf-book.service.ts @@ -1,5 +1,5 @@ import {Injectable, NgZone, inject} from '@angular/core'; -import {ReplaySubject, Subject} from 'rxjs'; +import {ReplaySubject, Subject, skip, take} from 'rxjs'; import type { EmbedPdfContainer, PluginRegistry, @@ -19,12 +19,48 @@ import type { I18nCapability, } from '@embedpdf/snippet'; + export interface PdfOutlineItem { title: string; pageIndex: number; children: PdfOutlineItem[]; } +export type PdfScrollLayout = 'vertical' | 'horizontal'; + +type ScrollLayoutMethod = (layout: PdfScrollLayout) => void; +type ReadScrollLayoutMethod = () => string; + +interface ScrollLayoutCapability extends Omit { + onLayoutReady?: (cb: () => void) => () => void; + setScrollStrategy?: ScrollLayoutMethod; + setScrollMode?: ScrollLayoutMethod; + setLayoutMode?: ScrollLayoutMethod; + getScrollStrategy?: ReadScrollLayoutMethod; + getScrollMode?: ReadScrollLayoutMethod; + getLayoutMode?: ReadScrollLayoutMethod; +} + +interface DocumentOpenedEvent { + id: string; + document?: { + pageCount: number; + } | null; + pageCount?: number; +} + +interface DocumentManagerCapability { + onDocumentOpened?: (cb: (ev: DocumentOpenedEvent) => void) => () => void; +} + +interface GrimmoryWindowState { + __grimmoryOrigDprDescriptor?: PropertyDescriptor; + __grimmoryShimsApplied?: boolean; + __grimmoryOrigBlob?: typeof Blob; + __grimmoryOrigWorker?: typeof Worker; + __grimmoryOrigRelease?: typeof Element.prototype.releasePointerCapture; +} + @Injectable() export class EmbedPdfBookService { private zone = inject(NgZone); @@ -40,6 +76,7 @@ export class EmbedPdfBookService { private rotate: RotateCapability | null = null; private pan: PanCapability | null = null; private i18n: I18nCapability | null = null; + private scrollLayout: PdfScrollLayout = 'vertical'; private currentDocumentId: string | null = null; @@ -50,6 +87,11 @@ export class EmbedPdfBookService { private documentOpenedUnsub?: () => void; private resizeObserver?: ResizeObserver; + + private getMutableWindow(): Window & typeof globalThis & GrimmoryWindowState { + return window as Window & typeof globalThis & GrimmoryWindowState; + } + pageChange$ = new Subject(); annotationEvent$ = new Subject(); documentOpened$ = new ReplaySubject<{pageCount: number}>(1); @@ -78,7 +120,6 @@ export class EmbedPdfBookService { const wasmUrl = new URL('/assets/pdfium/pdfium.wasm', location.origin).href; const requestedLocale = localeCode || 'en'; - const isSmallViewport = window.innerWidth <= 768; this.container = EmbedPDF.init({ type: 'container', @@ -122,7 +163,8 @@ export class EmbedPdfBookService { defaultZoomLevel: 'fit-page' as ZoomMode, }, render: { - defaultImageQuality: isSmallViewport ? 0.85 : 0.92, + // Keep book-viewer text crisp across viewport sizes. + defaultImageQuality: 0.92, }, tiling: this.getTilingConfig(), }) ?? null; @@ -140,6 +182,7 @@ export class EmbedPdfBookService { const scrollPlugin = this.registry.getPlugin('scroll'); this.scroll = scrollPlugin?.provides?.() as ScrollCapability ?? null; + this.applyScrollLayout(this.scrollLayout); const zoomPlugin = this.registry.getPlugin('zoom'); this.zoom = zoomPlugin?.provides?.() as ZoomCapability ?? null; @@ -172,10 +215,9 @@ export class EmbedPdfBookService { this.pageChange$.next(ev); }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (typeof (this.scroll as any).onLayoutReady === 'function') { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.layoutReadyUnsub = (this.scroll as any).onLayoutReady(() => { + const scrollWithLayoutReady = this.scroll as ScrollLayoutCapability; + if (typeof scrollWithLayoutReady.onLayoutReady === 'function') { + this.layoutReadyUnsub = scrollWithLayoutReady.onLayoutReady(() => { this.zone.run(() => this.layoutReady$.next()); }); } @@ -183,13 +225,13 @@ export class EmbedPdfBookService { // Listen for document opened via document-manager plugin const dmPlugin = this.registry.getPlugin('document-manager'); - const dm = dmPlugin?.provides?.() as Record | null; - if (dm && typeof dm['onDocumentOpened'] === 'function') { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.documentOpenedUnsub = (dm['onDocumentOpened'] as (cb: (ev: any) => void) => () => void)((ev: {id: string, pageCount?: number}) => { + const dm = dmPlugin?.provides?.() as DocumentManagerCapability | null; + if (dm && typeof dm.onDocumentOpened === 'function') { + this.documentOpenedUnsub = dm.onDocumentOpened((ev: DocumentOpenedEvent) => { this.zone.run(() => { this.currentDocumentId = ev.id; - this.documentOpened$.next({pageCount: ev?.pageCount ?? this.scroll?.getTotalPages() ?? 0}); + const pageCount = ev.document?.pageCount ?? ev.pageCount ?? this.scroll?.getTotalPages() ?? 0; + this.documentOpened$.next({pageCount}); }); }); } else { @@ -222,6 +264,31 @@ export class EmbedPdfBookService { this.applyLocale(localeCode || 'en'); } + setScrollLayout(layout: PdfScrollLayout): void { + const page = this.currentPage; + this.scrollLayout = layout; + this.applyScrollLayout(layout); + + // EmbedPDF layout changes are asynchronous and can reset the current page internally. + // We wait for the layout engine to settle before restoring the page position. + let handled = false; + const restorePage = () => { + if (handled) return; + handled = true; + this.scrollToPage(page, 'instant'); + }; + + // Use a short timeout as fallback + const timeoutId = setTimeout(restorePage, 100); + + // If the engine supports onLayoutReady, it will fire layoutReady$. + // We skip the current replayed value and wait for the next emission. + this.layoutReady$.pipe(skip(1), take(1)).subscribe(() => { + clearTimeout(timeoutId); + restorePage(); + }); + } + scrollToPage(pageNumber: number, behavior: 'instant' | 'smooth' = 'smooth'): void { this.scroll?.scrollToPage({pageNumber, behavior}); } @@ -378,6 +445,7 @@ export class EmbedPdfBookService { this.resizeObserver?.disconnect(); this.resizeObserver = undefined; + this.pageChange$.complete(); this.annotationEvent$.complete(); this.documentOpened$.complete(); @@ -416,6 +484,25 @@ export class EmbedPdfBookService { this.i18n.setLocale('en'); } + private applyScrollLayout(layout: PdfScrollLayout): void { + if (!this.scroll) return; + const scrollLayoutCap = this.scroll as ScrollLayoutCapability; + + if (typeof scrollLayoutCap.setScrollStrategy === 'function') { + scrollLayoutCap.setScrollStrategy(layout); + return; + } + + if (typeof scrollLayoutCap.setScrollMode === 'function') { + scrollLayoutCap.setScrollMode(layout); + return; + } + + if (typeof scrollLayoutCap.setLayoutMode === 'function') { + scrollLayoutCap.setLayoutMode(layout); + } + } + private convertBookmarks(items: unknown[]): PdfOutlineItem[] { if (!Array.isArray(items)) return []; @@ -472,14 +559,14 @@ export class EmbedPdfBookService { const isSmallViewport = window.innerWidth <= 768; const currentDpr = window.devicePixelRatio || 1; - // On small screens, we CAP the DPR at 2.0. + // On small screens, enforce DPR 2.0 to avoid low-DPR blur while still + // avoiding the memory spikes caused by very high DPR values. // Modern phones often have DPR 3.0+, which combined with annotation layers // exceeds the browser's texture memory budget, leading to "emergency" downsampling (blurriness). - const targetDpr = isSmallViewport ? Math.min(currentDpr, 2) : Math.max(currentDpr, 2.5); + const targetDpr = isSmallViewport ? 2 : Math.max(currentDpr, 2.5); if (currentDpr !== targetDpr) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const w = window as any; + const w = this.getMutableWindow(); w.__grimmoryOrigDprDescriptor = Object.getOwnPropertyDescriptor(window, 'devicePixelRatio'); Object.defineProperty(window, 'devicePixelRatio', { get: () => targetDpr, @@ -497,7 +584,7 @@ export class EmbedPdfBookService { private getTilingConfig(): {tileSize: number; overlapPx: number; extraRings: number} { const isSmallViewport = window.innerWidth <= 768; return isSmallViewport - ? {tileSize: 512, overlapPx: 2, extraRings: 0} + ? {tileSize: 640, overlapPx: 2, extraRings: 1} : {tileSize: 1024, overlapPx: 2, extraRings: 1}; } @@ -511,15 +598,14 @@ export class EmbedPdfBookService { * Idempotent — safe to call multiple times. */ private applyWorkerShims(): void { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const w = window as any; + const w = this.getMutableWindow(); if (w.__grimmoryShimsApplied) return; w.__grimmoryShimsApplied = true; // --- Blob shim --- const OrigBlob = window.Blob; w.__grimmoryOrigBlob = OrigBlob; - w.Blob = function PatchedBlob(parts: BlobPart[], opts?: BlobPropertyBag) { + const PatchedBlob = function (parts: BlobPart[], opts?: BlobPropertyBag): Blob { if (parts?.length >= 1 && typeof parts[0] === 'string') { const src = parts[0] as string; if (src.includes('wasmInit') && src.includes('runner.prepare()')) { @@ -539,14 +625,15 @@ export class EmbedPdfBookService { } } return new OrigBlob(parts, opts); - }; - w.Blob.prototype = OrigBlob.prototype; - Object.setPrototypeOf(w.Blob, OrigBlob); + } as unknown as typeof Blob; + PatchedBlob.prototype = OrigBlob.prototype; + Object.setPrototypeOf(PatchedBlob, OrigBlob); + w.Blob = PatchedBlob; // --- Worker shim --- const OrigWorker = window.Worker; w.__grimmoryOrigWorker = OrigWorker; - w.Worker = function PatchedWorker(url: string | URL, opts?: WorkerOptions) { + const PatchedWorker = function (url: string | URL, opts?: WorkerOptions): Worker { const worker = new OrigWorker(url, opts); const urlStr = typeof url === 'string' ? url : url.toString(); if (urlStr.startsWith('blob:') && opts?.type === 'module') { @@ -566,14 +653,14 @@ export class EmbedPdfBookService { }); } return worker; - }; - w.Worker.prototype = OrigWorker.prototype; - Object.setPrototypeOf(w.Worker, OrigWorker); + } as unknown as typeof Worker; + PatchedWorker.prototype = OrigWorker.prototype; + Object.setPrototypeOf(PatchedWorker, OrigWorker); + w.Worker = PatchedWorker; } private restoreWorkerShims(): void { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const w = window as any; + const w = this.getMutableWindow(); if (!w.__grimmoryShimsApplied) return; if (w.__grimmoryOrigBlob) { window.Blob = w.__grimmoryOrigBlob; @@ -593,8 +680,7 @@ export class EmbedPdfBookService { * already been released by the time the cleanup call fires. */ private patchReleasePointerCapture(): void { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const w = window as any; + const w = this.getMutableWindow(); if (w.__grimmoryOrigRelease) return; const orig = Element.prototype.releasePointerCapture; w.__grimmoryOrigRelease = orig; @@ -608,8 +694,7 @@ export class EmbedPdfBookService { } private restoreReleasePointerCapture(): void { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const w = window as any; + const w = this.getMutableWindow(); if (w.__grimmoryOrigRelease) { Element.prototype.releasePointerCapture = w.__grimmoryOrigRelease; delete w.__grimmoryOrigRelease; @@ -617,14 +702,12 @@ export class EmbedPdfBookService { } private restoreDevicePixelRatio(): void { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const w = window as any; + const w = this.getMutableWindow(); if (w.__grimmoryOrigDprDescriptor) { Object.defineProperty(window, 'devicePixelRatio', w.__grimmoryOrigDprDescriptor); delete w.__grimmoryOrigDprDescriptor; } else if (Object.getOwnPropertyDescriptor(window, 'devicePixelRatio')?.configurable) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - delete (window as any)['devicePixelRatio']; + Reflect.deleteProperty(window, 'devicePixelRatio'); } } @@ -636,13 +719,24 @@ export class EmbedPdfBookService { if (attempt < 25) setTimeout(() => waitForShadow(attempt + 1), 200); return; } - if (shadow.querySelector('style[data-grimmory-book]')) return; + if (shadow.querySelector('style[data-grimmory-book]')) { + return; + } const style = document.createElement('style'); style.setAttribute('data-grimmory-book', ''); style.textContent = ` /* ── Grimmory book-mode overrides ── */ + /* Center PDF content vertically and horizontally when smaller than viewport */ + [class*="bg-bg-app"] { + display: flex !important; + flex-direction: column !important; + } + [class*="bg-bg-app"] > * { + margin: auto !important; + } + /* Force high-quality image rendering for PDF tiles */ img { image-rendering: high-quality; @@ -673,24 +767,7 @@ export class EmbedPdfBookService { display: none !important; } - /* Hide the built-in footer/status bar */ - [class*="border-t"][class*="bg-bg-surface"][class*="px-4"][class*="py-1"] { - display: none !important; - } - - /* Hide bottom notification / popup bar */ - [class*="fixed"][class*="bottom-"], - [class*="absolute"][class*="bottom-"], - [class*="snackbar"], - [class*="toast"], - [class*="notification"], - [class*="bottom-bar"], - [class*="status-bar"], - [class*="statusbar"], - footer, - [class*="footer"] { - display: none !important; - } + /* Keep viewer popups/menus visible; only hide explicit file controls. */ /* Hide open/close document buttons */ [data-epdf-i="open-document"], @@ -700,6 +777,14 @@ export class EmbedPdfBookService { display: none !important; } + /* ── Hide EmbedPDF built-in footer / status bar ── */ + [data-epdf-i*="footer"], + [data-epdf-i*="status"], + [data-overlay-id="page-controls"], + [data-overlay-id*="overlay"], + [role="contentinfo"] { + display: none !important; + } /* Improve annotation layer rendering on touch devices. FreeText annotation overlays can bleed through when the @@ -727,6 +812,8 @@ export class EmbedPdfBookService { waitForShadow(); } + + private setupResizeObserver(target: HTMLElement): void { if (typeof ResizeObserver === 'undefined') return; diff --git a/frontend/src/app/features/readers/pdf-reader/utils/annotation-converter.spec.ts b/frontend/src/app/features/readers/pdf-reader/utils/annotation-converter.spec.ts new file mode 100644 index 000000000..d5eb3876e --- /dev/null +++ b/frontend/src/app/features/readers/pdf-reader/utils/annotation-converter.spec.ts @@ -0,0 +1,81 @@ +import {describe, expect, it} from 'vitest'; +import type {AnnotationTransferItem} from '@embedpdf/snippet'; + +import {parseStoredAnnotations, serializeAnnotations} from './annotation-converter'; + +function createHighlightItem(opacity = 0.9): AnnotationTransferItem { + return { + annotation: { + type: 9, + pageIndex: 0, + id: 'annotation-1', + rect: {origin: {x: 1, y: 2}, size: {width: 10, height: 12}}, + segmentRects: [{origin: {x: 1, y: 2}, size: {width: 10, height: 12}}], + color: '#FFFF00', + opacity, + } as never, + ctx: { + data: new Uint8Array([1, 2, 3, 4]).buffer, + }, + } as AnnotationTransferItem; +} + +describe('annotation-converter', () => { + it('serializes and restores ArrayBuffer payloads', () => { + const source = [createHighlightItem(0.5)]; + + const json = serializeAnnotations(source); + const restored = parseStoredAnnotations(json); + + const first = restored[0] as {ctx?: {data?: ArrayBuffer}}; + expect(restored).toHaveLength(1); + expect(first.ctx?.data).toBeInstanceOf(ArrayBuffer); + + const bytes = new Uint8Array(first.ctx?.data ?? new ArrayBuffer(0)); + expect(Array.from(bytes)).toEqual([1, 2, 3, 4]); + }); + + it('caps highlight opacity when reading stored embedpdf annotations', () => { + const json = JSON.stringify({ + format: 'embedpdf', + version: 1, + annotations: [ + { + ...createHighlightItem(0.95), + ctx: { + data: 'AQIDBA==', + _dataEncoding: 'base64', + }, + }, + ], + }); + + const restored = parseStoredAnnotations(json); + const annotation = restored[0]?.annotation as {opacity?: number}; + expect(annotation.opacity).toBe(0.6); + }); + + it('converts legacy pdf.js annotations to embedpdf transfer items', () => { + const legacy = JSON.stringify([ + { + annotationType: 9, + pageIndex: 3, + rect: [10, 20, 80, 120], + color: [1, 0.8, 0], + opacity: 0.8, + }, + ]); + + const converted = parseStoredAnnotations(legacy); + const annotation = converted[0]?.annotation as {type?: number; pageIndex?: number; opacity?: number}; + + expect(converted).toHaveLength(1); + expect(annotation.type).toBe(9); + expect(annotation.pageIndex).toBe(3); + expect(annotation.opacity).toBe(0.6); + }); + + it('returns empty list for malformed payload', () => { + expect(parseStoredAnnotations('{not-json')).toEqual([]); + }); +}); diff --git a/frontend/src/app/features/readers/pdf-reader/utils/annotation-converter.ts b/frontend/src/app/features/readers/pdf-reader/utils/annotation-converter.ts index a039c16f4..9ae6071de 100644 --- a/frontend/src/app/features/readers/pdf-reader/utils/annotation-converter.ts +++ b/frontend/src/app/features/readers/pdf-reader/utils/annotation-converter.ts @@ -11,6 +11,31 @@ export interface StoredAnnotations { annotations: AnnotationTransferItem[]; } +type AnnotationWithOpacity = AnnotationTransferItem['annotation'] & { + type?: number; + opacity?: number; +}; + +interface SerializableCtx { + data?: ArrayBuffer | string; + _dataEncoding?: 'base64'; + [key: string]: unknown; +} + +interface SerializableAnnotationTransferItem { + annotation?: AnnotationWithOpacity; + ctx?: SerializableCtx; + [key: string]: unknown; +} + +function toSerializableAnnotationTransferItem(item: AnnotationTransferItem): SerializableAnnotationTransferItem { + return item as unknown as SerializableAnnotationTransferItem; +} + +function toAnnotationTransferItem(item: SerializableAnnotationTransferItem): AnnotationTransferItem { + return item as AnnotationTransferItem; +} + /** * Detect and parse stored annotation data. * Returns EmbedPDF AnnotationTransferItems ready for import, or empty array. @@ -23,7 +48,15 @@ export function parseStoredAnnotations(jsonString: string | null | undefined): A // New format: { format: 'embedpdf', version: 1, annotations: [...] } if (parsed && parsed.format === 'embedpdf' && Array.isArray(parsed.annotations)) { - return parsed.annotations.map(restoreArrayBuffers); + const storedItems = parsed.annotations as SerializableAnnotationTransferItem[]; + return storedItems.reduce((acc, item) => { + try { + acc.push(restoreArrayBuffers(item)); + } catch { + // Skip malformed entries, keep valid annotations + } + return acc; + }, []); } // Legacy pdf.js format: raw array of editor annotations @@ -42,24 +75,24 @@ export function parseStoredAnnotations(jsonString: string | null | undefined): A * Handles ArrayBuffer fields (e.g. stamp ctx.data) by encoding to base64. */ export function serializeAnnotations(items: AnnotationTransferItem[]): string { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const serializable = items.map((item: any) => { - if (item.ctx?.data instanceof ArrayBuffer) { + const serializable = items.map((item): SerializableAnnotationTransferItem => { + const itemRecord = toSerializableAnnotationTransferItem(item); + if (itemRecord.ctx?.data instanceof ArrayBuffer) { return { - ...item, + ...itemRecord, ctx: { - ...item.ctx, - data: arrayBufferToBase64(item.ctx.data), + ...itemRecord.ctx, + data: arrayBufferToBase64(itemRecord.ctx.data), _dataEncoding: 'base64', }, }; } - return item; + return itemRecord; }); const wrapped = { format: 'embedpdf' as const, version: 1 as const, - annotations: serializable as AnnotationTransferItem[], + annotations: serializable, }; return JSON.stringify(wrapped); } @@ -235,24 +268,28 @@ function base64ToArrayBuffer(base64: string): ArrayBuffer { return bytes.buffer; } -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function restoreArrayBuffers(item: any): AnnotationTransferItem { +function restoreArrayBuffers(item: SerializableAnnotationTransferItem): AnnotationTransferItem { + const next: SerializableAnnotationTransferItem = { + ...item, + annotation: item.annotation ? {...item.annotation} : undefined, + }; + // Cap opacity for highlights to prevent solid blocks - if (item.annotation?.type === 9) { - const rawOpacity = item.annotation.opacity ?? 0.4; - item.annotation.opacity = Math.min(rawOpacity, 0.6); + if (next.annotation?.type === 9) { + const rawOpacity = next.annotation.opacity ?? 0.4; + next.annotation.opacity = Math.min(rawOpacity, 0.6); } - if (item.ctx?._dataEncoding === 'base64' && typeof item.ctx.data === 'string') { + if (next.ctx?._dataEncoding === 'base64' && typeof next.ctx.data === 'string') { // eslint-disable-next-line @typescript-eslint/no-unused-vars - const {_dataEncoding: _, ...rest} = item.ctx; - return { - ...item, + const {_dataEncoding: _, ...rest} = next.ctx; + return toAnnotationTransferItem({ + ...next, ctx: { ...rest, - data: base64ToArrayBuffer(item.ctx.data), + data: base64ToArrayBuffer(next.ctx.data), }, - }; + }); } - return item; + return toAnnotationTransferItem(next); } diff --git a/frontend/src/app/features/settings/reader-preferences/pdf-reader-preferences/pdf-reader-preferences-component.html b/frontend/src/app/features/settings/reader-preferences/pdf-reader-preferences/pdf-reader-preferences-component.html index 2cbbfd1a9..028a916ba 100644 --- a/frontend/src/app/features/settings/reader-preferences/pdf-reader-preferences/pdf-reader-preferences-component.html +++ b/frontend/src/app/features/settings/reader-preferences/pdf-reader-preferences/pdf-reader-preferences-component.html @@ -49,5 +49,30 @@

+ +
+
+
+ {{ t('scrollLayout') }} +
+ @for (layout of scrollLayouts; track layout) { + + } +
+
+

+ {{ t('scrollLayoutDesc') }} +

+
+
diff --git a/frontend/src/app/features/settings/reader-preferences/pdf-reader-preferences/pdf-reader-preferences-component.ts b/frontend/src/app/features/settings/reader-preferences/pdf-reader-preferences/pdf-reader-preferences-component.ts index 722b84f52..b0774079e 100644 --- a/frontend/src/app/features/settings/reader-preferences/pdf-reader-preferences/pdf-reader-preferences-component.ts +++ b/frontend/src/app/features/settings/reader-preferences/pdf-reader-preferences/pdf-reader-preferences-component.ts @@ -33,6 +33,11 @@ export class PdfReaderPreferencesComponent { {name: 'Actual Size', key: 'page-actual', icon: 'pi pi-expand', translationKey: 'actualSize'} ]; + readonly scrollLayouts: {name: string; key: 'vertical' | 'horizontal'; icon: string; translationKey: string}[] = [ + {name: 'Vertical', key: 'vertical', icon: 'pi pi-arrows-v', translationKey: 'vertical'}, + {name: 'Horizontal', key: 'horizontal', icon: 'pi pi-arrows-h', translationKey: 'horizontal'} + ]; + get selectedSpread(): 'even' | 'odd' | 'off' { return this.userSettings.pdfReaderSetting.pageSpread; } @@ -50,4 +55,13 @@ export class PdfReaderPreferencesComponent { this.userSettings.pdfReaderSetting.pageZoom = value; this.readerPreferencesService.updatePreference(['pdfReaderSetting', 'pageZoom'], value); } + + get selectedScrollLayout(): 'vertical' | 'horizontal' { + return this.userSettings.pdfReaderSetting.scrollLayout ?? 'vertical'; + } + + set selectedScrollLayout(value: 'vertical' | 'horizontal') { + this.userSettings.pdfReaderSetting.scrollLayout = value; + this.readerPreferencesService.updatePreference(['pdfReaderSetting', 'scrollLayout'], value); + } } diff --git a/frontend/src/app/features/settings/user-management/user.service.ts b/frontend/src/app/features/settings/user-management/user.service.ts index 7cbabe2e2..e67e51a0f 100644 --- a/frontend/src/app/features/settings/user-management/user.service.ts +++ b/frontend/src/app/features/settings/user-management/user.service.ts @@ -131,6 +131,7 @@ export interface PdfReaderSetting { pageSpread: PageSpread; pageZoom: string; showSidebar: boolean; + scrollLayout?: 'vertical' | 'horizontal'; } export enum PdfPageViewMode { diff --git a/frontend/src/assets/embedpdf-frame.html b/frontend/src/assets/embedpdf-frame.html index 96d9aa41f..e061d0ced 100644 --- a/frontend/src/assets/embedpdf-frame.html +++ b/frontend/src/assets/embedpdf-frame.html @@ -2,7 +2,7 @@ - +