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
@@ -190,6 +190,7 @@ public class BookLoreUser {
public static class PdfReaderSetting {
private String pageSpread;
private String pageZoom;
private String scrollLayout;
}
@Data
@@ -307,6 +307,7 @@ export interface MetadataUpdateWrapper {
export interface PdfViewerSetting {
zoom: string;
spread: 'none' | 'even' | 'odd';
scrollLayout?: 'vertical' | 'horizontal';
isDarkTheme?: boolean;
}
@@ -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<ReaderIconName, IconPath[]> = {
'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'}
]
};
@@ -16,13 +16,6 @@
}
@if (viewerMode() === 'document') {
@if (docViewerReady()) {
<button class="embed-close-btn icon-btn" [title]="'readerPdf.toolbar.closePdfReader' | transloco"
(click)="closeReader()">
<app-reader-icon name="close" [size]="18" />
</button>
}
@if (isDocViewerInfoVisible()) {
<div class="doc-viewer-info">
<span>{{ 'readerPdf.docViewer.changesSavedInfo' | transloco }}</span>
@@ -41,13 +34,7 @@
<!-- Book header toolbar -->
<div class="pdf-header-toolbar" [class.chrome-hidden]="!headerVisible()">
<div class="header-left">
<button class="icon-btn" [title]="'readerPdf.toolbar.sidebar' | transloco" (click)="toggleSidebar()">
<!-- sidebar/menu icon -->
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<rect width="18" height="18" x="3" y="3" rx="2" /><path d="M9 3v18" />
</svg>
</button>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'sidebar' }"></ng-container>
</div>
<span class="book-title">{{ bookTitle() }}</span>
@@ -55,79 +42,21 @@
<div class="header-right">
<!-- Desktop toolbar actions (hidden on mobile) -->
<div class="desktop-actions">
<!-- Search -->
<button class="icon-btn" [class.active]="isSearchOpen()"
[title]="'readerPdf.toolbar.search' | transloco" (click)="toggleSearch()">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8" /><path d="m21 21-4.3-4.3" />
</svg>
</button>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'search' }"></ng-container>
<div class="separator"></div>
<!-- Annotation tools -->
<button class="icon-btn annotation-tool-btn" [class.active]="activeAnnotationTool() === 'highlight'"
[title]="'readerPdf.toolbar.highlight' | transloco" (click)="toggleAnnotationTool('highlight')">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="m9 11-6 6v3h9l3-3" /><path 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" />
</svg>
</button>
<button class="icon-btn annotation-tool-btn" [class.active]="activeAnnotationTool() === 'freeText'"
[title]="'readerPdf.toolbar.freeText' | transloco" (click)="toggleAnnotationTool('freeText')">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M17 6.1H3" /><path d="M21 12.1H3" /><path d="M15.1 18H3" />
</svg>
</button>
<button class="icon-btn annotation-tool-btn" [class.active]="activeAnnotationTool() === 'ink'"
[title]="'readerPdf.toolbar.draw' | transloco" (click)="toggleAnnotationTool('ink')">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path 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" />
</svg>
</button>
<button class="icon-btn annotation-tool-btn" [class.active]="isPanActive()"
[title]="'readerPdf.toolbar.pan' | transloco" (click)="togglePanMode()">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M18 11V6a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v0" /><path d="M14 10V4a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v10" />
<path d="M10 10.5V6a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v8" />
<path 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" />
</svg>
</button>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'highlight' }"></ng-container>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'freeText' }"></ng-container>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'ink' }"></ng-container>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'pan' }"></ng-container>
<div class="separator"></div>
<!-- Bookmark toggle -->
<button class="icon-btn bookmark-btn" [class.bookmarked]="isCurrentPageBookmarked()"
[title]="isCurrentPageBookmarked() ? ('readerPdf.toolbar.removeBookmark' | transloco) : ('readerPdf.toolbar.addBookmark' | transloco)"
(click)="toggleBookmark()">
@if (isCurrentPageBookmarked()) {
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"
fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z" />
</svg>
} @else {
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"
fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z" />
</svg>
}
</button>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'bookmark' }"></ng-container>
<div class="separator"></div>
<!-- Zoom controls -->
<button class="icon-btn" [title]="'readerPdf.toolbar.zoomOut' | transloco" (click)="embedPdfBook.zoomOut()">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8" /><path d="m21 21-4.3-4.3" /><path d="M8 11h6" />
</svg>
</button>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'zoomOut' }"></ng-container>
<div class="zoom-menu-wrapper">
<button class="icon-btn zoom-label-btn" (click)="toggleZoomMenu()">
<button class="icon-btn zoom-label-btn" [attr.aria-label]="'readerPdf.toolbar.zoomPreset' | transloco" (click)="toggleZoomMenu()">
<span class="zoom-label">{{ zoom() }}</span>
</button>
@if (isZoomMenuOpen()) {
@@ -140,101 +69,28 @@
</div>
}
</div>
<button class="icon-btn" [title]="'readerPdf.toolbar.zoomIn' | transloco" (click)="embedPdfBook.zoomIn()">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8" /><path d="m21 21-4.3-4.3" /><path d="M11 8v6" /><path d="M8 11h6" />
</svg>
</button>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'zoomIn' }"></ng-container>
<div class="separator"></div>
<!-- Spread mode -->
<button class="icon-btn" [title]="'readerPdf.toolbar.spreadMode' | transloco" (click)="cycleSpreadMode()">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
@if (spreadMode() === 'none') {
<rect x="3" y="3" width="18" height="18" rx="2" />
} @else {
<rect x="2" y="3" width="9" height="18" rx="1" /><rect x="13" y="3" width="9" height="18" rx="1" />
}
</svg>
</button>
<!-- Rotate -->
<button class="icon-btn" [title]="'readerPdf.toolbar.rotatePage' | transloco" (click)="rotateClockwise()">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8" /><path d="M21 3v5h-5" />
</svg>
</button>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'spreadMode' }"></ng-container>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'scrollLayout' }"></ng-container>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'rotate' }"></ng-container>
<div class="separator"></div>
<!-- Theme toggle -->
<button class="icon-btn"
[title]="isDarkTheme() ? ('readerPdf.toolbar.switchToLightMode' | transloco) : ('readerPdf.toolbar.switchToDarkMode' | transloco)"
(click)="toggleDarkTheme()">
@if (isDarkTheme()) {
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="4" />
<path d="M12 2v2" /><path d="M12 20v2" />
<path d="m4.93 4.93 1.41 1.41" /><path d="m17.66 17.66 1.41 1.41" />
<path d="M2 12h2" /><path d="M20 12h2" />
<path d="m6.34 17.66-1.41 1.41" /><path d="m19.07 4.93-1.41 1.41" />
</svg>
} @else {
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" />
</svg>
}
</button>
<!-- Fullscreen -->
<button class="icon-btn" (click)="toggleFullscreen()"
[title]="isFullscreen() ? ('readerPdf.toolbar.exitFullscreen' | transloco) : ('readerPdf.toolbar.fullscreen' | transloco)">
@if (isFullscreen()) {
<app-reader-icon name="fullscreen-exit" [size]="18" />
} @else {
<app-reader-icon name="fullscreen" [size]="18" />
}
</button>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'theme' }"></ng-container>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'fullscreen' }"></ng-container>
<div class="separator"></div>
</div>
<!-- Mobile: bookmark + overflow menu (shown on mobile only) -->
<!-- Mobile actions -->
<div class="mobile-actions">
<button class="icon-btn bookmark-btn" [class.bookmarked]="isCurrentPageBookmarked()"
[attr.aria-label]="isCurrentPageBookmarked() ? ('readerPdf.toolbar.removeBookmark' | transloco) : ('readerPdf.toolbar.addBookmark' | transloco)"
(click)="toggleBookmark()">
@if (isCurrentPageBookmarked()) {
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24"
fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z" />
</svg>
} @else {
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24"
fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z" />
</svg>
}
</button>
<button class="icon-btn overflow-btn" [attr.aria-label]="'readerPdf.toolbar.moreOptions' | transloco" (click)="toggleToolbarOverflow()">
<!-- More/ellipsis icon -->
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="1" /><circle cx="19" cy="12" r="1" /><circle cx="5" cy="12" r="1" />
</svg>
</button>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'bookmark', iconSize: 20 }"></ng-container>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'overflow', iconSize: 20 }"></ng-container>
</div>
<!-- Close button (always visible) -->
<button class="icon-btn close-btn" [title]="'readerPdf.toolbar.closePdfReader' | transloco"
(click)="closeReader()">
<button class="icon-btn close-btn" [title]="'readerPdf.toolbar.closePdfReader' | transloco" [attr.aria-label]="'readerPdf.toolbar.closePdfReader' | transloco"
[disabled]="isClosingReader()" (pointerdown)="onCloseReaderPointerDown($event)" (click)="onCloseReaderClick($event)">
<app-reader-icon name="close" [size]="20" />
</button>
</div>
@@ -244,83 +100,32 @@
@if (isToolbarOverflowOpen()) {
<div class="toolbar-overflow-backdrop" role="presentation" (click)="closeToolbarOverflow()"></div>
<div class="toolbar-overflow-menu" tabindex="-1" (keydown.escape)="closeToolbarOverflow()" #overflowMenu>
<button class="overflow-item" (click)="toggleSearch(); closeToolbarOverflow()">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8" /><path d="m21 21-4.3-4.3" />
</svg>
<span>{{ 'readerPdf.toolbar.search' | transloco }}</span>
</button>
<button class="overflow-item" (click)="toggleAnnotationTool('highlight'); closeToolbarOverflow()">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="m9 11-6 6v3h9l3-3" /><path 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" />
</svg>
<span>{{ 'readerPdf.toolbar.highlight' | transloco }}</span>
</button>
<button class="overflow-item" (click)="toggleAnnotationTool('ink'); closeToolbarOverflow()">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path 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" />
</svg>
<span>{{ 'readerPdf.toolbar.draw' | transloco }}</span>
</button>
<button class="overflow-item" [class.active]="isPanActive()" (click)="togglePanMode(); closeToolbarOverflow()">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M18 11V6a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v0" /><path d="M14 10V4a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v10" />
<path d="M10 10.5V6a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v8" />
<path 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" />
</svg>
<span>{{ 'readerPdf.toolbar.pan' | transloco }}</span>
</button>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'sidebar', isOverflow: true }"></ng-container>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'search', isOverflow: true }"></ng-container>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'highlight', isOverflow: true }"></ng-container>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'freeText', isOverflow: true }"></ng-container>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'ink', isOverflow: true }"></ng-container>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'pan', isOverflow: true }"></ng-container>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'scrollLayout', isOverflow: true }"></ng-container>
<div class="overflow-divider"></div>
<button class="overflow-item" (click)="toggleDarkTheme(); closeToolbarOverflow()">
@if (isDarkTheme()) {
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="4" />
<path d="M12 2v2" /><path d="M12 20v2" />
<path d="m4.93 4.93 1.41 1.41" /><path d="m17.66 17.66 1.41 1.41" />
<path d="M2 12h2" /><path d="M20 12h2" />
<path d="m6.34 17.66-1.41 1.41" /><path d="m19.07 4.93-1.41 1.41" />
</svg>
} @else {
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" />
</svg>
}
<span>{{ isDarkTheme() ? ('readerPdf.toolbar.switchToLightMode' | transloco) : ('readerPdf.toolbar.switchToDarkMode' | transloco) }}</span>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'bookmark', isOverflow: true }"></ng-container>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'spreadMode', isOverflow: true }"></ng-container>
<div class="overflow-divider"></div>
@for (preset of zoomPresets; track preset.value) {
<button class="overflow-item" [class.active]="zoom() === preset.value" (click)="setZoomPreset(preset.value); closeToolbarOverflow()">
<app-reader-icon name="magnifier" [size]="18" />
<span>{{ preset.label }}</span>
</button>
<button class="overflow-item" (click)="rotateClockwise(); closeToolbarOverflow()">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8" /><path d="M21 3v5h-5" />
</svg>
<span>{{ 'readerPdf.toolbar.rotatePage' | transloco }}</span>
</button>
<button class="overflow-item" (click)="embedPdfBook.zoomIn(); closeToolbarOverflow()">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8" /><path d="m21 21-4.3-4.3" /><path d="M11 8v6" /><path d="M8 11h6" />
</svg>
<span>{{ 'readerPdf.toolbar.zoomIn' | transloco }}</span>
</button>
<button class="overflow-item" (click)="embedPdfBook.zoomOut(); closeToolbarOverflow()">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8" /><path d="m21 21-4.3-4.3" /><path d="M8 11h6" />
</svg>
<span>{{ 'readerPdf.toolbar.zoomOut' | transloco }}</span>
</button>
<button class="overflow-item" (click)="toggleFullscreen(); closeToolbarOverflow()">
@if (isFullscreen()) {
<app-reader-icon name="fullscreen-exit" [size]="18" />
} @else {
<app-reader-icon name="fullscreen" [size]="18" />
}
<span>{{ isFullscreen() ? ('readerPdf.toolbar.exitFullscreen' | transloco) : ('readerPdf.toolbar.fullscreen' | transloco) }}</span>
}
<div class="overflow-divider"></div>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'theme', isOverflow: true }"></ng-container>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'rotate', isOverflow: true }"></ng-container>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'zoomIn', isOverflow: true }"></ng-container>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'zoomOut', isOverflow: true }"></ng-container>
<ng-container *ngTemplateOutlet="actionBtn; context: { id: 'fullscreen', isOverflow: true }"></ng-container>
<button class="overflow-item" [disabled]="isClosingReader()" (click)="onCloseReaderClick($event); closeToolbarOverflow()">
<app-reader-icon name="close" [size]="18" />
<span>{{ 'readerPdf.toolbar.closePdfReader' | transloco }}</span>
</button>
</div>
}
@@ -329,10 +134,7 @@
@if (isSearchOpen()) {
<div class="search-bar" [class.chrome-hidden]="!headerVisible()">
<div class="search-input-wrapper">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="11" cy="11" r="8" /><path d="m21 21-4.3-4.3" />
</svg>
<app-reader-icon name="search" [size]="14" />
<input type="text" class="search-input" #searchInput
[ngModel]="searchQuery()" (ngModelChange)="onSearchQueryChange($event)"
[attr.aria-label]="'readerPdf.toolbar.searchPlaceholder' | transloco"
@@ -340,10 +142,10 @@
(keyup.enter)="onSearchNext()"
(keyup.escape)="closeSearch()" />
</div>
<button class="icon-btn search-nav-btn" [title]="'readerPdf.toolbar.searchPrevious' | transloco" (click)="onSearchPrevious()">
<button class="icon-btn search-nav-btn" [title]="'readerPdf.toolbar.searchPrevious' | transloco" [attr.aria-label]="'readerPdf.toolbar.searchPrevious' | transloco" (click)="onSearchPrevious()">
<app-reader-icon name="chevron-left" [size]="14" />
</button>
<button class="icon-btn search-nav-btn" [title]="'readerPdf.toolbar.searchNext' | transloco" (click)="onSearchNext()">
<button class="icon-btn search-nav-btn" [title]="'readerPdf.toolbar.searchNext' | transloco" [attr.aria-label]="'readerPdf.toolbar.searchNext' | transloco" (click)="onSearchNext()">
<app-reader-icon name="chevron-right" [size]="14" />
</button>
<button class="icon-btn search-close" [attr.aria-label]="'readerPdf.toolbar.closeSearch' | transloco" (click)="closeSearch()">
@@ -353,7 +155,7 @@
}
<!-- Book viewer container -->
<div #bookViewerContainer id="book-viewer" class="book-viewer-container"></div>
<div #bookViewerContainer id="book-viewer" class="book-viewer-container" [class.horizontal-scroll]="scrollLayout() === 'horizontal'"></div>
<!-- Sidebar -->
<app-pdf-sidebar
@@ -373,11 +175,11 @@
<div class="pdf-footer" [class.visible]="footerVisible()">
<div class="page-nav-left">
<button class="nav-btn" (click)="goToFirstPage()" [disabled]="page() <= 1"
[title]="'readerPdf.footer.firstPage' | transloco">
[title]="'readerPdf.footer.firstPage' | transloco" [attr.aria-label]="'readerPdf.footer.firstPage' | transloco">
<app-reader-icon name="chevron-first" [size]="16" />
</button>
<button class="nav-btn" (click)="goToPreviousPage()" [disabled]="page() <= 1"
[title]="'readerPdf.footer.previousPage' | transloco">
[title]="'readerPdf.footer.previousPage' | transloco" [attr.aria-label]="'readerPdf.footer.previousPage' | transloco">
<app-reader-icon name="chevron-left" [size]="16" />
</button>
<div class="page-info">
@@ -385,11 +187,11 @@
<span class="total"> {{ 'readerPdf.footer.of' | transloco }} {{ totalPages() }}</span>
</div>
<button class="nav-btn" (click)="goToNextPage()" [disabled]="page() >= totalPages()"
[title]="'readerPdf.footer.nextPage' | transloco">
[title]="'readerPdf.footer.nextPage' | transloco" [attr.aria-label]="'readerPdf.footer.nextPage' | transloco">
<app-reader-icon name="chevron-right" [size]="16" />
</button>
<button class="nav-btn" (click)="goToLastPage()" [disabled]="page() >= totalPages()"
[title]="'readerPdf.footer.lastPage' | transloco">
[title]="'readerPdf.footer.lastPage' | transloco" [attr.aria-label]="'readerPdf.footer.lastPage' | transloco">
<app-reader-icon name="chevron-last" [size]="16" />
</button>
</div>
@@ -431,3 +233,176 @@
</div>
}
<!-- Action Button Template -->
<ng-template #actionBtn let-id="id" let-isOverflow="isOverflow" let-iconSize="iconSize">
@let size = iconSize || 18;
@switch (id) {
@case ('sidebar') {
<ng-container *ngTemplateOutlet="btnBase; context: {
id: 'sidebar',
icon: 'sidebar',
title: 'readerPdf.toolbar.sidebar',
active: sidebarOpen(),
isOverflow: isOverflow,
size: size
}"></ng-container>
}
@case ('search') {
<ng-container *ngTemplateOutlet="btnBase; context: {
id: 'search',
icon: 'search',
title: 'readerPdf.toolbar.search',
active: isSearchOpen(),
pressed: isSearchOpen(),
isOverflow: isOverflow,
size: size
}"></ng-container>
}
@case ('highlight') {
<ng-container *ngTemplateOutlet="btnBase; context: {
id: 'highlight',
icon: 'highlight',
title: 'readerPdf.toolbar.highlight',
active: activeAnnotationTool() === 'highlight',
pressed: activeAnnotationTool() === 'highlight',
isOverflow: isOverflow,
size: size
}"></ng-container>
}
@case ('freeText') {
<ng-container *ngTemplateOutlet="btnBase; context: {
id: 'freeText',
icon: 'free-text',
title: 'readerPdf.toolbar.freeText',
active: activeAnnotationTool() === 'freeText',
pressed: activeAnnotationTool() === 'freeText',
isOverflow: isOverflow,
size: size
}"></ng-container>
}
@case ('ink') {
<ng-container *ngTemplateOutlet="btnBase; context: {
id: 'ink',
icon: 'draw',
title: 'readerPdf.toolbar.draw',
active: activeAnnotationTool() === 'ink',
pressed: activeAnnotationTool() === 'ink',
isOverflow: isOverflow,
size: size
}"></ng-container>
}
@case ('pan') {
<ng-container *ngTemplateOutlet="btnBase; context: {
id: 'pan',
icon: 'pan',
title: 'readerPdf.toolbar.pan',
active: isPanActive(),
pressed: isPanActive(),
isOverflow: isOverflow,
size: size
}"></ng-container>
}
@case ('bookmark') {
<ng-container *ngTemplateOutlet="btnBase; context: {
id: 'bookmark',
icon: 'bookmark',
title: isCurrentPageBookmarked() ? 'readerPdf.toolbar.removeBookmark' : 'readerPdf.toolbar.addBookmark',
active: isCurrentPageBookmarked(),
pressed: isCurrentPageBookmarked(),
className: 'bookmark-btn',
isOverflow: isOverflow,
size: size
}"></ng-container>
}
@case ('zoomOut') {
<ng-container *ngTemplateOutlet="btnBase; context: {
id: 'zoomOut',
icon: 'zoom-out',
title: 'readerPdf.toolbar.zoomOut',
isOverflow: isOverflow,
size: size
}"></ng-container>
}
@case ('zoomIn') {
<ng-container *ngTemplateOutlet="btnBase; context: {
id: 'zoomIn',
icon: 'zoom-in',
title: 'readerPdf.toolbar.zoomIn',
isOverflow: isOverflow,
size: size
}"></ng-container>
}
@case ('spreadMode') {
<ng-container *ngTemplateOutlet="btnBase; context: {
id: 'spreadMode',
icon: spreadMode() === 'none' ? 'spread-none' : 'spread-double',
title: 'readerPdf.toolbar.spreadMode',
isOverflow: isOverflow,
size: size
}"></ng-container>
}
@case ('scrollLayout') {
<ng-container *ngTemplateOutlet="btnBase; context: {
id: 'scrollLayout',
icon: scrollLayout() === 'horizontal' ? 'scroll-horizontal' : 'scroll-vertical',
title: scrollLayout() === 'horizontal' ? 'readerPdf.toolbar.scrollLayoutHorizontal' : 'readerPdf.toolbar.scrollLayoutVertical',
pressed: scrollLayout() === 'horizontal',
isOverflow: isOverflow,
size: size
}"></ng-container>
}
@case ('rotate') {
<ng-container *ngTemplateOutlet="btnBase; context: {
id: 'rotate',
icon: 'rotate',
title: 'readerPdf.toolbar.rotatePage',
isOverflow: isOverflow,
size: size
}"></ng-container>
}
@case ('theme') {
<ng-container *ngTemplateOutlet="btnBase; context: {
id: 'theme',
icon: isDarkTheme() ? 'sun' : 'moon',
title: isDarkTheme() ? 'readerPdf.toolbar.switchToLightMode' : 'readerPdf.toolbar.switchToDarkMode',
pressed: isDarkTheme(),
isOverflow: isOverflow,
size: size
}"></ng-container>
}
@case ('fullscreen') {
<ng-container *ngTemplateOutlet="btnBase; context: {
id: 'fullscreen',
icon: isFullscreen() ? 'fullscreen-exit' : 'fullscreen',
title: isFullscreen() ? 'readerPdf.toolbar.exitFullscreen' : 'readerPdf.toolbar.fullscreen',
isOverflow: isOverflow,
size: size
}"></ng-container>
}
@case ('overflow') {
<ng-container *ngTemplateOutlet="btnBase; context: {
id: 'overflow',
icon: 'dots-horizontal',
title: 'readerPdf.toolbar.moreOptions',
className: 'overflow-btn',
size: size
}"></ng-container>
}
}
</ng-template>
<ng-template #btnBase let-id="id" let-icon="icon" let-title="title" let-active="active" let-pressed="pressed" let-className="className" let-isOverflow="isOverflow" let-size="size">
@if (isOverflow) {
<button class="overflow-item" [class.active]="active" (click)="performAction(id); closeToolbarOverflow()">
<app-reader-icon [name]="icon" [size]="18" />
<span>{{ title | transloco }}</span>
</button>
} @else {
<button class="icon-btn" [class]="className" [class.active]="active" [class.bookmarked]="icon === 'bookmark' && active"
[title]="title | transloco" [attr.aria-label]="title | transloco"
[attr.aria-pressed]="pressed" (click)="performAction(id)">
<app-reader-icon [name]="icon" [size]="size" />
</button>
}
</ng-template>
@@ -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;
}
@@ -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,
@@ -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<ScrollCapability, 'onLayoutReady' | 'setScrollStrategy'> {
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<PageChangeEvent>();
annotationEvent$ = new Subject<AnnotationEvent>();
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<string, unknown> | 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;
@@ -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([]);
});
});
@@ -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<AnnotationTransferItem[]>((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);
}
@@ -49,5 +49,30 @@
</p>
</div>
</div>
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<span class="setting-label">{{ t('scrollLayout') }}</span>
<div class="button-group">
@for (layout of scrollLayouts; track layout) {
<button
type="button"
class="option-button"
[class.selected]="selectedScrollLayout === layout.key"
(click)="selectedScrollLayout = layout.key"
[pTooltip]="t(layout.translationKey)"
tooltipPosition="bottom">
<i [class]="layout.icon"></i>
<span class="option-text">{{ t(layout.translationKey) }}</span>
</button>
}
</div>
</div>
<p class="setting-description">
{{ t('scrollLayoutDesc') }}
</p>
</div>
</div>
</div>
</ng-container>
@@ -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);
}
}
@@ -131,6 +131,7 @@ export interface PdfReaderSetting {
pageSpread: PageSpread;
pageZoom: string;
showSidebar: boolean;
scrollLayout?: 'vertical' | 'horizontal';
}
export enum PdfPageViewMode {
+87 -24
View File
@@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body { height: 100%; overflow: hidden; }
@@ -14,6 +14,17 @@
<div id="viewer"></div>
<script>
(function () {
const isSmallViewport = window.innerWidth <= 768;
const currentDpr = window.devicePixelRatio || 1;
const targetDpr = isSmallViewport ? 2 : Math.max(currentDpr, 2.5);
if (currentDpr !== targetDpr) {
Object.defineProperty(window, 'devicePixelRatio', {
get: () => targetDpr,
configurable: true,
});
}
const OrigWorker = window.Worker;
window.Worker = function PatchedWorker(url, opts) {
console.log('[Shim] Worker created, url type=' + typeof url +
@@ -113,6 +124,8 @@
}, myOrigin);
}
function injectGrimmoryStyles(targetEl, attempt) {
if (attempt === undefined) attempt = 0;
const container = targetEl.querySelector('embedpdf-container');
@@ -121,7 +134,9 @@
if (attempt < 25) setTimeout(() => injectGrimmoryStyles(targetEl, attempt + 1), 200);
return;
}
if (shadow.querySelector('style[data-grimmory]')) return;
if (shadow.querySelector('style[data-grimmory]')) {
return;
}
const style = document.createElement('style');
style.setAttribute('data-grimmory', '');
@@ -152,7 +167,7 @@
border-bottom-color: #404040 !important;
box-shadow: 0 2px 8px rgba(0,0,0,0.30) !important;
height: 38px !important;
padding-right: 88px !important;
padding-right: 64px !important;
padding-top: 0 !important;
padding-bottom: 0 !important;
box-sizing: border-box !important;
@@ -164,23 +179,7 @@
box-shadow: 0 2px 8px rgba(0,0,0,0.10) !important;
}
[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. */
[data-epdf-i="open-document"],
[data-epdf-i="close-document"],
@@ -269,11 +268,29 @@
border: 1px solid #d0d0d0 !important;
}
/* 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;
-webkit-font-smoothing: antialiased;
}
/* ── 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;
}
/* ── Silence non-editable selection menus EXCEPT for navigation links ── */
/* If the menu has no user-editing tools OR navigation, hide the whole menu. */
@@ -297,7 +314,10 @@
}
window.addEventListener('message', async (event) => {
if (event.origin !== myOrigin) return;
if (event.source !== parent) return;
const msg = event.data;
if (!msg || typeof msg.type !== 'string') return;
if (msg.type === 'init') {
log('Init requested');
@@ -306,6 +326,7 @@
viewer.destroy();
viewer = null;
}
const isSmallViewport = window.innerWidth <= 768;
viewer = EmbedPDF.init({
type: 'container',
@@ -325,8 +346,10 @@
zoom: {
defaultZoomLevel: 'fit-page',
},
render: { defaultImageQuality: 2 },
tiling: { tileSize: 1024, overlapPx: 2, extraRings: 1 },
render: { defaultImageQuality: isSmallViewport ? 0.85 : 0.92 },
tiling: isSmallViewport
? { tileSize: 640, overlapPx: 2, extraRings: 1 }
: { tileSize: 1024, overlapPx: 2, extraRings: 1 },
});
injectGrimmoryStyles(target);
@@ -337,8 +360,9 @@
const dm = registry.getPlugin('document-manager')?.provides();
if (dm) {
dm.onDocumentOpened?.((ev) => {
log('Document opened, pages:', ev?.pageCount);
parent.postMessage({ type: 'documentOpened', pageCount: ev?.pageCount }, myOrigin);
const pageCount = ev?.document?.pageCount ?? ev?.pageCount;
log('Document opened, pages:', pageCount);
parent.postMessage({ type: 'documentOpened', pageCount }, myOrigin);
});
dm.onDocumentError?.((ev) => {
log('Document error:', ev);
@@ -448,6 +472,45 @@
const scrollPlugin = registry?.getPlugin('scroll')?.provides();
scrollPlugin?.scrollToPreviousPage('smooth');
}
if (msg.type === 'setScrollLayout') {
const scrollPlugin = registry?.getPlugin('scroll')?.provides();
if (scrollPlugin) {
const page = scrollPlugin.getCurrentPage();
if (typeof scrollPlugin.setScrollStrategy === 'function') {
scrollPlugin.setScrollStrategy(msg.layout);
} else if (typeof scrollPlugin.setScrollMode === 'function') {
scrollPlugin.setScrollMode(msg.layout);
} else if (typeof scrollPlugin.setLayoutMode === 'function') {
scrollPlugin.setLayoutMode(msg.layout);
}
let handled = false;
const restorePage = () => {
if (handled) return;
handled = true;
scrollPlugin.scrollToPage({ pageNumber: page, behavior: 'instant' });
};
if (typeof scrollPlugin.onLayoutReady === 'function') {
scrollPlugin.onLayoutReady(() => {
restorePage();
});
}
setTimeout(restorePage, 100);
}
}
if (msg.type === 'setPanMode') {
const panPlugin = registry?.getPlugin('pan')?.provides();
if (panPlugin) {
if (msg.enable) {
panPlugin.enablePan();
} else {
panPlugin.disablePan();
}
}
}
});
log('Frame loaded, waiting for init');
+4
View File
@@ -12,7 +12,11 @@
"searchPrevious": "Previous Result",
"zoomIn": "Zoom In",
"zoomOut": "Zoom Out",
"zoomPreset": "Zoom preset",
"spreadMode": "Page Layout",
"scrollLayout": "Scroll Layout",
"scrollLayoutVertical": "Vertical Scroll",
"scrollLayoutHorizontal": "Horizontal Scroll",
"rotatePage": "Rotate Page",
"bookmarkAdd": "Add Bookmark",
"bookmarkRemove": "Remove Bookmark",
@@ -61,6 +61,10 @@
"pageSpreadDesc": "Choose how PDF pages are displayed - single page or double page spread view.",
"pageZoom": "Page Zoom",
"pageZoomDesc": "Set the default zoom level for PDF documents to enhance readability.",
"scrollLayout": "Scroll Layout",
"scrollLayoutDesc": "Choose between vertical (continuous) or horizontal (page-by-page) scrolling.",
"vertical": "Vertical",
"horizontal": "Horizontal",
"even": "Even",
"odd": "Odd",
"none": "None",