fix(pdf-viewer): convert component properties to signals for improved reactivity (#475)

* fix(pdf-viewer): convert component properties to signals for improved reactivity

* fix(pdf-viewer): improve image quality and improve rendering stability
This commit is contained in:
brios
2026-04-22 17:27:12 -04:00
committed by Zach Yale
parent cefa3ac434
commit 846a4b29dd
4 changed files with 368 additions and 321 deletions
@@ -1,29 +1,29 @@
@if (isLoading) { @if (isLoading()) {
<div class="loading-container"> <div class="loading-container">
<p-progressSpinner></p-progressSpinner> <p-progressSpinner></p-progressSpinner>
</div> </div>
} }
@if (!isLoading) { @if (!isLoading()) {
<div class="pdf-reader-container" [class.dark]="isDarkTheme"> <div class="pdf-reader-container" [class.dark]="isDarkTheme()">
<!-- Footer trigger zone --> <!-- Footer trigger zone -->
<div class="footer-trigger-zone" [class.inactive]="footerVisible" (mouseenter)="onFooterTriggerZoneEnter()"></div> <div class="footer-trigger-zone" [class.inactive]="footerVisible()" (mouseenter)="onFooterTriggerZoneEnter()"></div>
@if (viewerMode === 'book') { @if (viewerMode() === 'book') {
<!-- Header trigger zone --> <!-- Header trigger zone -->
<div class="header-trigger-zone" [class.inactive]="headerVisible" (mouseenter)="onHeaderTriggerZoneEnter()"></div> <div class="header-trigger-zone" [class.inactive]="headerVisible()" (mouseenter)="onHeaderTriggerZoneEnter()"></div>
} }
@if (viewerMode === 'document') { @if (viewerMode() === 'document') {
@if (docViewerReady) { @if (docViewerReady()) {
<button class="embed-close-btn icon-btn" [title]="'readerPdf.toolbar.closePdfReader' | transloco" <button class="embed-close-btn icon-btn" [title]="'readerPdf.toolbar.closePdfReader' | transloco"
(click)="closeReader()"> (click)="closeReader()">
<app-reader-icon name="close" [size]="18" /> <app-reader-icon name="close" [size]="18" />
</button> </button>
} }
@if (isDocViewerInfoVisible) { @if (isDocViewerInfoVisible()) {
<div class="doc-viewer-info"> <div class="doc-viewer-info">
<span>{{ 'readerPdf.docViewer.changesSavedInfo' | transloco }}</span> <span>{{ 'readerPdf.docViewer.changesSavedInfo' | transloco }}</span>
<button class="dismiss-btn" [attr.aria-label]="'readerPdf.docViewer.dismiss' | transloco" (click)="dismissDocViewerInfo()"> <button class="dismiss-btn" [attr.aria-label]="'readerPdf.docViewer.dismiss' | transloco" (click)="dismissDocViewerInfo()">
@@ -36,10 +36,10 @@
} }
<!-- Book Viewer (direct EmbedPDF) --> <!-- Book Viewer (direct EmbedPDF) -->
@if (viewerMode === 'book') { @if (viewerMode() === 'book') {
<!-- Book header toolbar --> <!-- Book header toolbar -->
<div class="pdf-header-toolbar" [class.chrome-hidden]="!headerVisible"> <div class="pdf-header-toolbar" [class.chrome-hidden]="!headerVisible()">
<div class="header-left"> <div class="header-left">
<button class="icon-btn" [title]="'readerPdf.toolbar.sidebar' | transloco" (click)="toggleSidebar()"> <button class="icon-btn" [title]="'readerPdf.toolbar.sidebar' | transloco" (click)="toggleSidebar()">
<!-- sidebar/menu icon --> <!-- sidebar/menu icon -->
@@ -50,13 +50,13 @@
</button> </button>
</div> </div>
<span class="book-title">{{ bookTitle }}</span> <span class="book-title">{{ bookTitle() }}</span>
<div class="header-right"> <div class="header-right">
<!-- Desktop toolbar actions (hidden on mobile) --> <!-- Desktop toolbar actions (hidden on mobile) -->
<div class="desktop-actions"> <div class="desktop-actions">
<!-- Search --> <!-- Search -->
<button class="icon-btn" [class.active]="isSearchOpen" <button class="icon-btn" [class.active]="isSearchOpen()"
[title]="'readerPdf.toolbar.search' | transloco" (click)="toggleSearch()"> [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" <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"> stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
@@ -67,28 +67,28 @@
<div class="separator"></div> <div class="separator"></div>
<!-- Annotation tools --> <!-- Annotation tools -->
<button class="icon-btn annotation-tool-btn" [class.active]="activeAnnotationTool === 'highlight'" <button class="icon-btn annotation-tool-btn" [class.active]="activeAnnotationTool() === 'highlight'"
[title]="'readerPdf.toolbar.highlight' | transloco" (click)="toggleAnnotationTool('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" <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"> 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" /> <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> </svg>
</button> </button>
<button class="icon-btn annotation-tool-btn" [class.active]="activeAnnotationTool === 'freeText'" <button class="icon-btn annotation-tool-btn" [class.active]="activeAnnotationTool() === 'freeText'"
[title]="'readerPdf.toolbar.freeText' | transloco" (click)="toggleAnnotationTool('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" <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"> 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" /> <path d="M17 6.1H3" /><path d="M21 12.1H3" /><path d="M15.1 18H3" />
</svg> </svg>
</button> </button>
<button class="icon-btn annotation-tool-btn" [class.active]="activeAnnotationTool === 'ink'" <button class="icon-btn annotation-tool-btn" [class.active]="activeAnnotationTool() === 'ink'"
[title]="'readerPdf.toolbar.draw' | transloco" (click)="toggleAnnotationTool('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" <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"> 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" /> <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> </svg>
</button> </button>
<button class="icon-btn annotation-tool-btn" [class.active]="isPanActive" <button class="icon-btn annotation-tool-btn" [class.active]="isPanActive()"
[title]="'readerPdf.toolbar.pan' | transloco" (click)="togglePanMode()"> [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" <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"> stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
@@ -101,10 +101,10 @@
<div class="separator"></div> <div class="separator"></div>
<!-- Bookmark toggle --> <!-- Bookmark toggle -->
<button class="icon-btn bookmark-btn" [class.bookmarked]="isCurrentPageBookmarked" <button class="icon-btn bookmark-btn" [class.bookmarked]="isCurrentPageBookmarked()"
[title]="isCurrentPageBookmarked ? ('readerPdf.toolbar.removeBookmark' | transloco) : ('readerPdf.toolbar.addBookmark' | transloco)" [title]="isCurrentPageBookmarked() ? ('readerPdf.toolbar.removeBookmark' | transloco) : ('readerPdf.toolbar.addBookmark' | transloco)"
(click)="toggleBookmark()"> (click)="toggleBookmark()">
@if (isCurrentPageBookmarked) { @if (isCurrentPageBookmarked()) {
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" <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"> 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" /> <path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z" />
@@ -128,12 +128,12 @@
</button> </button>
<div class="zoom-menu-wrapper"> <div class="zoom-menu-wrapper">
<button class="icon-btn zoom-label-btn" (click)="toggleZoomMenu()"> <button class="icon-btn zoom-label-btn" (click)="toggleZoomMenu()">
<span class="zoom-label">{{ zoom }}</span> <span class="zoom-label">{{ zoom() }}</span>
</button> </button>
@if (isZoomMenuOpen) { @if (isZoomMenuOpen()) {
<div class="zoom-dropdown"> <div class="zoom-dropdown">
@for (preset of zoomPresets; track preset.value) { @for (preset of zoomPresets; track preset.value) {
<button class="zoom-option" [class.active]="zoom === preset.value" (click)="setZoomPreset(preset.value)"> <button class="zoom-option" [class.active]="zoom() === preset.value" (click)="setZoomPreset(preset.value)">
{{ preset.label }} {{ preset.label }}
</button> </button>
} }
@@ -153,7 +153,7 @@
<button class="icon-btn" [title]="'readerPdf.toolbar.spreadMode' | transloco" (click)="cycleSpreadMode()"> <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" <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"> stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
@if (spreadMode === 'none') { @if (spreadMode() === 'none') {
<rect x="3" y="3" width="18" height="18" rx="2" /> <rect x="3" y="3" width="18" height="18" rx="2" />
} @else { } @else {
<rect x="2" y="3" width="9" height="18" rx="1" /><rect x="13" y="3" width="9" height="18" rx="1" /> <rect x="2" y="3" width="9" height="18" rx="1" /><rect x="13" y="3" width="9" height="18" rx="1" />
@@ -173,9 +173,9 @@
<!-- Theme toggle --> <!-- Theme toggle -->
<button class="icon-btn" <button class="icon-btn"
[title]="isDarkTheme ? ('readerPdf.toolbar.switchToLightMode' | transloco) : ('readerPdf.toolbar.switchToDarkMode' | transloco)" [title]="isDarkTheme() ? ('readerPdf.toolbar.switchToLightMode' | transloco) : ('readerPdf.toolbar.switchToDarkMode' | transloco)"
(click)="toggleDarkTheme()"> (click)="toggleDarkTheme()">
@if (isDarkTheme) { @if (isDarkTheme()) {
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" <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"> stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="4" /> <circle cx="12" cy="12" r="4" />
@@ -194,8 +194,8 @@
<!-- Fullscreen --> <!-- Fullscreen -->
<button class="icon-btn" (click)="toggleFullscreen()" <button class="icon-btn" (click)="toggleFullscreen()"
[title]="isFullscreen ? ('readerPdf.toolbar.exitFullscreen' | transloco) : ('readerPdf.toolbar.fullscreen' | transloco)"> [title]="isFullscreen() ? ('readerPdf.toolbar.exitFullscreen' | transloco) : ('readerPdf.toolbar.fullscreen' | transloco)">
@if (isFullscreen) { @if (isFullscreen()) {
<app-reader-icon name="fullscreen-exit" [size]="18" /> <app-reader-icon name="fullscreen-exit" [size]="18" />
} @else { } @else {
<app-reader-icon name="fullscreen" [size]="18" /> <app-reader-icon name="fullscreen" [size]="18" />
@@ -207,10 +207,10 @@
<!-- Mobile: bookmark + overflow menu (shown on mobile only) --> <!-- Mobile: bookmark + overflow menu (shown on mobile only) -->
<div class="mobile-actions"> <div class="mobile-actions">
<button class="icon-btn bookmark-btn" [class.bookmarked]="isCurrentPageBookmarked" <button class="icon-btn bookmark-btn" [class.bookmarked]="isCurrentPageBookmarked()"
[attr.aria-label]="isCurrentPageBookmarked ? ('readerPdf.toolbar.removeBookmark' | transloco) : ('readerPdf.toolbar.addBookmark' | transloco)" [attr.aria-label]="isCurrentPageBookmarked() ? ('readerPdf.toolbar.removeBookmark' | transloco) : ('readerPdf.toolbar.addBookmark' | transloco)"
(click)="toggleBookmark()"> (click)="toggleBookmark()">
@if (isCurrentPageBookmarked) { @if (isCurrentPageBookmarked()) {
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" <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"> 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" /> <path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z" />
@@ -241,7 +241,7 @@
</div> </div>
<!-- Mobile overflow menu --> <!-- Mobile overflow menu -->
@if (isToolbarOverflowOpen) { @if (isToolbarOverflowOpen()) {
<div class="toolbar-overflow-backdrop" role="presentation" (click)="closeToolbarOverflow()"></div> <div class="toolbar-overflow-backdrop" role="presentation" (click)="closeToolbarOverflow()"></div>
<div class="toolbar-overflow-menu" tabindex="-1" (keydown.escape)="closeToolbarOverflow()" #overflowMenu> <div class="toolbar-overflow-menu" tabindex="-1" (keydown.escape)="closeToolbarOverflow()" #overflowMenu>
<button class="overflow-item" (click)="toggleSearch(); closeToolbarOverflow()"> <button class="overflow-item" (click)="toggleSearch(); closeToolbarOverflow()">
@@ -265,7 +265,7 @@
</svg> </svg>
<span>{{ 'readerPdf.toolbar.draw' | transloco }}</span> <span>{{ 'readerPdf.toolbar.draw' | transloco }}</span>
</button> </button>
<button class="overflow-item" [class.active]="isPanActive" (click)="togglePanMode(); closeToolbarOverflow()"> <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" <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"> 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="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" />
@@ -276,7 +276,7 @@
</button> </button>
<div class="overflow-divider"></div> <div class="overflow-divider"></div>
<button class="overflow-item" (click)="toggleDarkTheme(); closeToolbarOverflow()"> <button class="overflow-item" (click)="toggleDarkTheme(); closeToolbarOverflow()">
@if (isDarkTheme) { @if (isDarkTheme()) {
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" <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"> stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="4" /> <circle cx="12" cy="12" r="4" />
@@ -291,7 +291,7 @@
<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" /> <path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" />
</svg> </svg>
} }
<span>{{ isDarkTheme ? ('readerPdf.toolbar.switchToLightMode' | transloco) : ('readerPdf.toolbar.switchToDarkMode' | transloco) }}</span> <span>{{ isDarkTheme() ? ('readerPdf.toolbar.switchToLightMode' | transloco) : ('readerPdf.toolbar.switchToDarkMode' | transloco) }}</span>
</button> </button>
<button class="overflow-item" (click)="rotateClockwise(); closeToolbarOverflow()"> <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" <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
@@ -315,28 +315,28 @@
<span>{{ 'readerPdf.toolbar.zoomOut' | transloco }}</span> <span>{{ 'readerPdf.toolbar.zoomOut' | transloco }}</span>
</button> </button>
<button class="overflow-item" (click)="toggleFullscreen(); closeToolbarOverflow()"> <button class="overflow-item" (click)="toggleFullscreen(); closeToolbarOverflow()">
@if (isFullscreen) { @if (isFullscreen()) {
<app-reader-icon name="fullscreen-exit" [size]="18" /> <app-reader-icon name="fullscreen-exit" [size]="18" />
} @else { } @else {
<app-reader-icon name="fullscreen" [size]="18" /> <app-reader-icon name="fullscreen" [size]="18" />
} }
<span>{{ isFullscreen ? ('readerPdf.toolbar.exitFullscreen' | transloco) : ('readerPdf.toolbar.fullscreen' | transloco) }}</span> <span>{{ isFullscreen() ? ('readerPdf.toolbar.exitFullscreen' | transloco) : ('readerPdf.toolbar.fullscreen' | transloco) }}</span>
</button> </button>
</div> </div>
} }
<!-- Search bar (slides below header) --> <!-- Search bar (slides below header) -->
@if (isSearchOpen) { @if (isSearchOpen()) {
<div class="search-bar" [class.chrome-hidden]="!headerVisible"> <div class="search-bar" [class.chrome-hidden]="!headerVisible()">
<div class="search-input-wrapper"> <div class="search-input-wrapper">
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" <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"> 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" /> <circle cx="11" cy="11" r="8" /><path d="m21 21-4.3-4.3" />
</svg> </svg>
<input type="text" class="search-input" #searchInput [(ngModel)]="searchQuery" <input type="text" class="search-input" #searchInput
[ngModel]="searchQuery()" (ngModelChange)="onSearchQueryChange($event)"
[attr.aria-label]="'readerPdf.toolbar.searchPlaceholder' | transloco" [attr.aria-label]="'readerPdf.toolbar.searchPlaceholder' | transloco"
[placeholder]="'readerPdf.toolbar.searchPlaceholder' | transloco" [placeholder]="'readerPdf.toolbar.searchPlaceholder' | transloco"
(input)="onSearchInput()"
(keyup.enter)="onSearchNext()" (keyup.enter)="onSearchNext()"
(keyup.escape)="closeSearch()" /> (keyup.escape)="closeSearch()" />
</div> </div>
@@ -353,14 +353,14 @@
} }
<!-- Book viewer container --> <!-- Book viewer container -->
<div id="book-viewer" class="book-viewer-container"></div> <div #bookViewerContainer id="book-viewer" class="book-viewer-container"></div>
<!-- Sidebar --> <!-- Sidebar -->
<app-pdf-sidebar <app-pdf-sidebar
[isOpen]="sidebarOpen" [isOpen]="sidebarOpen()"
[outline]="outline" [outline]="outline()"
[bookmarks]="pdfBookmarks" [bookmarks]="pdfBookmarks()"
[annotations]="annotationListItems" [annotations]="annotationListItems()"
(closed)="onSidebarClosed()" (closed)="onSidebarClosed()"
(navigateToPage)="onSidebarNavigateToPage($event)" (navigateToPage)="onSidebarNavigateToPage($event)"
(deleteBookmark)="onDeleteBookmark($event)" (deleteBookmark)="onDeleteBookmark($event)"
@@ -370,25 +370,25 @@
} }
<!-- Footer (shared across both viewer modes) --> <!-- Footer (shared across both viewer modes) -->
<div class="pdf-footer" [class.visible]="footerVisible"> <div class="pdf-footer" [class.visible]="footerVisible()">
<div class="page-nav-left"> <div class="page-nav-left">
<button class="nav-btn" (click)="goToFirstPage()" [disabled]="page <= 1" <button class="nav-btn" (click)="goToFirstPage()" [disabled]="page() <= 1"
[title]="'readerPdf.footer.firstPage' | transloco"> [title]="'readerPdf.footer.firstPage' | transloco">
<app-reader-icon name="chevron-first" [size]="16" /> <app-reader-icon name="chevron-first" [size]="16" />
</button> </button>
<button class="nav-btn" (click)="goToPreviousPage()" [disabled]="page <= 1" <button class="nav-btn" (click)="goToPreviousPage()" [disabled]="page() <= 1"
[title]="'readerPdf.footer.previousPage' | transloco"> [title]="'readerPdf.footer.previousPage' | transloco">
<app-reader-icon name="chevron-left" [size]="16" /> <app-reader-icon name="chevron-left" [size]="16" />
</button> </button>
<div class="page-info"> <div class="page-info">
<span class="current">{{ page }}</span> <span class="current">{{ page() }}</span>
<span class="total"> {{ 'readerPdf.footer.of' | transloco }} {{ totalPages }}</span> <span class="total"> {{ 'readerPdf.footer.of' | transloco }} {{ totalPages() }}</span>
</div> </div>
<button class="nav-btn" (click)="goToNextPage()" [disabled]="page >= totalPages" <button class="nav-btn" (click)="goToNextPage()" [disabled]="page() >= totalPages()"
[title]="'readerPdf.footer.nextPage' | transloco"> [title]="'readerPdf.footer.nextPage' | transloco">
<app-reader-icon name="chevron-right" [size]="16" /> <app-reader-icon name="chevron-right" [size]="16" />
</button> </button>
<button class="nav-btn" (click)="goToLastPage()" [disabled]="page >= totalPages" <button class="nav-btn" (click)="goToLastPage()" [disabled]="page() >= totalPages()"
[title]="'readerPdf.footer.lastPage' | transloco"> [title]="'readerPdf.footer.lastPage' | transloco">
<app-reader-icon name="chevron-last" [size]="16" /> <app-reader-icon name="chevron-last" [size]="16" />
</button> </button>
@@ -396,21 +396,22 @@
<div class="page-controls"> <div class="page-controls">
<div class="slider-wrapper"> <div class="slider-wrapper">
<input type="range" class="page-slider" [min]="1" [max]="totalPages" [value]="page" <input type="range" class="page-slider" [min]="1" [max]="totalPages()" [value]="page()"
(input)="onSliderChange($event)" list="pdf-page-ticks" [title]="'readerPdf.footer.pageSlider' | transloco" /> (input)="onSliderChange($event)" list="pdf-page-ticks" [title]="'readerPdf.footer.pageSlider' | transloco" />
<datalist id="pdf-page-ticks"> <datalist id="pdf-page-ticks">
@for (tick of sliderTicks; track tick) { @for (tick of sliderTicks(); track tick) {
<option [value]="tick"></option> <option [value]="tick"></option>
} }
</datalist> </datalist>
</div> </div>
<div class="goto-page"> <div class="goto-page">
<input type="number" [(ngModel)]="goToPageInput" [min]="1" [max]="totalPages" <input type="number" [ngModel]="goToPageInput()" (ngModelChange)="goToPageInput.set($event)"
[min]="1" [max]="totalPages()"
[placeholder]="'readerPdf.footer.pagePlaceholder' | transloco" class="page-input" [placeholder]="'readerPdf.footer.pagePlaceholder' | transloco" class="page-input"
(keyup.enter)="onGoToPage()" /> (keyup.enter)="onGoToPage()" />
<button class="go-btn" (click)="onGoToPage()" <button class="go-btn" (click)="onGoToPage()"
[disabled]="goToPageInput === null || goToPageInput < 1 || goToPageInput > totalPages"> [disabled]="goToPageInput() === null || goToPageInput()! < 1 || goToPageInput()! > totalPages()">
{{ 'readerPdf.footer.go' | transloco }} {{ 'readerPdf.footer.go' | transloco }}
</button> </button>
</div> </div>
@@ -419,10 +420,10 @@
<div class="footer-spacer"></div> <div class="footer-spacer"></div>
<div class="viewer-mode-toggle"> <div class="viewer-mode-toggle">
<button class="toggle-btn toggle-book" [class.active]="viewerMode === 'book'" (click)="setViewerMode('book')"> <button class="toggle-btn toggle-book" [class.active]="viewerMode() === 'book'" (click)="setViewerMode('book')">
<i class="pi pi-book"></i><span>{{ 'readerPdf.footer.bookViewer' | transloco }}</span> <i class="pi pi-book"></i><span>{{ 'readerPdf.footer.bookViewer' | transloco }}</span>
</button> </button>
<button class="toggle-btn toggle-doc" [class.active]="viewerMode === 'document'" (click)="setViewerMode('document')"> <button class="toggle-btn toggle-doc" [class.active]="viewerMode() === 'document'" (click)="setViewerMode('document')">
<i class="pi pi-file"></i><span>{{ 'readerPdf.footer.docViewer' | transloco }}</span> <i class="pi pi-file"></i><span>{{ 'readerPdf.footer.docViewer' | transloco }}</span>
</button> </button>
</div> </div>
@@ -77,6 +77,7 @@ $transition-fast: 150ms ease;
height: $header-height; height: $header-height;
box-sizing: border-box; box-sizing: border-box;
padding: 0 16px; padding: 0 16px;
padding-top: env(safe-area-inset-top);
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
@@ -298,6 +299,7 @@ $transition-fast: 150ms ease;
right: 0; right: 0;
height: $footer-height; height: $footer-height;
padding: 0 16px; padding: 0 16px;
padding-bottom: env(safe-area-inset-bottom);
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
@@ -751,8 +753,9 @@ $transition-fast: 150ms ease;
// Tablet (portrait) switches to mobile toolbar layout // Tablet (portrait) switches to mobile toolbar layout
@media (width <= 1024px) { @media (width <= 1024px) {
.pdf-header-toolbar { .pdf-header-toolbar {
height: $header-height + 4px; height: calc(#{$header-height} + 4px + env(safe-area-inset-top));
padding: 0 8px; padding: 0 8px;
padding-top: env(safe-area-inset-top);
} }
.desktop-actions { .desktop-actions {
@@ -766,6 +769,7 @@ $transition-fast: 150ms ease;
.pdf-footer { .pdf-footer {
height: auto; height: auto;
padding: 8px 12px; padding: 8px 12px;
padding-bottom: calc(8px + env(safe-area-inset-bottom));
flex-wrap: wrap; flex-wrap: wrap;
gap: 8px; gap: 8px;
} }
@@ -795,6 +799,8 @@ $transition-fast: 150ms ease;
} }
.search-bar { .search-bar {
top: calc(#{$header-height} + 4px + env(safe-area-inset-top));
.search-input-wrapper { .search-input-wrapper {
max-width: none; max-width: none;
} }
@@ -819,57 +825,97 @@ $transition-fast: 150ms ease;
.footer-trigger-zone { .footer-trigger-zone {
height: 50px; height: 50px;
} }
.toolbar-overflow-menu {
top: calc(#{$header-height} + 4px + env(safe-area-inset-top));
right: 4px;
left: 4px;
min-width: unset;
.overflow-item {
padding: 12px 16px;
font-size: 15px;
min-height: 44px;
}
}
.slider-wrapper {
.page-slider {
&::-webkit-slider-thumb {
width: 24px;
height: 24px;
margin-top: calc((6px - 24px) / 2);
}
&::-moz-range-thumb {
width: 24px;
height: 24px;
}
}
}
} }
// Small phones // Small phones
@media (width <= 480px) { @media (width <= 480px) {
.pdf-header-toolbar { .pdf-header-toolbar {
padding: 0 6px; padding: 0 6px;
padding-top: env(safe-area-inset-top);
} }
.pdf-footer { .pdf-footer {
padding: 6px 8px; padding: 6px 8px;
padding-bottom: calc(6px + env(safe-area-inset-bottom));
gap: 6px;
} }
.page-nav-left { .page-nav-left {
gap: 4px; gap: 2px;
} }
.nav-btn { .nav-btn {
padding: 8px; padding: 8px;
min-width: 36px; min-width: 40px;
min-height: 36px; min-height: 40px;
} }
.page-info { .page-info {
min-width: 70px; min-width: 60px;
font-size: 12px; font-size: 12px;
padding: 4px 8px; padding: 4px 6px;
} }
.slider-wrapper { .slider-wrapper {
.page-slider { .page-slider {
&::-webkit-slider-thumb { &::-webkit-slider-thumb {
width: 22px; width: 28px;
height: 22px; height: 28px;
margin-top: calc((6px - 22px) / 2); margin-top: calc((6px - 28px) / 2);
} }
&::-moz-range-thumb { &::-moz-range-thumb {
width: 22px; width: 28px;
height: 22px; height: 28px;
} }
} }
} }
.viewer-mode-toggle .toggle-btn { .viewer-mode-toggle .toggle-btn {
padding: 0 8px; padding: 0 8px;
height: 34px; height: 36px;
min-width: 36px;
} }
.icon-btn { .icon-btn {
padding: 8px; padding: 8px;
min-width: 36px; min-width: 40px;
min-height: 36px; min-height: 40px;
}
.page-controls {
// Give slider full width on small screens
.slider-wrapper {
flex: 1;
min-width: 0;
}
} }
} }
@@ -1,9 +1,10 @@
import { Component, ElementRef, inject, NgZone, OnDestroy, OnInit, ViewChild, afterNextRender } from '@angular/core'; import { Component, ElementRef, inject, Injector, NgZone, OnDestroy, OnInit, afterNextRender, viewChild, DestroyRef, signal, computed } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRoute, Router } from '@angular/router';
import { PageTitleService } from "../../../shared/service/page-title.service"; import { PageTitleService } from "../../../shared/service/page-title.service";
import { BookService } from '../../book/service/book.service'; import { BookService } from '../../book/service/book.service';
import { forkJoin, firstValueFrom, from, Observable, of, Subject, Subscription, takeUntil } from "rxjs"; import { forkJoin, firstValueFrom, from, Observable, of, Subject, Subscription } from "rxjs";
import { debounceTime, filter, map, switchMap } from 'rxjs/operators'; import { debounceTime, filter, map, switchMap } from 'rxjs/operators';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { BookSetting } from '../../book/model/book.model'; import { BookSetting } from '../../book/model/book.model';
import { UserService } from '../../settings/user-management/user.service'; import { UserService } from '../../settings/user-management/user.service';
import { AuthService } from '../../../shared/service/auth.service'; import { AuthService } from '../../../shared/service/auth.service';
@@ -45,23 +46,65 @@ type EmbedPdfMessage =
}) })
export class PdfReaderComponent implements OnInit, OnDestroy { export class PdfReaderComponent implements OnInit, OnDestroy {
isLoading = true; // --- Template-bound signals ---
totalPages: number = 0; readonly isLoading = signal(true);
isDarkTheme = true; readonly totalPages = signal(0);
readonly isDarkTheme = signal(true);
readonly page = signal(1);
readonly zoom = signal('fit-page');
readonly bookTitle = signal('');
readonly isFullscreen = signal(false);
readonly viewerMode = signal<'book' | 'document'>('book');
readonly docViewerReady = signal(false);
readonly isDocViewerInfoVisible = signal(false);
readonly headerVisible = signal(true);
readonly footerVisible = signal(true);
readonly sidebarOpen = signal(false);
readonly isSearchOpen = signal(false);
readonly isPanActive = signal(false);
readonly searchQuery = signal('');
readonly isToolbarOverflowOpen = signal(false);
readonly isZoomMenuOpen = signal(false);
readonly activeAnnotationTool = signal<string | null>(null);
readonly spreadMode = signal<'none' | 'odd' | 'even'>('none');
readonly goToPageInput = signal<number | null>(null);
readonly outline = signal<PdfOutlineItem[]>([]);
readonly pdfBookmarks = signal<BookMark[]>([]);
readonly annotationListItems = signal<PdfAnnotationListItem[]>([]);
readonly sliderTicks = computed(() => {
const total = this.totalPages();
if (total <= 1) return [];
const step = Math.max(1, Math.floor(total / 10));
const ticks: number[] = [];
for (let i = 1; i <= total; i += step) ticks.push(i);
if (ticks[ticks.length - 1] !== total) ticks.push(total);
return ticks;
});
readonly isCurrentPageBookmarked = computed(() => {
this.pdfBookmarks(); // re-evaluate when bookmark list changes
return this.pdfBookmarkService.isPageBookmarked(this.page());
});
// Zoom presets
readonly zoomPresets: { label: string; value: string }[] = [
{ label: 'Fit Page', value: 'fit-page' },
{ label: 'Fit Width', value: 'fit-width' },
{ label: '50%', value: '50%' },
{ label: '75%', value: '75%' },
{ label: '100%', value: '100%' },
{ label: '125%', value: '125%' },
{ label: '150%', value: '150%' },
{ label: '200%', value: '200%' },
];
// --- Internal state (not template-bound) ---
canPrint = false; canPrint = false;
page!: number;
spread!: 'none' | 'even' | 'odd';
zoom!: string;
bookData!: string; bookData!: string;
bookId!: number; bookId!: number;
bookFileId?: number; bookFileId?: number;
bookTitle = ''; private spread!: 'none' | 'even' | 'odd';
isFullscreen = false;
viewerMode: 'book' | 'document' = 'book';
isDocViewerInfoVisible = false;
docViewerReady = false;
private readonly DOC_VIEWER_DISMISSED_KEY = 'grimmory_doc_viewer_info_dismissed'; private readonly DOC_VIEWER_DISMISSED_KEY = 'grimmory_doc_viewer_info_dismissed';
// Doc mode (iframe) state // Doc mode (iframe) state
@@ -79,8 +122,6 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
private bookViewerInitialized = false; private bookViewerInitialized = false;
// Chrome auto-hide // Chrome auto-hide
headerVisible = true;
footerVisible = true;
private chromeAutoHideTimer?: ReturnType<typeof setTimeout>; private chromeAutoHideTimer?: ReturnType<typeof setTimeout>;
private readonly CHROME_HIDE_DELAY = 3000; private readonly CHROME_HIDE_DELAY = 3000;
private mouseMoveCleanup?: () => void; private mouseMoveCleanup?: () => void;
@@ -90,64 +131,26 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
private lastMouseMoveTime = 0; private lastMouseMoveTime = 0;
// Mobile touch navigation // Mobile touch navigation
isMobile = false; private isMobile = false;
isToolbarOverflowOpen = false; readonly overflowMenuRef = viewChild<ElementRef<HTMLDivElement>>('overflowMenu');
@ViewChild('overflowMenu') overflowMenuRef?: ElementRef<HTMLDivElement>; readonly bookViewerContainerRef = viewChild<ElementRef<HTMLDivElement>>('bookViewerContainer');
private touchStartX = 0; private touchStartX = 0;
private touchStartY = 0; private touchStartY = 0;
private touchStartTime = 0; private touchStartTime = 0;
private touchMoveCount = 0; private touchMoveCount = 0;
private readonly SWIPE_THRESHOLD = 50; private readonly SWIPE_THRESHOLD = 50;
private readonly TAP_ZONE_RATIO = 0.25; // left/right 25% of screen width private readonly TAP_ZONE_RATIO = 0.25;
private readonly TAP_MAX_DURATION = 300; // ms private readonly TAP_MAX_DURATION = 300;
// Sidebar
sidebarOpen = false;
outline: PdfOutlineItem[] = [];
pdfBookmarks: BookMark[] = [];
annotationListItems: PdfAnnotationListItem[] = [];
// Annotation tools // Annotation tools
activeAnnotationTool: string | null = null;
readonly annotationColors = ['#FFEB3B', '#4CAF50', '#2196F3', '#E91E63', '#9C27B0', '#FF5722']; readonly annotationColors = ['#FFEB3B', '#4CAF50', '#2196F3', '#E91E63', '#9C27B0', '#FF5722'];
activeAnnotationColor = '#FFEB3B'; activeAnnotationColor = '#FFEB3B';
// Search // Search
isSearchOpen = false; readonly searchInputRef = viewChild<ElementRef<HTMLInputElement>>('searchInput');
isPanActive = false;
searchQuery = '';
@ViewChild('searchInput') searchInputRef?: ElementRef<HTMLInputElement>;
private readonly searchQuery$ = new Subject<string>(); private readonly searchQuery$ = new Subject<string>();
private dbAnnotationIds = new Set<string>(); private dbAnnotationIds = new Set<string>();
// Zoom presets
readonly zoomPresets: { label: string; value: string }[] = [
{ label: 'Fit Page', value: 'fit-page' },
{ label: 'Fit Width', value: 'fit-width' },
{ label: '50%', value: '50%' },
{ label: '75%', value: '75%' },
{ label: '100%', value: '100%' },
{ label: '125%', value: '125%' },
{ label: '150%', value: '150%' },
{ label: '200%', value: '200%' },
];
isZoomMenuOpen = false;
// Spread mode
spreadMode: 'none' | 'odd' | 'even' = 'none';
// Footer page navigation
goToPageInput: number | null = null;
get sliderTicks(): number[] {
if (this.totalPages <= 1) return [];
const step = Math.max(1, Math.floor(this.totalPages / 10));
const ticks: number[] = [];
for (let i = 1; i <= this.totalPages; i += step) ticks.push(i);
if (ticks[ticks.length - 1] !== this.totalPages) ticks.push(this.totalPages);
return ticks;
}
private altBookType?: string; private altBookType?: string;
private appSettingsSubscription!: Subscription; private appSettingsSubscription!: Subscription;
private annotationSaveSubject = new Subject<void>(); private annotationSaveSubject = new Subject<void>();
@@ -159,7 +162,8 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
private lastAnnotationData: string | null = null; private lastAnnotationData: string | null = null;
private annotationsDirty = false; private annotationsDirty = false;
private pdfBlobUrl: string | null = null; private pdfBlobUrl: string | null = null;
private readonly destroy$ = new Subject<void>(); private readonly destroyRef = inject(DestroyRef);
private readonly injector = inject(Injector);
private bookService = inject(BookService); private bookService = inject(BookService);
private userService = inject(UserService); private userService = inject(UserService);
@@ -181,7 +185,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
ngOnInit(): void { ngOnInit(): void {
const dismissed = localStorage.getItem(this.DOC_VIEWER_DISMISSED_KEY); const dismissed = localStorage.getItem(this.DOC_VIEWER_DISMISSED_KEY);
this.isDocViewerInfoVisible = dismissed !== 'true'; this.isDocViewerInfoVisible.set(dismissed !== 'true');
this.isMobile = 'ontouchstart' in window || navigator.maxTouchPoints > 0; this.isMobile = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
setTimeout(() => this.wakeLockService.enable(), 1000); setTimeout(() => this.wakeLockService.enable(), 1000);
@@ -189,9 +193,9 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
document.addEventListener('fullscreenchange', this.onFullscreenChange); document.addEventListener('fullscreenchange', this.onFullscreenChange);
this.t.langChanges$ this.t.langChanges$
.pipe(takeUntil(this.destroy$)) .pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(lang => { .subscribe(lang => {
if (this.viewerMode === 'book') { if (this.viewerMode() === 'book') {
this.embedPdfBook.setLocale(lang); this.embedPdfBook.setLocale(lang);
} else if (this.embedPdfIframe?.contentWindow) { } else if (this.embedPdfIframe?.contentWindow) {
this.embedPdfIframe.contentWindow.postMessage({ type: 'setLocale', locale: lang }, location.origin); this.embedPdfIframe.contentWindow.postMessage({ type: 'setLocale', locale: lang }, location.origin);
@@ -213,11 +217,11 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
this.mouseMoveCleanup = () => document.removeEventListener('mousemove', mouseMoveHandler); this.mouseMoveCleanup = () => document.removeEventListener('mousemove', mouseMoveHandler);
const clickHandler = (e: MouseEvent) => { const clickHandler = (e: MouseEvent) => {
if (!this.isZoomMenuOpen) return; if (!this.isZoomMenuOpen()) return;
const wrapper = document.querySelector('.zoom-menu-wrapper'); const wrapper = document.querySelector('.zoom-menu-wrapper');
if (wrapper && !wrapper.contains(e.target as Node)) { if (wrapper && !wrapper.contains(e.target as Node)) {
this.ngZone.run(() => { this.ngZone.run(() => {
this.isZoomMenuOpen = false; this.isZoomMenuOpen.set(false);
}); });
} }
}; };
@@ -243,24 +247,23 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
this.ngZone.run(() => { this.ngZone.run(() => {
if (!this.isSearchOpen) { if (!this.isSearchOpen()) {
this.toggleSearch(); this.toggleSearch();
} else { } else {
// Focus search input if already open this.searchInputRef()?.nativeElement.focus();
this.searchInputRef?.nativeElement.focus();
} }
}); });
} }
if (e.key === 'Escape') { if (e.key === 'Escape') {
if (this.isSearchOpen) { if (this.isSearchOpen()) {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
this.ngZone.run(() => this.closeSearch()); this.ngZone.run(() => this.closeSearch());
} else if (this.sidebarOpen) { } else if (this.sidebarOpen()) {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
this.ngZone.run(() => this.sidebarOpen = false); this.ngZone.run(() => this.sidebarOpen.set(false));
} }
} }
}; };
@@ -294,9 +297,9 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// Debounced search // Debounced search
this.searchQuery$.pipe( this.searchQuery$.pipe(
takeUntil(this.destroy$), takeUntilDestroyed(this.destroyRef),
debounceTime(400), debounceTime(400),
filter(() => this.isSearchOpen) filter(() => this.isSearchOpen())
).subscribe(query => { ).subscribe(query => {
if (query.length > 1) { if (query.length > 1) {
this.embedPdfBook.searchAllPages(query); this.embedPdfBook.searchAllPages(query);
@@ -310,9 +313,9 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
.subscribe(() => this.cacheAnnotationData()); .subscribe(() => this.cacheAnnotationData());
this.route.paramMap.pipe( this.route.paramMap.pipe(
takeUntil(this.destroy$), takeUntilDestroyed(this.destroyRef),
switchMap((params) => { switchMap((params) => {
this.isLoading = true; this.isLoading.set(true);
this.bookId = +params.get('bookId')!; this.bookId = +params.get('bookId')!;
this.altBookType = this.route.snapshot.queryParamMap.get('bookType') ?? undefined; this.altBookType = this.route.snapshot.queryParamMap.get('bookType') ?? undefined;
@@ -343,68 +346,51 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
const pdfPrefs = bookSetting; const pdfPrefs = bookSetting;
this.pageTitle.setBookPageTitle(pdfMeta); this.pageTitle.setBookPageTitle(pdfMeta);
this.bookTitle = pdfMeta.metadata?.title || ''; this.bookTitle.set(pdfMeta.metadata?.title || '');
const globalOrIndividual = myself.userSettings.perBookSetting.pdf; const globalOrIndividual = myself.userSettings.perBookSetting.pdf;
let zoomVal: string;
let spreadVal: 'none' | 'even' | 'odd';
if (globalOrIndividual === 'Global') { if (globalOrIndividual === 'Global') {
this.zoom = myself.userSettings.pdfReaderSetting.pageZoom || 'page-fit'; zoomVal = myself.userSettings.pdfReaderSetting.pageZoom || 'page-fit';
this.spread = (myself.userSettings.pdfReaderSetting.pageSpread || 'none') === 'off' ? 'none' : (myself.userSettings.pdfReaderSetting.pageSpread as 'none' | 'even' | 'odd') || 'none'; spreadVal = (myself.userSettings.pdfReaderSetting.pageSpread || 'none') === 'off' ? 'none' : (myself.userSettings.pdfReaderSetting.pageSpread as 'none' | 'even' | 'odd') || 'none';
} else { } else {
this.zoom = pdfPrefs.pdfSettings?.zoom || myself.userSettings.pdfReaderSetting.pageZoom || 'page-fit'; zoomVal = pdfPrefs.pdfSettings?.zoom || myself.userSettings.pdfReaderSetting.pageZoom || 'page-fit';
const rawSpread = pdfPrefs.pdfSettings?.spread || myself.userSettings.pdfReaderSetting.pageSpread || 'none'; const rawSpread = pdfPrefs.pdfSettings?.spread || myself.userSettings.pdfReaderSetting.pageSpread || 'none';
this.spread = rawSpread === 'off' ? 'none' : rawSpread as 'none' | 'even' | 'odd'; spreadVal = rawSpread === 'off' ? 'none' : rawSpread as 'none' | 'even' | 'odd';
this.isDarkTheme = pdfPrefs.pdfSettings?.isDarkTheme ?? true; this.isDarkTheme.set(pdfPrefs.pdfSettings?.isDarkTheme ?? true);
} }
this.spreadMode = this.spread; this.spread = spreadVal;
this.spreadMode.set(spreadVal);
this.canPrint = myself.permissions.canDownload || myself.permissions.admin; this.canPrint = myself.permissions.canDownload || myself.permissions.admin;
this.page = pdfMeta.pdfProgress?.page || 1; this.page.set(pdfMeta.pdfProgress?.page || 1);
this.zoom = this.normalizeZoom(this.zoom); this.zoom.set(this.normalizeZoom(zoomVal));
this.bookData = bookData; this.bookData = bookData;
this.isLoading = false; this.isLoading.set(false);
// Initialize book viewer after loading completes // Schedule viewer initialization after the template renders the container
this.ngZone.runOutsideAngular(() => this.ensureViewerElementAndInitialize()); afterNextRender(() => {
this.ngZone.runOutsideAngular(() => this.initBookViewer());
}, { injector: this.injector });
}, },
error: () => { error: () => {
this.messageService.add({ severity: 'error', summary: this.t.translate('common.error'), detail: this.t.translate('readerPdf.toast.failedToLoadBook') }); this.messageService.add({ severity: 'error', summary: this.t.translate('common.error'), detail: this.t.translate('readerPdf.toast.failedToLoadBook') });
this.isLoading = false; this.isLoading.set(false);
} }
}); });
} }
dismissDocViewerInfo(): void { dismissDocViewerInfo(): void {
this.isDocViewerInfoVisible = false; this.isDocViewerInfoVisible.set(false);
localStorage.setItem(this.DOC_VIEWER_DISMISSED_KEY, 'true'); localStorage.setItem(this.DOC_VIEWER_DISMISSED_KEY, 'true');
} }
// --- Book viewer (EmbedPDF direct) --- // --- Book viewer (EmbedPDF direct) ---
private async ensureViewerElementAndInitialize(attempt = 0): Promise<void> {
const targetEl = document.getElementById('book-viewer');
if (!targetEl) {
if (attempt < 20) {
setTimeout(() => this.ensureViewerElementAndInitialize(attempt + 1), 50);
} else {
console.error('[BookViewer] Failed to find #book-viewer element after 20 attempts');
this.ngZone.run(() => {
this.isLoading = false;
this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
detail: this.t.translate('readerPdf.toast.failedToLoadBook')
});
});
}
return;
}
this.ngZone.run(() => this.initBookViewer());
}
private async initBookViewer(): Promise<void> { private async initBookViewer(): Promise<void> {
if (this.viewerMode !== 'book' || this.bookViewerInitialized || this.isInitializingBookViewer) return; if (this.viewerMode() !== 'book' || this.bookViewerInitialized || this.isInitializingBookViewer) return;
const targetEl = document.getElementById('book-viewer'); const targetEl = this.bookViewerContainerRef()?.nativeElement;
if (!targetEl) return; if (!targetEl) return;
this.isInitializingBookViewer = true; this.isInitializingBookViewer = true;
@@ -430,14 +416,14 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
} }
// Check if we were aborted or navigated away during the fetch // Check if we were aborted or navigated away during the fetch
if (this.pdfFetchAbortController.signal.aborted || currentBookId !== this.bookId || this.viewerMode !== 'book') { if (this.pdfFetchAbortController.signal.aborted || currentBookId !== this.bookId || this.viewerMode() !== 'book') {
return; return;
} }
await this.embedPdfBook.init( await this.embedPdfBook.init(
targetEl, targetEl,
pdfUrl, pdfUrl,
this.isDarkTheme ? 'dark' : 'light', this.isDarkTheme() ? 'dark' : 'light',
this.t.getActiveLang() this.t.getActiveLang()
); );
this.bookViewerInitialized = true; this.bookViewerInitialized = true;
@@ -447,18 +433,18 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// Subscribe to page changes (outside zone, debounced) // Subscribe to page changes (outside zone, debounced)
this.embedPdfBook.pageChange$.pipe( this.embedPdfBook.pageChange$.pipe(
takeUntil(this.destroy$), takeUntilDestroyed(this.destroyRef),
debounceTime(100) debounceTime(100)
).subscribe(ev => { ).subscribe(ev => {
this.ngZone.run(() => { this.ngZone.run(() => {
this.onPageChange(ev.pageNumber); this.onPageChange(ev.pageNumber);
this.totalPages = ev.totalPages; this.totalPages.set(ev.totalPages);
}); });
}); });
// Subscribe to annotation events for debounced save // Subscribe to annotation events for debounced save
this.embedPdfBook.annotationEvent$.pipe( this.embedPdfBook.annotationEvent$.pipe(
takeUntil(this.destroy$) takeUntilDestroyed(this.destroyRef)
).subscribe((ev) => { ).subscribe((ev) => {
this.ngZone.run(() => { this.ngZone.run(() => {
if (this.annotationsLoaded && !this.isImportingAnnotations) { if (this.annotationsLoaded && !this.isImportingAnnotations) {
@@ -489,37 +475,41 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// Subscribe to document opened // Subscribe to document opened
this.embedPdfBook.documentOpened$.pipe( this.embedPdfBook.documentOpened$.pipe(
takeUntil(this.destroy$) takeUntilDestroyed(this.destroyRef)
).subscribe(ev => { ).subscribe(ev => {
this.totalPages = ev.pageCount; this.totalPages.set(ev.pageCount);
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0; const currentPage = this.page();
this.readingSessionService.startSession(this.bookId, "PDF", this.page.toString(), percentage); const percentage = ev.pageCount > 0 ? Math.round((currentPage / ev.pageCount) * 1000) / 10 : 0;
this.readingSessionService.updateProgress(this.page.toString(), percentage); this.readingSessionService.startSession(this.bookId, "PDF", currentPage.toString(), percentage);
this.readingSessionService.updateProgress(currentPage.toString(), percentage);
// Apply saved zoom level // Apply saved zoom level
if (this.zoom && this.zoom !== 'fit-page') { const currentZoom = this.zoom();
this.embedPdfBook.setZoomLevel(this.zoom); if (currentZoom && currentZoom !== 'fit-page') {
this.embedPdfBook.setZoomLevel(currentZoom);
} }
// Apply saved spread mode // Apply saved spread mode
if (this.spread && this.spread !== 'none') { if (this.spread && this.spread !== 'none') {
this.embedPdfBook.setSpreadMode(this.spread); this.embedPdfBook.setSpreadMode(this.spread);
this.spreadMode = this.spread; this.spreadMode.set(this.spread);
} }
// Load outline, bookmarks, and annotations
this.loadOutline();
this.loadBookmarks();
this.loadAnnotations();
}); });
// Use onLayoutReady for initial page scroll (fires when document layout is calculated) // Use onLayoutReady for initial page scroll (fires when document layout is calculated)
this.embedPdfBook.layoutReady$.pipe( this.embedPdfBook.layoutReady$.pipe(
takeUntil(this.destroy$) takeUntilDestroyed(this.destroyRef),
debounceTime(200) // Give the engine a moment to settle and start high-quality rendering
).subscribe(() => { ).subscribe(() => {
if (this.page > 1) { const currentPage = this.page();
this.embedPdfBook.scrollToPage(this.page, 'instant'); if (currentPage > 1) {
this.embedPdfBook.scrollToPage(currentPage, 'instant');
} }
// Load outline, bookmarks, and annotations after layout is ready and settled
this.loadOutline();
this.loadBookmarks();
this.loadAnnotations();
}); });
} catch (err) { } catch (err) {
@@ -561,12 +551,12 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
} }
private async loadOutline(): Promise<void> { private async loadOutline(): Promise<void> {
this.outline = await this.embedPdfBook.getOutline(); this.outline.set(await this.embedPdfBook.getOutline());
} }
private loadBookmarks(): void { private loadBookmarks(): void {
this.pdfBookmarkService.loadBookmarks().subscribe(bookmarks => { this.pdfBookmarkService.loadBookmarks().subscribe(bookmarks => {
this.pdfBookmarks = bookmarks; this.pdfBookmarks.set(bookmarks);
}); });
} }
@@ -578,7 +568,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
const allItems = parseStoredAnnotations(response.data); const allItems = parseStoredAnnotations(response.data);
this.dbAnnotationIds = new Set(allItems.map(i => i.annotation.id)); this.dbAnnotationIds = new Set(allItems.map(i => i.annotation.id));
// Deduplicate items based on animation ID to heal previous corruption // Deduplicate items based on annotation ID to heal previous corruption
const seenIds = new Set<string>(); const seenIds = new Set<string>();
const items = allItems.filter(item => { const items = allItems.filter(item => {
if (seenIds.has(item.annotation.id)) return false; if (seenIds.has(item.annotation.id)) return false;
@@ -627,11 +617,11 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
} }
private async refreshAnnotationList(): Promise<void> { private async refreshAnnotationList(): Promise<void> {
if (!this.annotationsLoaded || this.viewerMode === 'document') return; if (!this.annotationsLoaded || this.viewerMode() === 'document') return;
try { try {
const allItems = await this.embedPdfBook.exportAnnotations(); const allItems = await this.embedPdfBook.exportAnnotations();
const items = this.filterAndDeduplicateAnnotations(allItems); const items = this.filterAndDeduplicateAnnotations(allItems);
this.annotationListItems = items.map(item => { this.annotationListItems.set(items.map(item => {
const ann = item.annotation as unknown as Record<string, unknown>; const ann = item.annotation as unknown as Record<string, unknown>;
return { return {
id: String(ann['id'] || ''), id: String(ann['id'] || ''),
@@ -640,9 +630,9 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
color: (ann['strokeColor'] ?? ann['color']) as string | undefined, color: (ann['strokeColor'] ?? ann['color']) as string | undefined,
text: ann['contents'] as string | undefined, text: ann['contents'] as string | undefined,
}; };
}); }));
} catch { } catch {
this.annotationListItems = []; this.annotationListItems.set([]);
} }
} }
@@ -658,23 +648,23 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// --- Annotation tools --- // --- Annotation tools ---
toggleAnnotationTool(toolId: string | null): void { toggleAnnotationTool(toolId: string | null): void {
if (this.activeAnnotationTool === toolId) { if (this.activeAnnotationTool() === toolId) {
this.activeAnnotationTool = null; this.activeAnnotationTool.set(null);
} else { } else {
this.isPanActive = false; this.isPanActive.set(false);
this.embedPdfBook.setPanMode(false); this.embedPdfBook.setPanMode(false);
this.activeAnnotationTool = toolId; this.activeAnnotationTool.set(toolId);
} }
this.embedPdfBook.setActiveTool(this.activeAnnotationTool); this.embedPdfBook.setActiveTool(this.activeAnnotationTool());
} }
togglePanMode(): void { togglePanMode(): void {
this.isPanActive = !this.isPanActive; this.isPanActive.update(v => !v);
if (this.isPanActive) { if (this.isPanActive()) {
this.activeAnnotationTool = null; this.activeAnnotationTool.set(null);
this.embedPdfBook.setActiveTool(null); this.embedPdfBook.setActiveTool(null);
} }
this.embedPdfBook.setPanMode(this.isPanActive); this.embedPdfBook.setPanMode(this.isPanActive());
} }
setAnnotationColor(color: string): void { setAnnotationColor(color: string): void {
@@ -684,27 +674,27 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// --- Search --- // --- Search ---
toggleSearch(): void { toggleSearch(): void {
this.isSearchOpen = !this.isSearchOpen; this.isSearchOpen.update(v => !v);
if (this.isSearchOpen) { if (this.isSearchOpen()) {
afterNextRender(() => this.searchInputRef?.nativeElement.focus()); afterNextRender(() => this.searchInputRef()?.nativeElement.focus(), { injector: this.injector });
this.embedPdfBook.startSearch(); this.embedPdfBook.startSearch();
} else { } else {
this.searchQuery = ''; this.searchQuery.set('');
this.embedPdfBook.stopSearch(); this.embedPdfBook.stopSearch();
} }
} }
closeSearch(): void { closeSearch(): void {
this.isSearchOpen = false; this.isSearchOpen.set(false);
this.searchQuery = ''; this.searchQuery.set('');
this.embedPdfBook.stopSearch(); this.embedPdfBook.stopSearch();
} }
onSearchInput(): void { onSearchQueryChange(value: string): void {
this.searchQuery$.next(this.searchQuery); this.searchQuery.set(value);
this.searchQuery$.next(value);
} }
onSearchNext(): void { onSearchNext(): void {
this.embedPdfBook.nextSearchResult(); this.embedPdfBook.nextSearchResult();
} }
@@ -716,13 +706,13 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// --- Zoom --- // --- Zoom ---
toggleZoomMenu(): void { toggleZoomMenu(): void {
this.isZoomMenuOpen = !this.isZoomMenuOpen; this.isZoomMenuOpen.update(v => !v);
} }
setZoomPreset(value: string): void { setZoomPreset(value: string): void {
this.zoom = value; this.zoom.set(value);
this.embedPdfBook.setZoomLevel(value); this.embedPdfBook.setZoomLevel(value);
this.isZoomMenuOpen = false; this.isZoomMenuOpen.set(false);
this.updateViewerSetting(); this.updateViewerSetting();
} }
@@ -730,10 +720,11 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
cycleSpreadMode(): void { cycleSpreadMode(): void {
const modes: ('none' | 'odd' | 'even')[] = ['none', 'odd', 'even']; const modes: ('none' | 'odd' | 'even')[] = ['none', 'odd', 'even'];
const idx = modes.indexOf(this.spreadMode); const idx = modes.indexOf(this.spreadMode());
this.spreadMode = modes[(idx + 1) % modes.length]; const next = modes[(idx + 1) % modes.length];
this.spread = this.spreadMode; this.spreadMode.set(next);
this.embedPdfBook.setSpreadMode(this.spreadMode); this.spread = next;
this.embedPdfBook.setSpreadMode(next);
this.updateViewerSetting(); this.updateViewerSetting();
} }
@@ -745,14 +736,10 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// --- Bookmarks --- // --- Bookmarks ---
get isCurrentPageBookmarked(): boolean {
return this.pdfBookmarkService.isPageBookmarked(this.page);
}
toggleBookmark(): void { toggleBookmark(): void {
this.pdfBookmarkService.toggleBookmark(this.page).subscribe(success => { this.pdfBookmarkService.toggleBookmark(this.page()).subscribe(success => {
if (success) { if (success) {
this.pdfBookmarks = this.pdfBookmarkService.getAllBookmarks(); this.pdfBookmarks.set(this.pdfBookmarkService.getAllBookmarks());
} }
}); });
} }
@@ -760,16 +747,17 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
onDeleteBookmark(bookmarkId: number): void { onDeleteBookmark(bookmarkId: number): void {
this.pdfBookmarkService.deleteBookmark(bookmarkId).subscribe(success => { this.pdfBookmarkService.deleteBookmark(bookmarkId).subscribe(success => {
if (success) { if (success) {
this.pdfBookmarks = this.pdfBookmarkService.getAllBookmarks(); this.pdfBookmarks.set(this.pdfBookmarkService.getAllBookmarks());
} }
}); });
} }
onDeleteAnnotation(annotationId: string): void { onDeleteAnnotation(annotationId: string): void {
const item = this.annotationListItems.find(a => a.id === annotationId); const items = this.annotationListItems();
const item = items.find(a => a.id === annotationId);
if (item) { if (item) {
this.embedPdfBook.deleteAnnotation(item.pageIndex, annotationId); this.embedPdfBook.deleteAnnotation(item.pageIndex, annotationId);
this.annotationListItems = this.annotationListItems.filter(a => a.id !== annotationId); this.annotationListItems.set(items.filter(a => a.id !== annotationId));
this.annotationSaveSubject.next(); this.annotationSaveSubject.next();
} }
} }
@@ -777,16 +765,16 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// --- Sidebar --- // --- Sidebar ---
toggleSidebar(): void { toggleSidebar(): void {
this.sidebarOpen = !this.sidebarOpen; this.sidebarOpen.update(v => !v);
} }
onSidebarClosed(): void { onSidebarClosed(): void {
this.sidebarOpen = false; this.sidebarOpen.set(false);
} }
onSidebarNavigateToPage(pageNumber: number): void { onSidebarNavigateToPage(pageNumber: number): void {
this.sidebarOpen = false; this.sidebarOpen.set(false);
if (this.viewerMode === 'book') { if (this.viewerMode() === 'book') {
this.embedPdfBook.scrollToPage(pageNumber); this.embedPdfBook.scrollToPage(pageNumber);
} }
this.onPageChange(pageNumber); this.onPageChange(pageNumber);
@@ -795,9 +783,9 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// --- Viewer mode switching --- // --- Viewer mode switching ---
async setViewerMode(mode: 'book' | 'document') { async setViewerMode(mode: 'book' | 'document') {
if (mode === this.viewerMode) return; if (mode === this.viewerMode()) return;
this.docViewerReady = false; this.docViewerReady.set(false);
if (this.initTimeout) { if (this.initTimeout) {
clearTimeout(this.initTimeout); clearTimeout(this.initTimeout);
this.initTimeout = undefined; this.initTimeout = undefined;
@@ -807,7 +795,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// Save annotations before switching // Save annotations before switching
await this.persistAnnotations(); await this.persistAnnotations();
this.destroyBookViewer(); this.destroyBookViewer();
this.viewerMode = mode; this.viewerMode.set(mode);
this.initTimeout = setTimeout(() => { this.initTimeout = setTimeout(() => {
this.initTimeout = undefined; this.initTimeout = undefined;
this.initDocViewerIframe(); this.initDocViewerIframe();
@@ -817,7 +805,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
if (this.embedPdfIframe) { if (this.embedPdfIframe) {
this.saveEmbedPdfDocument().finally(() => this.destroyDocViewerIframe()); this.saveEmbedPdfDocument().finally(() => this.destroyDocViewerIframe());
} }
this.viewerMode = mode; this.viewerMode.set(mode);
this.initTimeout = setTimeout(() => { this.initTimeout = setTimeout(() => {
this.initTimeout = undefined; this.initTimeout = undefined;
this.initBookViewer(); this.initBookViewer();
@@ -843,7 +831,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
const response = await fetch(this.bookData, { headers, credentials: 'include' }); const response = await fetch(this.bookData, { headers, credentials: 'include' });
if (!response.ok) throw new Error(`PDF fetch failed: ${response.status}`); if (!response.ok) throw new Error(`PDF fetch failed: ${response.status}`);
if (this.viewerMode !== 'document') return; if (this.viewerMode() !== 'document') return;
const pdfBuffer = await response.arrayBuffer(); const pdfBuffer = await response.arrayBuffer();
const targetEl = document.getElementById('embedpdf-viewer'); const targetEl = document.getElementById('embedpdf-viewer');
@@ -872,7 +860,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
iframe.contentWindow!.postMessage({ iframe.contentWindow!.postMessage({
type: 'init', type: 'init',
wasmUrl: '/assets/pdfium/pdfium.wasm', wasmUrl: '/assets/pdfium/pdfium.wasm',
theme: this.isDarkTheme ? 'dark' : 'light', theme: this.isDarkTheme() ? 'dark' : 'light',
locale: this.t.getActiveLang() locale: this.t.getActiveLang()
}, location.origin); }, location.origin);
@@ -889,7 +877,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
private handleEmbedPdfMessage(msg: EmbedPdfMessage): void { private handleEmbedPdfMessage(msg: EmbedPdfMessage): void {
switch (msg.type) { switch (msg.type) {
case 'ready': case 'ready':
this.docViewerReady = true; this.docViewerReady.set(true);
if (this.pendingPdfBuffer && this.embedPdfIframe?.contentWindow) { if (this.pendingPdfBuffer && this.embedPdfIframe?.contentWindow) {
const buf = this.pendingPdfBuffer; const buf = this.pendingPdfBuffer;
this.pendingPdfBuffer = undefined; this.pendingPdfBuffer = undefined;
@@ -916,7 +904,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
break; break;
case 'pageChange': case 'pageChange':
this.onPageChange(msg.pageNumber); this.onPageChange(msg.pageNumber);
this.totalPages = msg.totalPages; this.totalPages.set(msg.totalPages);
break; break;
} }
} }
@@ -993,24 +981,26 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// --- Common viewer methods --- // --- Common viewer methods ---
onPageChange(page: number | undefined): void { onPageChange(page: number | undefined): void {
if (page == null || page === this.page) { if (page == null || page === this.page()) {
return; return;
} }
this.page = page; this.page.set(page);
this.updateProgress(); this.updateProgress();
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0; const total = this.totalPages();
this.readingSessionService.updateProgress(this.page.toString(), percentage); const percentage = total > 0 ? Math.round((page / total) * 1000) / 10 : 0;
this.readingSessionService.updateProgress(page.toString(), percentage);
} }
toggleDarkTheme(): void { toggleDarkTheme(): void {
this.isDarkTheme = !this.isDarkTheme; this.isDarkTheme.update(v => !v);
this.updateViewerSetting(); this.updateViewerSetting();
// Sync theme with active viewer // Sync theme with active viewer
if (this.viewerMode === 'book') { if (this.viewerMode() === 'book') {
this.embedPdfBook.setTheme(this.isDarkTheme ? 'dark' : 'light'); this.embedPdfBook.setTheme(this.isDarkTheme() ? 'dark' : 'light');
} else if (this.embedPdfIframe?.contentWindow) { } else if (this.embedPdfIframe?.contentWindow) {
this.embedPdfIframe.contentWindow.postMessage( this.embedPdfIframe.contentWindow.postMessage(
{ type: 'setTheme', theme: this.isDarkTheme ? 'dark' : 'light' }, { type: 'setTheme', theme: this.isDarkTheme() ? 'dark' : 'light' },
location.origin location.origin
); );
} }
@@ -1020,16 +1010,18 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
const bookSetting: BookSetting = { const bookSetting: BookSetting = {
pdfSettings: { pdfSettings: {
spread: this.spread, spread: this.spread,
zoom: this.zoom, zoom: this.zoom(),
isDarkTheme: this.isDarkTheme, isDarkTheme: this.isDarkTheme(),
} }
} }
this.bookService.updateViewerSetting(bookSetting, this.bookId).subscribe(); this.bookService.updateViewerSetting(bookSetting, this.bookId).subscribe();
} }
updateProgress(): void { updateProgress(): void {
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0; const currentPage = this.page();
this.bookService.savePdfProgress(this.bookId, this.page, percentage, this.bookFileId).subscribe(); 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();
} }
ngOnDestroy(): void { ngOnDestroy(): void {
@@ -1038,16 +1030,14 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
this.wakeLockService.disable(); this.wakeLockService.disable();
if (this.chromeAutoHideTimer) clearTimeout(this.chromeAutoHideTimer); if (this.chromeAutoHideTimer) clearTimeout(this.chromeAutoHideTimer);
// Tear down all subscriptions via takeUntil
this.destroy$.next();
this.destroy$.complete();
// Save progress via fetch+keepalive so it survives navigation // Save progress via fetch+keepalive so it survives navigation
this.saveProgressSync(); this.saveProgressSync();
if (this.readingSessionService.isSessionActive()) { if (this.readingSessionService.isSessionActive()) {
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0; const currentPage = this.page();
this.readingSessionService.endSession(this.page.toString(), percentage); const total = this.totalPages();
const percentage = total > 0 ? Math.round((currentPage / total) * 1000) / 10 : 0;
this.readingSessionService.endSession(currentPage.toString(), percentage);
} }
this.annotationSaveSubscription?.unsubscribe(); this.annotationSaveSubscription?.unsubscribe();
@@ -1084,13 +1074,13 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// --- Chrome auto-hide --- // --- Chrome auto-hide ---
showChrome(): void { showChrome(): void {
this.headerVisible = true; this.headerVisible.set(true);
this.footerVisible = true; this.footerVisible.set(true);
} }
hideChrome(): void { hideChrome(): void {
this.headerVisible = false; this.headerVisible.set(false);
this.footerVisible = false; this.footerVisible.set(false);
} }
private startChromeAutoHide(): void { private startChromeAutoHide(): void {
@@ -1099,19 +1089,19 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
} }
onHeaderTriggerZoneEnter(): void { onHeaderTriggerZoneEnter(): void {
this.headerVisible = true; this.headerVisible.set(true);
this.startChromeAutoHide(); this.startChromeAutoHide();
} }
onFooterTriggerZoneEnter(): void { onFooterTriggerZoneEnter(): void {
this.footerVisible = true; this.footerVisible.set(true);
this.startChromeAutoHide(); this.startChromeAutoHide();
} }
// --- Touch navigation --- // --- Touch navigation ---
private handleTouchEnd(e: TouchEvent): void { private handleTouchEnd(e: TouchEvent): void {
if (this.viewerMode !== 'book') return; if (this.viewerMode() !== 'book') return;
// Ignore touches on interactive elements // Ignore touches on interactive elements
const target = e.target instanceof Element ? e.target : (e.target as Node)?.parentElement; const target = e.target instanceof Element ? e.target : (e.target as Node)?.parentElement;
@@ -1149,7 +1139,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
this.goToNextPage(); this.goToNextPage();
} else { } else {
// Center zone: toggle chrome // Center zone: toggle chrome
if (this.headerVisible || this.footerVisible) { if (this.headerVisible() || this.footerVisible()) {
this.hideChrome(); this.hideChrome();
} else { } else {
this.showChrome(); this.showChrome();
@@ -1163,14 +1153,14 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// --- Toolbar overflow menu --- // --- Toolbar overflow menu ---
toggleToolbarOverflow(): void { toggleToolbarOverflow(): void {
this.isToolbarOverflowOpen = !this.isToolbarOverflowOpen; this.isToolbarOverflowOpen.update(v => !v);
if (this.isToolbarOverflowOpen) { if (this.isToolbarOverflowOpen()) {
afterNextRender(() => this.overflowMenuRef?.nativeElement.focus()); afterNextRender(() => this.overflowMenuRef()?.nativeElement.focus(), { injector: this.injector });
} }
} }
closeToolbarOverflow(): void { closeToolbarOverflow(): void {
this.isToolbarOverflowOpen = false; this.isToolbarOverflowOpen.set(false);
} }
// --- Fullscreen --- // --- Fullscreen ---
@@ -1184,13 +1174,13 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
} }
private onFullscreenChange = (): void => { private onFullscreenChange = (): void => {
this.isFullscreen = !!document.fullscreenElement; this.isFullscreen.set(!!document.fullscreenElement);
}; };
// --- Footer page navigation --- // --- Footer page navigation ---
goToFirstPage(): void { goToFirstPage(): void {
if (this.viewerMode === 'book') { if (this.viewerMode() === 'book') {
this.embedPdfBook.scrollToPage(1); this.embedPdfBook.scrollToPage(1);
} else if (this.embedPdfIframe?.contentWindow) { } else if (this.embedPdfIframe?.contentWindow) {
this.embedPdfIframe.contentWindow.postMessage({ type: 'scrollToPage', pageNumber: 1 }, location.origin); this.embedPdfIframe.contentWindow.postMessage({ type: 'scrollToPage', pageNumber: 1 }, location.origin);
@@ -1199,9 +1189,10 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
} }
goToPreviousPage(): void { goToPreviousPage(): void {
if (this.page > 1) { const currentPage = this.page();
const p = this.page - 1; if (currentPage > 1) {
if (this.viewerMode === 'book') { const p = currentPage - 1;
if (this.viewerMode() === 'book') {
this.embedPdfBook.scrollToPreviousPage(); this.embedPdfBook.scrollToPreviousPage();
} else if (this.embedPdfIframe?.contentWindow) { } else if (this.embedPdfIframe?.contentWindow) {
this.embedPdfIframe.contentWindow.postMessage({ type: 'prevPage' }, location.origin); this.embedPdfIframe.contentWindow.postMessage({ type: 'prevPage' }, location.origin);
@@ -1211,9 +1202,11 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
} }
goToNextPage(): void { goToNextPage(): void {
if (this.page < this.totalPages) { const currentPage = this.page();
const p = this.page + 1; const total = this.totalPages();
if (this.viewerMode === 'book') { if (currentPage < total) {
const p = currentPage + 1;
if (this.viewerMode() === 'book') {
this.embedPdfBook.scrollToNextPage(); this.embedPdfBook.scrollToNextPage();
} else if (this.embedPdfIframe?.contentWindow) { } else if (this.embedPdfIframe?.contentWindow) {
this.embedPdfIframe.contentWindow.postMessage({ type: 'nextPage' }, location.origin); this.embedPdfIframe.contentWindow.postMessage({ type: 'nextPage' }, location.origin);
@@ -1223,17 +1216,18 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
} }
goToLastPage(): void { goToLastPage(): void {
if (this.viewerMode === 'book') { const total = this.totalPages();
this.embedPdfBook.scrollToPage(this.totalPages); if (this.viewerMode() === 'book') {
this.embedPdfBook.scrollToPage(total);
} else if (this.embedPdfIframe?.contentWindow) { } else if (this.embedPdfIframe?.contentWindow) {
this.embedPdfIframe.contentWindow.postMessage({ type: 'scrollToPage', pageNumber: this.totalPages }, location.origin); this.embedPdfIframe.contentWindow.postMessage({ type: 'scrollToPage', pageNumber: total }, location.origin);
} }
this.onPageChange(this.totalPages); this.onPageChange(total);
} }
onSliderChange(event: Event): void { onSliderChange(event: Event): void {
const value = +(event.target as HTMLInputElement).value; const value = +(event.target as HTMLInputElement).value;
if (this.viewerMode === 'book') { if (this.viewerMode() === 'book') {
this.embedPdfBook.scrollToPage(value, 'instant'); this.embedPdfBook.scrollToPage(value, 'instant');
} else if (this.embedPdfIframe?.contentWindow) { } else if (this.embedPdfIframe?.contentWindow) {
this.embedPdfIframe.contentWindow.postMessage({ type: 'scrollToPage', pageNumber: value }, location.origin); this.embedPdfIframe.contentWindow.postMessage({ type: 'scrollToPage', pageNumber: value }, location.origin);
@@ -1242,20 +1236,22 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
} }
onGoToPage(): void { onGoToPage(): void {
if (this.goToPageInput && this.goToPageInput >= 1 && this.goToPageInput <= this.totalPages) { const input = this.goToPageInput();
if (this.viewerMode === 'book') { const total = this.totalPages();
this.embedPdfBook.scrollToPage(this.goToPageInput); if (input && input >= 1 && input <= total) {
if (this.viewerMode() === 'book') {
this.embedPdfBook.scrollToPage(input);
} else if (this.embedPdfIframe?.contentWindow) { } else if (this.embedPdfIframe?.contentWindow) {
this.embedPdfIframe.contentWindow.postMessage({ type: 'scrollToPage', pageNumber: this.goToPageInput }, location.origin); this.embedPdfIframe.contentWindow.postMessage({ type: 'scrollToPage', pageNumber: input }, location.origin);
} }
this.onPageChange(this.goToPageInput); this.onPageChange(input);
this.goToPageInput = null; this.goToPageInput.set(null);
} }
} }
closeReader = async (): Promise<void> => { closeReader = async (): Promise<void> => {
try { try {
if (this.viewerMode === 'document' && this.embedPdfIframe) { if (this.viewerMode() === 'document' && this.embedPdfIframe) {
await this.saveEmbedPdfDocument(); await this.saveEmbedPdfDocument();
await this.destroyDocViewerIframe(); await this.destroyDocViewerIframe();
} else { } else {
@@ -1265,8 +1261,10 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
console.error('[PDF Reader] Error saving on close:', e); console.error('[PDF Reader] Error saving on close:', e);
} }
if (this.readingSessionService.isSessionActive()) { if (this.readingSessionService.isSessionActive()) {
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0; const currentPage = this.page();
this.readingSessionService.endSession(this.page.toString(), percentage); 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 // Navigate back within the SPA; fall back to home if there's no history
if (window.history.length > 1) { if (window.history.length > 1) {
@@ -1291,7 +1289,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
} }
private async persistAnnotations(): Promise<void> { private async persistAnnotations(): Promise<void> {
if (!this.annotationsLoaded || !this.bookId || this.viewerMode === 'document') return; if (!this.annotationsLoaded || !this.bookId || this.viewerMode() === 'document') return;
try { try {
const allItems = await this.embedPdfBook.exportAnnotations(); const allItems = await this.embedPdfBook.exportAnnotations();
const items = this.filterAndDeduplicateAnnotations(allItems); const items = this.filterAndDeduplicateAnnotations(allItems);
@@ -1330,16 +1328,18 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
} }
private saveProgressSync(): void { private saveProgressSync(): void {
if (!this.bookId || !this.page) return; const currentPage = this.page();
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0; if (!this.bookId || !currentPage) return;
const total = this.totalPages();
const percentage = total > 0 ? Math.round((currentPage / total) * 1000) / 10 : 0;
const body: Record<string, unknown> = { const body: Record<string, unknown> = {
bookId: this.bookId, bookId: this.bookId,
pdfProgress: { page: this.page, percentage } pdfProgress: { page: currentPage, percentage }
}; };
if (this.bookFileId) { if (this.bookFileId) {
body['fileProgress'] = { body['fileProgress'] = {
bookFileId: this.bookFileId, bookFileId: this.bookFileId,
positionData: String(this.page), positionData: String(currentPage),
progressPercent: percentage progressPercent: percentage
}; };
} }
@@ -107,7 +107,7 @@ export class EmbedPdfBookService {
defaultZoomLevel: 'fit-page' as ZoomMode, defaultZoomLevel: 'fit-page' as ZoomMode,
}, },
render: { render: {
defaultImageQuality: 2, defaultImageQuality: 4,
}, },
tiling: { tiling: {
tileSize: 1024, tileSize: 1024,
@@ -451,7 +451,7 @@ export class EmbedPdfBookService {
* PDF pages appear noticeably pixelated. * PDF pages appear noticeably pixelated.
*/ */
private ensureHighDpiRendering(): void { private ensureHighDpiRendering(): void {
const MIN_DPR = 2; const MIN_DPR = 2.5;
if (window.devicePixelRatio < MIN_DPR) { if (window.devicePixelRatio < MIN_DPR) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any // eslint-disable-next-line @typescript-eslint/no-explicit-any
const w = window as any; const w = window as any;