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">
<p-progressSpinner></p-progressSpinner>
</div>
}
@if (!isLoading) {
<div class="pdf-reader-container" [class.dark]="isDarkTheme">
@if (!isLoading()) {
<div class="pdf-reader-container" [class.dark]="isDarkTheme()">
<!-- 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 -->
<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 (docViewerReady) {
@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) {
@if (isDocViewerInfoVisible()) {
<div class="doc-viewer-info">
<span>{{ 'readerPdf.docViewer.changesSavedInfo' | transloco }}</span>
<button class="dismiss-btn" [attr.aria-label]="'readerPdf.docViewer.dismiss' | transloco" (click)="dismissDocViewerInfo()">
@@ -36,10 +36,10 @@
}
<!-- Book Viewer (direct EmbedPDF) -->
@if (viewerMode === 'book') {
@if (viewerMode() === 'book') {
<!-- 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">
<button class="icon-btn" [title]="'readerPdf.toolbar.sidebar' | transloco" (click)="toggleSidebar()">
<!-- sidebar/menu icon -->
@@ -50,13 +50,13 @@
</button>
</div>
<span class="book-title">{{ bookTitle }}</span>
<span class="book-title">{{ bookTitle() }}</span>
<div class="header-right">
<!-- Desktop toolbar actions (hidden on mobile) -->
<div class="desktop-actions">
<!-- Search -->
<button class="icon-btn" [class.active]="isSearchOpen"
<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">
@@ -67,28 +67,28 @@
<div class="separator"></div>
<!-- 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')">
<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'"
<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'"
<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"
<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">
@@ -101,10 +101,10 @@
<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)"
<button class="icon-btn bookmark-btn" [class.bookmarked]="isCurrentPageBookmarked()"
[title]="isCurrentPageBookmarked() ? ('readerPdf.toolbar.removeBookmark' | transloco) : ('readerPdf.toolbar.addBookmark' | transloco)"
(click)="toggleBookmark()">
@if (isCurrentPageBookmarked) {
@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" />
@@ -128,12 +128,12 @@
</button>
<div class="zoom-menu-wrapper">
<button class="icon-btn zoom-label-btn" (click)="toggleZoomMenu()">
<span class="zoom-label">{{ zoom }}</span>
<span class="zoom-label">{{ zoom() }}</span>
</button>
@if (isZoomMenuOpen) {
@if (isZoomMenuOpen()) {
<div class="zoom-dropdown">
@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 }}
</button>
}
@@ -153,7 +153,7 @@
<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') {
@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" />
@@ -173,9 +173,9 @@
<!-- Theme toggle -->
<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()">
@if (isDarkTheme) {
@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" />
@@ -194,8 +194,8 @@
<!-- Fullscreen -->
<button class="icon-btn" (click)="toggleFullscreen()"
[title]="isFullscreen ? ('readerPdf.toolbar.exitFullscreen' | transloco) : ('readerPdf.toolbar.fullscreen' | transloco)">
@if (isFullscreen) {
[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" />
@@ -207,10 +207,10 @@
<!-- Mobile: bookmark + overflow menu (shown on mobile only) -->
<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)"
<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) {
@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" />
@@ -241,7 +241,7 @@
</div>
<!-- Mobile overflow menu -->
@if (isToolbarOverflowOpen) {
@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()">
@@ -265,7 +265,7 @@
</svg>
<span>{{ 'readerPdf.toolbar.draw' | transloco }}</span>
</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"
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" />
@@ -276,7 +276,7 @@
</button>
<div class="overflow-divider"></div>
<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"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<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" />
</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 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"
@@ -315,28 +315,28 @@
<span>{{ 'readerPdf.toolbar.zoomOut' | transloco }}</span>
</button>
<button class="overflow-item" (click)="toggleFullscreen(); closeToolbarOverflow()">
@if (isFullscreen) {
@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>
<span>{{ isFullscreen() ? ('readerPdf.toolbar.exitFullscreen' | transloco) : ('readerPdf.toolbar.fullscreen' | transloco) }}</span>
</button>
</div>
}
<!-- Search bar (slides below header) -->
@if (isSearchOpen) {
<div class="search-bar" [class.chrome-hidden]="!headerVisible">
@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>
<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"
[placeholder]="'readerPdf.toolbar.searchPlaceholder' | transloco"
(input)="onSearchInput()"
(keyup.enter)="onSearchNext()"
(keyup.escape)="closeSearch()" />
</div>
@@ -353,14 +353,14 @@
}
<!-- Book viewer container -->
<div id="book-viewer" class="book-viewer-container"></div>
<div #bookViewerContainer id="book-viewer" class="book-viewer-container"></div>
<!-- Sidebar -->
<app-pdf-sidebar
[isOpen]="sidebarOpen"
[outline]="outline"
[bookmarks]="pdfBookmarks"
[annotations]="annotationListItems"
[isOpen]="sidebarOpen()"
[outline]="outline()"
[bookmarks]="pdfBookmarks()"
[annotations]="annotationListItems()"
(closed)="onSidebarClosed()"
(navigateToPage)="onSidebarNavigateToPage($event)"
(deleteBookmark)="onDeleteBookmark($event)"
@@ -370,25 +370,25 @@
}
<!-- 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">
<button class="nav-btn" (click)="goToFirstPage()" [disabled]="page <= 1"
<button class="nav-btn" (click)="goToFirstPage()" [disabled]="page() <= 1"
[title]="'readerPdf.footer.firstPage' | transloco">
<app-reader-icon name="chevron-first" [size]="16" />
</button>
<button class="nav-btn" (click)="goToPreviousPage()" [disabled]="page <= 1"
<button class="nav-btn" (click)="goToPreviousPage()" [disabled]="page() <= 1"
[title]="'readerPdf.footer.previousPage' | transloco">
<app-reader-icon name="chevron-left" [size]="16" />
</button>
<div class="page-info">
<span class="current">{{ page }}</span>
<span class="total"> {{ 'readerPdf.footer.of' | transloco }} {{ totalPages }}</span>
<span class="current">{{ page() }}</span>
<span class="total"> {{ 'readerPdf.footer.of' | transloco }} {{ totalPages() }}</span>
</div>
<button class="nav-btn" (click)="goToNextPage()" [disabled]="page >= totalPages"
<button class="nav-btn" (click)="goToNextPage()" [disabled]="page() >= totalPages()"
[title]="'readerPdf.footer.nextPage' | transloco">
<app-reader-icon name="chevron-right" [size]="16" />
</button>
<button class="nav-btn" (click)="goToLastPage()" [disabled]="page >= totalPages"
<button class="nav-btn" (click)="goToLastPage()" [disabled]="page() >= totalPages()"
[title]="'readerPdf.footer.lastPage' | transloco">
<app-reader-icon name="chevron-last" [size]="16" />
</button>
@@ -396,21 +396,22 @@
<div class="page-controls">
<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" />
<datalist id="pdf-page-ticks">
@for (tick of sliderTicks; track tick) {
@for (tick of sliderTicks(); track tick) {
<option [value]="tick"></option>
}
</datalist>
</div>
<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"
(keyup.enter)="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 }}
</button>
</div>
@@ -419,10 +420,10 @@
<div class="footer-spacer"></div>
<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>
</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>
</button>
</div>
@@ -77,6 +77,7 @@ $transition-fast: 150ms ease;
height: $header-height;
box-sizing: border-box;
padding: 0 16px;
padding-top: env(safe-area-inset-top);
display: flex;
align-items: center;
justify-content: space-between;
@@ -298,6 +299,7 @@ $transition-fast: 150ms ease;
right: 0;
height: $footer-height;
padding: 0 16px;
padding-bottom: env(safe-area-inset-bottom);
display: flex;
align-items: center;
justify-content: space-between;
@@ -751,8 +753,9 @@ $transition-fast: 150ms ease;
// Tablet (portrait) switches to mobile toolbar layout
@media (width <= 1024px) {
.pdf-header-toolbar {
height: $header-height + 4px;
height: calc(#{$header-height} + 4px + env(safe-area-inset-top));
padding: 0 8px;
padding-top: env(safe-area-inset-top);
}
.desktop-actions {
@@ -766,6 +769,7 @@ $transition-fast: 150ms ease;
.pdf-footer {
height: auto;
padding: 8px 12px;
padding-bottom: calc(8px + env(safe-area-inset-bottom));
flex-wrap: wrap;
gap: 8px;
}
@@ -795,6 +799,8 @@ $transition-fast: 150ms ease;
}
.search-bar {
top: calc(#{$header-height} + 4px + env(safe-area-inset-top));
.search-input-wrapper {
max-width: none;
}
@@ -819,57 +825,97 @@ $transition-fast: 150ms ease;
.footer-trigger-zone {
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
@media (width <= 480px) {
.pdf-header-toolbar {
padding: 0 6px;
padding-top: env(safe-area-inset-top);
}
.pdf-footer {
padding: 6px 8px;
padding-bottom: calc(6px + env(safe-area-inset-bottom));
gap: 6px;
}
.page-nav-left {
gap: 4px;
gap: 2px;
}
.nav-btn {
padding: 8px;
min-width: 36px;
min-height: 36px;
min-width: 40px;
min-height: 40px;
}
.page-info {
min-width: 70px;
min-width: 60px;
font-size: 12px;
padding: 4px 8px;
padding: 4px 6px;
}
.slider-wrapper {
.page-slider {
&::-webkit-slider-thumb {
width: 22px;
height: 22px;
margin-top: calc((6px - 22px) / 2);
width: 28px;
height: 28px;
margin-top: calc((6px - 28px) / 2);
}
&::-moz-range-thumb {
width: 22px;
height: 22px;
width: 28px;
height: 28px;
}
}
}
.viewer-mode-toggle .toggle-btn {
padding: 0 8px;
height: 34px;
height: 36px;
min-width: 36px;
}
.icon-btn {
padding: 8px;
min-width: 36px;
min-height: 36px;
min-width: 40px;
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 { PageTitleService } from "../../../shared/service/page-title.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 { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { BookSetting } from '../../book/model/book.model';
import { UserService } from '../../settings/user-management/user.service';
import { AuthService } from '../../../shared/service/auth.service';
@@ -45,23 +46,65 @@ type EmbedPdfMessage =
})
export class PdfReaderComponent implements OnInit, OnDestroy {
isLoading = true;
totalPages: number = 0;
isDarkTheme = true;
// --- Template-bound signals ---
readonly isLoading = signal(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;
page!: number;
spread!: 'none' | 'even' | 'odd';
zoom!: string;
bookData!: string;
bookId!: number;
bookFileId?: number;
bookTitle = '';
isFullscreen = false;
viewerMode: 'book' | 'document' = 'book';
isDocViewerInfoVisible = false;
docViewerReady = false;
private spread!: 'none' | 'even' | 'odd';
private readonly DOC_VIEWER_DISMISSED_KEY = 'grimmory_doc_viewer_info_dismissed';
// Doc mode (iframe) state
@@ -79,8 +122,6 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
private bookViewerInitialized = false;
// Chrome auto-hide
headerVisible = true;
footerVisible = true;
private chromeAutoHideTimer?: ReturnType<typeof setTimeout>;
private readonly CHROME_HIDE_DELAY = 3000;
private mouseMoveCleanup?: () => void;
@@ -90,64 +131,26 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
private lastMouseMoveTime = 0;
// Mobile touch navigation
isMobile = false;
isToolbarOverflowOpen = false;
@ViewChild('overflowMenu') overflowMenuRef?: ElementRef<HTMLDivElement>;
private isMobile = false;
readonly overflowMenuRef = viewChild<ElementRef<HTMLDivElement>>('overflowMenu');
readonly bookViewerContainerRef = viewChild<ElementRef<HTMLDivElement>>('bookViewerContainer');
private touchStartX = 0;
private touchStartY = 0;
private touchStartTime = 0;
private touchMoveCount = 0;
private readonly SWIPE_THRESHOLD = 50;
private readonly TAP_ZONE_RATIO = 0.25; // left/right 25% of screen width
private readonly TAP_MAX_DURATION = 300; // ms
// Sidebar
sidebarOpen = false;
outline: PdfOutlineItem[] = [];
pdfBookmarks: BookMark[] = [];
annotationListItems: PdfAnnotationListItem[] = [];
private readonly TAP_ZONE_RATIO = 0.25;
private readonly TAP_MAX_DURATION = 300;
// Annotation tools
activeAnnotationTool: string | null = null;
readonly annotationColors = ['#FFEB3B', '#4CAF50', '#2196F3', '#E91E63', '#9C27B0', '#FF5722'];
activeAnnotationColor = '#FFEB3B';
// Search
isSearchOpen = false;
isPanActive = false;
searchQuery = '';
@ViewChild('searchInput') searchInputRef?: ElementRef<HTMLInputElement>;
readonly searchInputRef = viewChild<ElementRef<HTMLInputElement>>('searchInput');
private readonly searchQuery$ = new Subject<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 appSettingsSubscription!: Subscription;
private annotationSaveSubject = new Subject<void>();
@@ -159,7 +162,8 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
private lastAnnotationData: string | null = null;
private annotationsDirty = false;
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 userService = inject(UserService);
@@ -181,7 +185,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
ngOnInit(): void {
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;
setTimeout(() => this.wakeLockService.enable(), 1000);
@@ -189,9 +193,9 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
document.addEventListener('fullscreenchange', this.onFullscreenChange);
this.t.langChanges$
.pipe(takeUntil(this.destroy$))
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(lang => {
if (this.viewerMode === 'book') {
if (this.viewerMode() === 'book') {
this.embedPdfBook.setLocale(lang);
} else if (this.embedPdfIframe?.contentWindow) {
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);
const clickHandler = (e: MouseEvent) => {
if (!this.isZoomMenuOpen) return;
if (!this.isZoomMenuOpen()) return;
const wrapper = document.querySelector('.zoom-menu-wrapper');
if (wrapper && !wrapper.contains(e.target as Node)) {
this.ngZone.run(() => {
this.isZoomMenuOpen = false;
this.isZoomMenuOpen.set(false);
});
}
};
@@ -243,24 +247,23 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
e.preventDefault();
e.stopPropagation();
this.ngZone.run(() => {
if (!this.isSearchOpen) {
if (!this.isSearchOpen()) {
this.toggleSearch();
} else {
// Focus search input if already open
this.searchInputRef?.nativeElement.focus();
this.searchInputRef()?.nativeElement.focus();
}
});
}
if (e.key === 'Escape') {
if (this.isSearchOpen) {
if (this.isSearchOpen()) {
e.preventDefault();
e.stopPropagation();
this.ngZone.run(() => this.closeSearch());
} else if (this.sidebarOpen) {
} else if (this.sidebarOpen()) {
e.preventDefault();
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
this.searchQuery$.pipe(
takeUntil(this.destroy$),
takeUntilDestroyed(this.destroyRef),
debounceTime(400),
filter(() => this.isSearchOpen)
filter(() => this.isSearchOpen())
).subscribe(query => {
if (query.length > 1) {
this.embedPdfBook.searchAllPages(query);
@@ -310,9 +313,9 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
.subscribe(() => this.cacheAnnotationData());
this.route.paramMap.pipe(
takeUntil(this.destroy$),
takeUntilDestroyed(this.destroyRef),
switchMap((params) => {
this.isLoading = true;
this.isLoading.set(true);
this.bookId = +params.get('bookId')!;
this.altBookType = this.route.snapshot.queryParamMap.get('bookType') ?? undefined;
@@ -343,68 +346,51 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
const pdfPrefs = bookSetting;
this.pageTitle.setBookPageTitle(pdfMeta);
this.bookTitle = pdfMeta.metadata?.title || '';
this.bookTitle.set(pdfMeta.metadata?.title || '');
const globalOrIndividual = myself.userSettings.perBookSetting.pdf;
let zoomVal: string;
let spreadVal: 'none' | 'even' | 'odd';
if (globalOrIndividual === 'Global') {
this.zoom = myself.userSettings.pdfReaderSetting.pageZoom || 'page-fit';
this.spread = (myself.userSettings.pdfReaderSetting.pageSpread || 'none') === 'off' ? 'none' : (myself.userSettings.pdfReaderSetting.pageSpread as 'none' | 'even' | 'odd') || 'none';
zoomVal = myself.userSettings.pdfReaderSetting.pageZoom || 'page-fit';
spreadVal = (myself.userSettings.pdfReaderSetting.pageSpread || 'none') === 'off' ? 'none' : (myself.userSettings.pdfReaderSetting.pageSpread as 'none' | 'even' | 'odd') || 'none';
} 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';
this.spread = rawSpread === 'off' ? 'none' : rawSpread as 'none' | 'even' | 'odd';
this.isDarkTheme = pdfPrefs.pdfSettings?.isDarkTheme ?? true;
spreadVal = rawSpread === 'off' ? 'none' : rawSpread as 'none' | 'even' | 'odd';
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.page = pdfMeta.pdfProgress?.page || 1;
this.zoom = this.normalizeZoom(this.zoom);
this.page.set(pdfMeta.pdfProgress?.page || 1);
this.zoom.set(this.normalizeZoom(zoomVal));
this.bookData = bookData;
this.isLoading = false;
this.isLoading.set(false);
// Initialize book viewer after loading completes
this.ngZone.runOutsideAngular(() => this.ensureViewerElementAndInitialize());
// Schedule viewer initialization after the template renders the container
afterNextRender(() => {
this.ngZone.runOutsideAngular(() => this.initBookViewer());
}, { injector: this.injector });
},
error: () => {
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 {
this.isDocViewerInfoVisible = false;
this.isDocViewerInfoVisible.set(false);
localStorage.setItem(this.DOC_VIEWER_DISMISSED_KEY, 'true');
}
// --- 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> {
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;
this.isInitializingBookViewer = true;
@@ -430,14 +416,14 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
}
// 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;
}
await this.embedPdfBook.init(
targetEl,
pdfUrl,
this.isDarkTheme ? 'dark' : 'light',
this.isDarkTheme() ? 'dark' : 'light',
this.t.getActiveLang()
);
this.bookViewerInitialized = true;
@@ -447,18 +433,18 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// Subscribe to page changes (outside zone, debounced)
this.embedPdfBook.pageChange$.pipe(
takeUntil(this.destroy$),
takeUntilDestroyed(this.destroyRef),
debounceTime(100)
).subscribe(ev => {
this.ngZone.run(() => {
this.onPageChange(ev.pageNumber);
this.totalPages = ev.totalPages;
this.totalPages.set(ev.totalPages);
});
});
// Subscribe to annotation events for debounced save
this.embedPdfBook.annotationEvent$.pipe(
takeUntil(this.destroy$)
takeUntilDestroyed(this.destroyRef)
).subscribe((ev) => {
this.ngZone.run(() => {
if (this.annotationsLoaded && !this.isImportingAnnotations) {
@@ -489,37 +475,41 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// Subscribe to document opened
this.embedPdfBook.documentOpened$.pipe(
takeUntil(this.destroy$)
takeUntilDestroyed(this.destroyRef)
).subscribe(ev => {
this.totalPages = ev.pageCount;
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0;
this.readingSessionService.startSession(this.bookId, "PDF", this.page.toString(), percentage);
this.readingSessionService.updateProgress(this.page.toString(), percentage);
this.totalPages.set(ev.pageCount);
const currentPage = this.page();
const percentage = ev.pageCount > 0 ? Math.round((currentPage / ev.pageCount) * 1000) / 10 : 0;
this.readingSessionService.startSession(this.bookId, "PDF", currentPage.toString(), percentage);
this.readingSessionService.updateProgress(currentPage.toString(), percentage);
// Apply saved zoom level
if (this.zoom && this.zoom !== 'fit-page') {
this.embedPdfBook.setZoomLevel(this.zoom);
const currentZoom = this.zoom();
if (currentZoom && currentZoom !== 'fit-page') {
this.embedPdfBook.setZoomLevel(currentZoom);
}
// Apply saved spread mode
if (this.spread && this.spread !== 'none') {
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)
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(() => {
if (this.page > 1) {
this.embedPdfBook.scrollToPage(this.page, 'instant');
const currentPage = this.page();
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) {
@@ -561,12 +551,12 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
}
private async loadOutline(): Promise<void> {
this.outline = await this.embedPdfBook.getOutline();
this.outline.set(await this.embedPdfBook.getOutline());
}
private loadBookmarks(): void {
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);
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 items = allItems.filter(item => {
if (seenIds.has(item.annotation.id)) return false;
@@ -627,11 +617,11 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
}
private async refreshAnnotationList(): Promise<void> {
if (!this.annotationsLoaded || this.viewerMode === 'document') return;
if (!this.annotationsLoaded || this.viewerMode() === 'document') return;
try {
const allItems = await this.embedPdfBook.exportAnnotations();
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>;
return {
id: String(ann['id'] || ''),
@@ -640,9 +630,9 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
color: (ann['strokeColor'] ?? ann['color']) as string | undefined,
text: ann['contents'] as string | undefined,
};
});
}));
} catch {
this.annotationListItems = [];
this.annotationListItems.set([]);
}
}
@@ -658,23 +648,23 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// --- Annotation tools ---
toggleAnnotationTool(toolId: string | null): void {
if (this.activeAnnotationTool === toolId) {
this.activeAnnotationTool = null;
if (this.activeAnnotationTool() === toolId) {
this.activeAnnotationTool.set(null);
} else {
this.isPanActive = false;
this.isPanActive.set(false);
this.embedPdfBook.setPanMode(false);
this.activeAnnotationTool = toolId;
this.activeAnnotationTool.set(toolId);
}
this.embedPdfBook.setActiveTool(this.activeAnnotationTool);
this.embedPdfBook.setActiveTool(this.activeAnnotationTool());
}
togglePanMode(): void {
this.isPanActive = !this.isPanActive;
if (this.isPanActive) {
this.activeAnnotationTool = null;
this.isPanActive.update(v => !v);
if (this.isPanActive()) {
this.activeAnnotationTool.set(null);
this.embedPdfBook.setActiveTool(null);
}
this.embedPdfBook.setPanMode(this.isPanActive);
this.embedPdfBook.setPanMode(this.isPanActive());
}
setAnnotationColor(color: string): void {
@@ -684,27 +674,27 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// --- Search ---
toggleSearch(): void {
this.isSearchOpen = !this.isSearchOpen;
if (this.isSearchOpen) {
afterNextRender(() => this.searchInputRef?.nativeElement.focus());
this.isSearchOpen.update(v => !v);
if (this.isSearchOpen()) {
afterNextRender(() => this.searchInputRef()?.nativeElement.focus(), { injector: this.injector });
this.embedPdfBook.startSearch();
} else {
this.searchQuery = '';
this.searchQuery.set('');
this.embedPdfBook.stopSearch();
}
}
closeSearch(): void {
this.isSearchOpen = false;
this.searchQuery = '';
this.isSearchOpen.set(false);
this.searchQuery.set('');
this.embedPdfBook.stopSearch();
}
onSearchInput(): void {
this.searchQuery$.next(this.searchQuery);
onSearchQueryChange(value: string): void {
this.searchQuery.set(value);
this.searchQuery$.next(value);
}
onSearchNext(): void {
this.embedPdfBook.nextSearchResult();
}
@@ -716,13 +706,13 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// --- Zoom ---
toggleZoomMenu(): void {
this.isZoomMenuOpen = !this.isZoomMenuOpen;
this.isZoomMenuOpen.update(v => !v);
}
setZoomPreset(value: string): void {
this.zoom = value;
this.zoom.set(value);
this.embedPdfBook.setZoomLevel(value);
this.isZoomMenuOpen = false;
this.isZoomMenuOpen.set(false);
this.updateViewerSetting();
}
@@ -730,10 +720,11 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
cycleSpreadMode(): void {
const modes: ('none' | 'odd' | 'even')[] = ['none', 'odd', 'even'];
const idx = modes.indexOf(this.spreadMode);
this.spreadMode = modes[(idx + 1) % modes.length];
this.spread = this.spreadMode;
this.embedPdfBook.setSpreadMode(this.spreadMode);
const idx = modes.indexOf(this.spreadMode());
const next = modes[(idx + 1) % modes.length];
this.spreadMode.set(next);
this.spread = next;
this.embedPdfBook.setSpreadMode(next);
this.updateViewerSetting();
}
@@ -745,14 +736,10 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// --- Bookmarks ---
get isCurrentPageBookmarked(): boolean {
return this.pdfBookmarkService.isPageBookmarked(this.page);
}
toggleBookmark(): void {
this.pdfBookmarkService.toggleBookmark(this.page).subscribe(success => {
this.pdfBookmarkService.toggleBookmark(this.page()).subscribe(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 {
this.pdfBookmarkService.deleteBookmark(bookmarkId).subscribe(success => {
if (success) {
this.pdfBookmarks = this.pdfBookmarkService.getAllBookmarks();
this.pdfBookmarks.set(this.pdfBookmarkService.getAllBookmarks());
}
});
}
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) {
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();
}
}
@@ -777,16 +765,16 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// --- Sidebar ---
toggleSidebar(): void {
this.sidebarOpen = !this.sidebarOpen;
this.sidebarOpen.update(v => !v);
}
onSidebarClosed(): void {
this.sidebarOpen = false;
this.sidebarOpen.set(false);
}
onSidebarNavigateToPage(pageNumber: number): void {
this.sidebarOpen = false;
if (this.viewerMode === 'book') {
this.sidebarOpen.set(false);
if (this.viewerMode() === 'book') {
this.embedPdfBook.scrollToPage(pageNumber);
}
this.onPageChange(pageNumber);
@@ -795,9 +783,9 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// --- Viewer mode switching ---
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) {
clearTimeout(this.initTimeout);
this.initTimeout = undefined;
@@ -807,7 +795,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// Save annotations before switching
await this.persistAnnotations();
this.destroyBookViewer();
this.viewerMode = mode;
this.viewerMode.set(mode);
this.initTimeout = setTimeout(() => {
this.initTimeout = undefined;
this.initDocViewerIframe();
@@ -817,7 +805,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
if (this.embedPdfIframe) {
this.saveEmbedPdfDocument().finally(() => this.destroyDocViewerIframe());
}
this.viewerMode = mode;
this.viewerMode.set(mode);
this.initTimeout = setTimeout(() => {
this.initTimeout = undefined;
this.initBookViewer();
@@ -843,7 +831,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
const response = await fetch(this.bookData, { headers, credentials: 'include' });
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 targetEl = document.getElementById('embedpdf-viewer');
@@ -872,7 +860,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
iframe.contentWindow!.postMessage({
type: 'init',
wasmUrl: '/assets/pdfium/pdfium.wasm',
theme: this.isDarkTheme ? 'dark' : 'light',
theme: this.isDarkTheme() ? 'dark' : 'light',
locale: this.t.getActiveLang()
}, location.origin);
@@ -889,7 +877,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
private handleEmbedPdfMessage(msg: EmbedPdfMessage): void {
switch (msg.type) {
case 'ready':
this.docViewerReady = true;
this.docViewerReady.set(true);
if (this.pendingPdfBuffer && this.embedPdfIframe?.contentWindow) {
const buf = this.pendingPdfBuffer;
this.pendingPdfBuffer = undefined;
@@ -916,7 +904,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
break;
case 'pageChange':
this.onPageChange(msg.pageNumber);
this.totalPages = msg.totalPages;
this.totalPages.set(msg.totalPages);
break;
}
}
@@ -993,24 +981,26 @@ 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()) {
return;
}
this.page = page;
this.page.set(page);
this.updateProgress();
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0;
this.readingSessionService.updateProgress(this.page.toString(), percentage);
const total = this.totalPages();
const percentage = total > 0 ? Math.round((page / total) * 1000) / 10 : 0;
this.readingSessionService.updateProgress(page.toString(), percentage);
}
toggleDarkTheme(): void {
this.isDarkTheme = !this.isDarkTheme;
this.isDarkTheme.update(v => !v);
this.updateViewerSetting();
// Sync theme with active viewer
if (this.viewerMode === 'book') {
this.embedPdfBook.setTheme(this.isDarkTheme ? 'dark' : 'light');
if (this.viewerMode() === 'book') {
this.embedPdfBook.setTheme(this.isDarkTheme() ? 'dark' : 'light');
} else if (this.embedPdfIframe?.contentWindow) {
this.embedPdfIframe.contentWindow.postMessage(
{ type: 'setTheme', theme: this.isDarkTheme ? 'dark' : 'light' },
{ type: 'setTheme', theme: this.isDarkTheme() ? 'dark' : 'light' },
location.origin
);
}
@@ -1020,16 +1010,18 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
const bookSetting: BookSetting = {
pdfSettings: {
spread: this.spread,
zoom: this.zoom,
isDarkTheme: this.isDarkTheme,
zoom: this.zoom(),
isDarkTheme: this.isDarkTheme(),
}
}
this.bookService.updateViewerSetting(bookSetting, this.bookId).subscribe();
}
updateProgress(): void {
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0;
this.bookService.savePdfProgress(this.bookId, this.page, percentage, this.bookFileId).subscribe();
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();
}
ngOnDestroy(): void {
@@ -1038,16 +1030,14 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
this.wakeLockService.disable();
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
this.saveProgressSync();
if (this.readingSessionService.isSessionActive()) {
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0;
this.readingSessionService.endSession(this.page.toString(), percentage);
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);
}
this.annotationSaveSubscription?.unsubscribe();
@@ -1084,13 +1074,13 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// --- Chrome auto-hide ---
showChrome(): void {
this.headerVisible = true;
this.footerVisible = true;
this.headerVisible.set(true);
this.footerVisible.set(true);
}
hideChrome(): void {
this.headerVisible = false;
this.footerVisible = false;
this.headerVisible.set(false);
this.footerVisible.set(false);
}
private startChromeAutoHide(): void {
@@ -1099,19 +1089,19 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
}
onHeaderTriggerZoneEnter(): void {
this.headerVisible = true;
this.headerVisible.set(true);
this.startChromeAutoHide();
}
onFooterTriggerZoneEnter(): void {
this.footerVisible = true;
this.footerVisible.set(true);
this.startChromeAutoHide();
}
// --- Touch navigation ---
private handleTouchEnd(e: TouchEvent): void {
if (this.viewerMode !== 'book') return;
if (this.viewerMode() !== 'book') return;
// Ignore touches on interactive elements
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();
} else {
// Center zone: toggle chrome
if (this.headerVisible || this.footerVisible) {
if (this.headerVisible() || this.footerVisible()) {
this.hideChrome();
} else {
this.showChrome();
@@ -1163,14 +1153,14 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
// --- Toolbar overflow menu ---
toggleToolbarOverflow(): void {
this.isToolbarOverflowOpen = !this.isToolbarOverflowOpen;
if (this.isToolbarOverflowOpen) {
afterNextRender(() => this.overflowMenuRef?.nativeElement.focus());
this.isToolbarOverflowOpen.update(v => !v);
if (this.isToolbarOverflowOpen()) {
afterNextRender(() => this.overflowMenuRef()?.nativeElement.focus(), { injector: this.injector });
}
}
closeToolbarOverflow(): void {
this.isToolbarOverflowOpen = false;
this.isToolbarOverflowOpen.set(false);
}
// --- Fullscreen ---
@@ -1184,13 +1174,13 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
}
private onFullscreenChange = (): void => {
this.isFullscreen = !!document.fullscreenElement;
this.isFullscreen.set(!!document.fullscreenElement);
};
// --- Footer page navigation ---
goToFirstPage(): void {
if (this.viewerMode === 'book') {
if (this.viewerMode() === 'book') {
this.embedPdfBook.scrollToPage(1);
} else if (this.embedPdfIframe?.contentWindow) {
this.embedPdfIframe.contentWindow.postMessage({ type: 'scrollToPage', pageNumber: 1 }, location.origin);
@@ -1199,9 +1189,10 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
}
goToPreviousPage(): void {
if (this.page > 1) {
const p = this.page - 1;
if (this.viewerMode === 'book') {
const currentPage = this.page();
if (currentPage > 1) {
const p = currentPage - 1;
if (this.viewerMode() === 'book') {
this.embedPdfBook.scrollToPreviousPage();
} else if (this.embedPdfIframe?.contentWindow) {
this.embedPdfIframe.contentWindow.postMessage({ type: 'prevPage' }, location.origin);
@@ -1211,9 +1202,11 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
}
goToNextPage(): void {
if (this.page < this.totalPages) {
const p = this.page + 1;
if (this.viewerMode === 'book') {
const currentPage = this.page();
const total = this.totalPages();
if (currentPage < total) {
const p = currentPage + 1;
if (this.viewerMode() === 'book') {
this.embedPdfBook.scrollToNextPage();
} else if (this.embedPdfIframe?.contentWindow) {
this.embedPdfIframe.contentWindow.postMessage({ type: 'nextPage' }, location.origin);
@@ -1223,17 +1216,18 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
}
goToLastPage(): void {
if (this.viewerMode === 'book') {
this.embedPdfBook.scrollToPage(this.totalPages);
const total = this.totalPages();
if (this.viewerMode() === 'book') {
this.embedPdfBook.scrollToPage(total);
} 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 {
const value = +(event.target as HTMLInputElement).value;
if (this.viewerMode === 'book') {
if (this.viewerMode() === 'book') {
this.embedPdfBook.scrollToPage(value, 'instant');
} else if (this.embedPdfIframe?.contentWindow) {
this.embedPdfIframe.contentWindow.postMessage({ type: 'scrollToPage', pageNumber: value }, location.origin);
@@ -1242,20 +1236,22 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
}
onGoToPage(): void {
if (this.goToPageInput && this.goToPageInput >= 1 && this.goToPageInput <= this.totalPages) {
if (this.viewerMode === 'book') {
this.embedPdfBook.scrollToPage(this.goToPageInput);
const input = this.goToPageInput();
const total = this.totalPages();
if (input && input >= 1 && input <= total) {
if (this.viewerMode() === 'book') {
this.embedPdfBook.scrollToPage(input);
} 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.goToPageInput = null;
this.onPageChange(input);
this.goToPageInput.set(null);
}
}
closeReader = async (): Promise<void> => {
try {
if (this.viewerMode === 'document' && this.embedPdfIframe) {
if (this.viewerMode() === 'document' && this.embedPdfIframe) {
await this.saveEmbedPdfDocument();
await this.destroyDocViewerIframe();
} else {
@@ -1265,8 +1261,10 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
console.error('[PDF Reader] Error saving on close:', e);
}
if (this.readingSessionService.isSessionActive()) {
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0;
this.readingSessionService.endSession(this.page.toString(), percentage);
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) {
@@ -1291,7 +1289,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
}
private async persistAnnotations(): Promise<void> {
if (!this.annotationsLoaded || !this.bookId || this.viewerMode === 'document') return;
if (!this.annotationsLoaded || !this.bookId || this.viewerMode() === 'document') return;
try {
const allItems = await this.embedPdfBook.exportAnnotations();
const items = this.filterAndDeduplicateAnnotations(allItems);
@@ -1330,16 +1328,18 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
}
private saveProgressSync(): void {
if (!this.bookId || !this.page) return;
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0;
const currentPage = this.page();
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> = {
bookId: this.bookId,
pdfProgress: { page: this.page, percentage }
pdfProgress: { page: currentPage, percentage }
};
if (this.bookFileId) {
body['fileProgress'] = {
bookFileId: this.bookFileId,
positionData: String(this.page),
positionData: String(currentPage),
progressPercent: percentage
};
}
@@ -107,7 +107,7 @@ export class EmbedPdfBookService {
defaultZoomLevel: 'fit-page' as ZoomMode,
},
render: {
defaultImageQuality: 2,
defaultImageQuality: 4,
},
tiling: {
tileSize: 1024,
@@ -451,7 +451,7 @@ export class EmbedPdfBookService {
* PDF pages appear noticeably pixelated.
*/
private ensureHighDpiRendering(): void {
const MIN_DPR = 2;
const MIN_DPR = 2.5;
if (window.devicePixelRatio < MIN_DPR) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const w = window as any;