fix(pdf): improve PDF blob handling and improve viewer destruction logic (#506)
* fix(pdf): improve PDF blob handling and improve viewer destruction logic * fix(pdf): PDF annotation saving logic and improve responsive design for mobile * fix(pdf): improve PDF fetching (once again) and caching logic to improve performance and reduce network requests * fix(pdf): hide footer and notification elements in PDF viewer * fix(pdf): improve loading behavior and improve annotation persistence logic * fix(pdf): improve PDF annotation persistence with retry mechanism and logging * fix(pdf): improve PDF annotation saving with raw fetch and improved error handling * fix(pdf): cap highlight opacity and adjust rendering for small viewports
This commit is contained in:
+63
@@ -0,0 +1,63 @@
|
|||||||
|
package org.booklore.service.book;
|
||||||
|
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.booklore.model.entity.BookEntity;
|
||||||
|
import org.booklore.model.entity.BookLoreUserEntity;
|
||||||
|
import org.booklore.model.entity.PdfAnnotationEntity;
|
||||||
|
import org.booklore.repository.BookRepository;
|
||||||
|
import org.booklore.repository.PdfAnnotationRepository;
|
||||||
|
import org.booklore.repository.UserRepository;
|
||||||
|
import jakarta.persistence.EntityNotFoundException;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Propagation;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles the actual database persistence for PDF annotations in isolated transactions.
|
||||||
|
* This ensures that flush failures (optimistic locking or constraints) don't poison
|
||||||
|
* the caller's transaction and allow for clean retries.
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Slf4j
|
||||||
|
public class PdfAnnotationPersistenceHandler {
|
||||||
|
|
||||||
|
private final PdfAnnotationRepository pdfAnnotationRepository;
|
||||||
|
private final BookRepository bookRepository;
|
||||||
|
private final UserRepository userRepository;
|
||||||
|
|
||||||
|
@Transactional(propagation = Propagation.REQUIRES_NEW)
|
||||||
|
public void saveOrUpdate(Long bookId, Long userId, String data) {
|
||||||
|
Optional<PdfAnnotationEntity> existing = pdfAnnotationRepository.findByBookIdAndUserId(bookId, userId);
|
||||||
|
|
||||||
|
if (existing.isPresent()) {
|
||||||
|
PdfAnnotationEntity entity = existing.get();
|
||||||
|
// Version check is performed by Hibernate on flush
|
||||||
|
entity.setData(data);
|
||||||
|
pdfAnnotationRepository.saveAndFlush(entity);
|
||||||
|
log.info("Updated PDF annotations for book {} by user {}", bookId, userId);
|
||||||
|
} else {
|
||||||
|
PdfAnnotationEntity entity = PdfAnnotationEntity.builder()
|
||||||
|
.book(findBook(bookId))
|
||||||
|
.user(findUser(userId))
|
||||||
|
.data(data)
|
||||||
|
.build();
|
||||||
|
// Unique constraint check happens on flush
|
||||||
|
pdfAnnotationRepository.saveAndFlush(entity);
|
||||||
|
log.info("Created PDF annotations for book {} by user {}", bookId, userId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private BookEntity findBook(Long bookId) {
|
||||||
|
return bookRepository.findById(bookId)
|
||||||
|
.orElseThrow(() -> new EntityNotFoundException("Book not found: " + bookId));
|
||||||
|
}
|
||||||
|
|
||||||
|
private BookLoreUserEntity findUser(Long userId) {
|
||||||
|
return userRepository.findById(userId)
|
||||||
|
.orElseThrow(() -> new EntityNotFoundException("User not found: " + userId));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,19 +1,16 @@
|
|||||||
package org.booklore.service.book;
|
package org.booklore.service.book;
|
||||||
|
|
||||||
import org.booklore.config.security.service.AuthenticationService;
|
import org.booklore.config.security.service.AuthenticationService;
|
||||||
import org.booklore.model.entity.BookEntity;
|
|
||||||
import org.booklore.model.entity.BookLoreUserEntity;
|
|
||||||
import org.booklore.model.entity.PdfAnnotationEntity;
|
|
||||||
import org.booklore.repository.BookRepository;
|
|
||||||
import org.booklore.repository.PdfAnnotationRepository;
|
import org.booklore.repository.PdfAnnotationRepository;
|
||||||
import org.booklore.repository.UserRepository;
|
|
||||||
import jakarta.persistence.EntityNotFoundException;
|
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.orm.ObjectOptimisticLockingFailureException;
|
||||||
|
import org.springframework.dao.DataIntegrityViolationException;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
import org.booklore.model.entity.PdfAnnotationEntity;
|
||||||
|
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
@@ -21,9 +18,8 @@ import java.util.Optional;
|
|||||||
public class PdfAnnotationService {
|
public class PdfAnnotationService {
|
||||||
|
|
||||||
private final PdfAnnotationRepository pdfAnnotationRepository;
|
private final PdfAnnotationRepository pdfAnnotationRepository;
|
||||||
private final BookRepository bookRepository;
|
|
||||||
private final UserRepository userRepository;
|
|
||||||
private final AuthenticationService authenticationService;
|
private final AuthenticationService authenticationService;
|
||||||
|
private final PdfAnnotationPersistenceHandler pdfAnnotationPersistenceHandler;
|
||||||
|
|
||||||
@Transactional(readOnly = true)
|
@Transactional(readOnly = true)
|
||||||
public Optional<String> getAnnotations(Long bookId) {
|
public Optional<String> getAnnotations(Long bookId) {
|
||||||
@@ -32,24 +28,38 @@ public class PdfAnnotationService {
|
|||||||
.map(PdfAnnotationEntity::getData);
|
.map(PdfAnnotationEntity::getData);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Transactional
|
/**
|
||||||
|
* Orchestrates the save/update of PDF annotations with a retry mechanism.
|
||||||
|
* The actual database operation is handled by {@link PdfAnnotationPersistenceHandler}
|
||||||
|
* in its own transaction (REQUIRES_NEW) to ensure that concurrency failures
|
||||||
|
* don't poison the main request transaction.
|
||||||
|
*/
|
||||||
public void saveAnnotations(Long bookId, String data) {
|
public void saveAnnotations(Long bookId, String data) {
|
||||||
Long userId = getCurrentUserId();
|
Long userId = getCurrentUserId();
|
||||||
Optional<PdfAnnotationEntity> existing = pdfAnnotationRepository.findByBookIdAndUserId(bookId, userId);
|
int maxRetries = 3;
|
||||||
|
int retryCount = 0;
|
||||||
|
|
||||||
if (existing.isPresent()) {
|
while (retryCount < maxRetries) {
|
||||||
PdfAnnotationEntity entity = existing.get();
|
try {
|
||||||
entity.setData(data);
|
pdfAnnotationPersistenceHandler.saveOrUpdate(bookId, userId, data);
|
||||||
pdfAnnotationRepository.save(entity);
|
return;
|
||||||
log.info("Updated PDF annotations for book {} by user {}", bookId, userId);
|
} catch (ObjectOptimisticLockingFailureException | DataIntegrityViolationException e) {
|
||||||
} else {
|
retryCount++;
|
||||||
PdfAnnotationEntity entity = PdfAnnotationEntity.builder()
|
if (retryCount >= maxRetries) {
|
||||||
.book(findBook(bookId))
|
log.error("Failed to save PDF annotations for book {}/user {} after {} retries: {}",
|
||||||
.user(findUser(userId))
|
bookId, userId, maxRetries, e.getMessage());
|
||||||
.data(data)
|
throw e; // Final failure, pass to exception handler
|
||||||
.build();
|
}
|
||||||
pdfAnnotationRepository.save(entity);
|
log.info("Concurrent update for PDF annotations (book {}, user {}), retrying (attempt {}/{}). Reason: {}",
|
||||||
log.info("Created PDF annotations for book {} by user {}", bookId, userId);
|
bookId, userId, retryCount, maxRetries, e.getMessage());
|
||||||
|
|
||||||
|
try {
|
||||||
|
Thread.sleep(50); // Small backoff before retry
|
||||||
|
} catch (InterruptedException ie) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
throw new RuntimeException(ie);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,14 +73,4 @@ public class PdfAnnotationService {
|
|||||||
private Long getCurrentUserId() {
|
private Long getCurrentUserId() {
|
||||||
return authenticationService.getAuthenticatedUser().getId();
|
return authenticationService.getAuthenticatedUser().getId();
|
||||||
}
|
}
|
||||||
|
|
||||||
private BookEntity findBook(Long bookId) {
|
|
||||||
return bookRepository.findById(bookId)
|
|
||||||
.orElseThrow(() -> new EntityNotFoundException("Book not found: " + bookId));
|
|
||||||
}
|
|
||||||
|
|
||||||
private BookLoreUserEntity findUser(Long userId) {
|
|
||||||
return userRepository.findById(userId)
|
|
||||||
.orElseThrow(() -> new EntityNotFoundException("User not found: " + userId));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,8 @@
|
|||||||
"navigationUrls": [
|
"navigationUrls": [
|
||||||
"/**",
|
"/**",
|
||||||
"!/api/**",
|
"!/api/**",
|
||||||
"!/komga/**"
|
"!/komga/**",
|
||||||
|
"!/assets/embedpdf-frame.html"
|
||||||
],
|
],
|
||||||
"assetGroups": [
|
"assetGroups": [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,21 +1,26 @@
|
|||||||
import {HttpErrorResponse, HttpEvent, HttpHandlerFn, HttpInterceptorFn, HttpRequest} from '@angular/common/http';
|
import {HttpErrorResponse, HttpEvent, HttpHandlerFn, HttpInterceptorFn, HttpRequest} from '@angular/common/http';
|
||||||
import {inject} from '@angular/core';
|
import {inject} from '@angular/core';
|
||||||
import {catchError, filter, switchMap, take} from 'rxjs/operators';
|
import {catchError, filter, switchMap, take} from 'rxjs/operators';
|
||||||
import {BehaviorSubject, Observable, throwError} from 'rxjs';
|
import {BehaviorSubject, Observable, throwError, defer} from 'rxjs';
|
||||||
import {AuthService} from '../../shared/service/auth.service';
|
import {AuthService} from '../../shared/service/auth.service';
|
||||||
import {API_CONFIG} from '../config/api-config';
|
import {API_CONFIG} from '../config/api-config';
|
||||||
|
|
||||||
|
let isRefreshing = false;
|
||||||
|
const refreshTokenSubject = new BehaviorSubject<string | null>(null);
|
||||||
|
|
||||||
export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandlerFn) => {
|
export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandlerFn) => {
|
||||||
const authService = inject(AuthService);
|
const authService = inject(AuthService);
|
||||||
|
|
||||||
const token = authService.getInternalAccessToken();
|
const token = authService.getInternalAccessToken();
|
||||||
const isApiRequest = req.url.startsWith(`${API_CONFIG.BASE_URL}/api/`);
|
const isApiRequest = req.url.startsWith(`${API_CONFIG.BASE_URL}/api/`);
|
||||||
|
const isAuthRequest = req.url.startsWith(`${API_CONFIG.BASE_URL}/api/v1/auth/`);
|
||||||
|
const hasAuthHeader = req.headers.has('Authorization');
|
||||||
|
|
||||||
const authReq = (token && isApiRequest) ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req;
|
const authReq = (token && isApiRequest && !isAuthRequest && !hasAuthHeader) ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req;
|
||||||
|
|
||||||
return next(authReq).pipe(
|
return next(authReq).pipe(
|
||||||
catchError((error: HttpErrorResponse) => {
|
catchError((error: HttpErrorResponse) => {
|
||||||
if (error.status === 401) {
|
if (error.status === 401 && !isAuthRequest) {
|
||||||
return handle401Error(authService, authReq, next);
|
return handle401Error(authService, authReq, next);
|
||||||
}
|
}
|
||||||
return throwError(() => error);
|
return throwError(() => error);
|
||||||
@@ -23,43 +28,42 @@ export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandler
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
let isRefreshing = false;
|
|
||||||
const refreshTokenSubject = new BehaviorSubject<string | null>(null);
|
|
||||||
|
|
||||||
function handle401Error(authService: AuthService, request: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> {
|
function handle401Error(authService: AuthService, request: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> {
|
||||||
if (!isRefreshing) {
|
return defer(() => {
|
||||||
isRefreshing = true;
|
if (!isRefreshing) {
|
||||||
refreshTokenSubject.next(null);
|
isRefreshing = true;
|
||||||
|
refreshTokenSubject.next(null);
|
||||||
|
|
||||||
return authService.internalRefreshToken().pipe(
|
return authService.internalRefreshToken().pipe(
|
||||||
switchMap(response => {
|
switchMap(response => {
|
||||||
isRefreshing = false;
|
isRefreshing = false;
|
||||||
const { accessToken, refreshToken } = response;
|
const { accessToken, refreshToken } = response;
|
||||||
if (accessToken && refreshToken) {
|
if (accessToken && refreshToken) {
|
||||||
authService.saveInternalTokens(accessToken, refreshToken);
|
authService.saveInternalTokens(accessToken, refreshToken);
|
||||||
refreshTokenSubject.next(accessToken);
|
refreshTokenSubject.next(accessToken);
|
||||||
}
|
}
|
||||||
return next(request.clone({
|
return next(request.clone({
|
||||||
setHeaders: { Authorization: `Bearer ${accessToken}` }
|
setHeaders: { Authorization: `Bearer ${accessToken}` }
|
||||||
}));
|
}));
|
||||||
}),
|
}),
|
||||||
catchError(err => {
|
catchError(err => {
|
||||||
isRefreshing = false;
|
isRefreshing = false;
|
||||||
forceLogout(authService);
|
forceLogout(authService);
|
||||||
return throwError(() => err);
|
return throwError(() => err);
|
||||||
})
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return refreshTokenSubject.pipe(
|
||||||
|
filter(token => token !== null),
|
||||||
|
take(1),
|
||||||
|
switchMap(token =>
|
||||||
|
next(request.clone({
|
||||||
|
setHeaders: { Authorization: `Bearer ${token}` }
|
||||||
|
}))
|
||||||
|
)
|
||||||
);
|
);
|
||||||
}
|
});
|
||||||
|
|
||||||
return refreshTokenSubject.pipe(
|
|
||||||
filter(token => token !== null),
|
|
||||||
take(1),
|
|
||||||
switchMap(token =>
|
|
||||||
next(request.clone({
|
|
||||||
setHeaders: { Authorization: `Bearer ${token}` }
|
|
||||||
}))
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function forceLogout(authService: AuthService): void {
|
function forceLogout(authService: AuthService): void {
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
@if (isLoading()) {
|
@if (isLoading() || (viewerMode() === 'book' && !isInitialScrollDone())) {
|
||||||
<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()" [class.v-hidden]="viewerMode() === 'book' && !isInitialScrollDone()">
|
||||||
|
|
||||||
<!-- 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>
|
||||||
|
|||||||
@@ -13,14 +13,21 @@ $active-color: #4a90e2;
|
|||||||
$hover-bg: rgb(255 255 255 / 12%);
|
$hover-bg: rgb(255 255 255 / 12%);
|
||||||
$transition-fast: 150ms ease;
|
$transition-fast: 150ms ease;
|
||||||
|
|
||||||
|
.v-hidden {
|
||||||
|
visibility: hidden !important;
|
||||||
|
}
|
||||||
|
|
||||||
// --- Loading ---
|
// --- Loading ---
|
||||||
|
|
||||||
.loading-container {
|
.loading-container {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
height: 100dvh;
|
height: 100dvh;
|
||||||
background: #1a1a1a;
|
background: #1a1a1a;
|
||||||
|
z-index: 1000;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Reader container ---
|
// --- Reader container ---
|
||||||
@@ -77,11 +84,10 @@ $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;
|
||||||
z-index: 1002;
|
z-index: 1001;
|
||||||
background: $gradient-bg;
|
background: $gradient-bg;
|
||||||
border-bottom: 1px solid $border-color;
|
border-bottom: 1px solid $border-color;
|
||||||
box-shadow: 0 2px 8px rgb(0 0 0 / 30%);
|
box-shadow: 0 2px 8px rgb(0 0 0 / 30%);
|
||||||
@@ -809,7 +815,7 @@ $transition-fast: 150ms ease;
|
|||||||
.doc-viewer-info {
|
.doc-viewer-info {
|
||||||
right: 12px;
|
right: 12px;
|
||||||
left: 12px;
|
left: 12px;
|
||||||
top: 48px;
|
top: calc(48px + env(safe-area-inset-top));
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ import { Component, ElementRef, inject, Injector, NgZone, OnDestroy, OnInit, aft
|
|||||||
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 } from "rxjs";
|
import { forkJoin, from, Observable, of, Subject, Subscription } from "rxjs";
|
||||||
import { debounceTime, filter, map, switchMap } from 'rxjs/operators';
|
import { debounceTime, filter, map, switchMap, take } from 'rxjs/operators';
|
||||||
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
|
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';
|
||||||
@@ -72,6 +72,8 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
|||||||
readonly pdfBookmarks = signal<BookMark[]>([]);
|
readonly pdfBookmarks = signal<BookMark[]>([]);
|
||||||
readonly annotationListItems = signal<PdfAnnotationListItem[]>([]);
|
readonly annotationListItems = signal<PdfAnnotationListItem[]>([]);
|
||||||
|
|
||||||
|
readonly isInitialScrollDone = signal(false);
|
||||||
|
|
||||||
readonly sliderTicks = computed(() => {
|
readonly sliderTicks = computed(() => {
|
||||||
const total = this.totalPages();
|
const total = this.totalPages();
|
||||||
if (total <= 1) return [];
|
if (total <= 1) return [];
|
||||||
@@ -117,6 +119,8 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
|||||||
private initTimeout?: ReturnType<typeof setTimeout>;
|
private initTimeout?: ReturnType<typeof setTimeout>;
|
||||||
private isInitializingBookViewer = false;
|
private isInitializingBookViewer = false;
|
||||||
private pdfFetchAbortController?: AbortController;
|
private pdfFetchAbortController?: AbortController;
|
||||||
|
private cachedPdfBuffer: ArrayBuffer | null = null;
|
||||||
|
private suppressProgressSave = false;
|
||||||
|
|
||||||
// Book mode state
|
// Book mode state
|
||||||
private bookViewerInitialized = false;
|
private bookViewerInitialized = false;
|
||||||
@@ -366,6 +370,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
|||||||
this.page.set(pdfMeta.pdfProgress?.page || 1);
|
this.page.set(pdfMeta.pdfProgress?.page || 1);
|
||||||
this.zoom.set(this.normalizeZoom(zoomVal));
|
this.zoom.set(this.normalizeZoom(zoomVal));
|
||||||
this.bookData = bookData;
|
this.bookData = bookData;
|
||||||
|
this.isInitialScrollDone.set(false);
|
||||||
this.isLoading.set(false);
|
this.isLoading.set(false);
|
||||||
|
|
||||||
// Schedule viewer initialization after the template renders the container
|
// Schedule viewer initialization after the template renders the container
|
||||||
@@ -407,7 +412,9 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
|||||||
this.pdfFetchAbortController = new AbortController();
|
this.pdfFetchAbortController = new AbortController();
|
||||||
|
|
||||||
let pdfUrl: string;
|
let pdfUrl: string;
|
||||||
if (currentBookData.startsWith('blob:')) {
|
if (this.pdfBlobUrl) {
|
||||||
|
pdfUrl = this.pdfBlobUrl;
|
||||||
|
} else if (currentBookData.startsWith('blob:')) {
|
||||||
pdfUrl = currentBookData;
|
pdfUrl = currentBookData;
|
||||||
} else {
|
} else {
|
||||||
pdfUrl = await this.fetchAsObjectUrl(currentBookData, this.pdfFetchAbortController.signal);
|
pdfUrl = await this.fetchAsObjectUrl(currentBookData, this.pdfFetchAbortController.signal);
|
||||||
@@ -428,6 +435,16 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
|||||||
);
|
);
|
||||||
this.bookViewerInitialized = true;
|
this.bookViewerInitialized = true;
|
||||||
|
|
||||||
|
// Cache the raw PDF bytes so the doc-viewer switch never needs a network request
|
||||||
|
if (!this.cachedPdfBuffer) {
|
||||||
|
const blobSrc = this.pdfBlobUrl || (this.bookData.startsWith('blob:') ? this.bookData : null);
|
||||||
|
if (blobSrc) {
|
||||||
|
fetch(blobSrc).then(r => r.arrayBuffer()).then(buf => {
|
||||||
|
this.cachedPdfBuffer = buf;
|
||||||
|
}).catch(() => { /* caching is best-effort */ });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Initialize bookmark service early so toggleBookmark works before documentOpened$
|
// Initialize bookmark service early so toggleBookmark works before documentOpened$
|
||||||
this.pdfBookmarkService.initialize(this.bookId);
|
this.pdfBookmarkService.initialize(this.bookId);
|
||||||
|
|
||||||
@@ -499,11 +516,30 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
|||||||
// 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(
|
||||||
takeUntilDestroyed(this.destroyRef),
|
takeUntilDestroyed(this.destroyRef),
|
||||||
debounceTime(200) // Give the engine a moment to settle and start high-quality rendering
|
take(1)
|
||||||
).subscribe(() => {
|
).subscribe(() => {
|
||||||
const currentPage = this.page();
|
const currentPage = this.page();
|
||||||
if (currentPage > 1) {
|
if (currentPage > 1) {
|
||||||
this.embedPdfBook.scrollToPage(currentPage, 'instant');
|
this.embedPdfBook.scrollToPage(currentPage, 'instant');
|
||||||
|
|
||||||
|
// Wait for the scroll to be processed before revealing the viewer.
|
||||||
|
// EmbedPDF processes scrollToPage asynchronously, so revealing
|
||||||
|
// immediately would flash page 1 before jumping to the target.
|
||||||
|
const scrollSub = this.embedPdfBook.pageChange$.pipe(
|
||||||
|
filter(ev => ev.pageNumber >= currentPage - 1),
|
||||||
|
take(1)
|
||||||
|
).subscribe(() => {
|
||||||
|
this.ngZone.run(() => this.isInitialScrollDone.set(true));
|
||||||
|
});
|
||||||
|
// Fallback in case pageChange$ doesn't fire (e.g. single-page PDF)
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!this.isInitialScrollDone()) {
|
||||||
|
scrollSub.unsubscribe();
|
||||||
|
this.ngZone.run(() => this.isInitialScrollDone.set(true));
|
||||||
|
}
|
||||||
|
}, 800);
|
||||||
|
} else {
|
||||||
|
this.isInitialScrollDone.set(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load outline, bookmarks, and annotations after layout is ready and settled
|
// Load outline, bookmarks, and annotations after layout is ready and settled
|
||||||
@@ -544,10 +580,12 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private destroyBookViewer(): void {
|
private destroyBookViewer(revoke = true): void {
|
||||||
this.embedPdfBook.destroy();
|
this.embedPdfBook.destroy();
|
||||||
this.bookViewerInitialized = false;
|
this.bookViewerInitialized = false;
|
||||||
this.revokePdfBlobUrl();
|
if (revoke) {
|
||||||
|
this.revokePdfBlobUrl();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async loadOutline(): Promise<void> {
|
private async loadOutline(): Promise<void> {
|
||||||
@@ -565,6 +603,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
|||||||
next: async (response) => {
|
next: async (response) => {
|
||||||
console.info('[PDF Annotations] GET response:', response);
|
console.info('[PDF Annotations] GET response:', response);
|
||||||
if (response?.data) {
|
if (response?.data) {
|
||||||
|
this.lastAnnotationData = response.data;
|
||||||
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));
|
||||||
|
|
||||||
@@ -621,6 +660,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
|||||||
try {
|
try {
|
||||||
const allItems = await this.embedPdfBook.exportAnnotations();
|
const allItems = await this.embedPdfBook.exportAnnotations();
|
||||||
const items = this.filterAndDeduplicateAnnotations(allItems);
|
const items = this.filterAndDeduplicateAnnotations(allItems);
|
||||||
|
console.info(`[PDF Annotations] refresh list: exported ${allItems.length}, kept ${items.length}`);
|
||||||
this.annotationListItems.set(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 {
|
||||||
@@ -792,9 +832,10 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (mode === 'document') {
|
if (mode === 'document') {
|
||||||
// Save annotations before switching
|
this.suppressProgressSave = true;
|
||||||
|
// Ensure annotations are captured before destroying the book viewer
|
||||||
await this.persistAnnotations();
|
await this.persistAnnotations();
|
||||||
this.destroyBookViewer();
|
this.destroyBookViewer(false); // Do not revoke blob URL
|
||||||
this.viewerMode.set(mode);
|
this.viewerMode.set(mode);
|
||||||
this.initTimeout = setTimeout(() => {
|
this.initTimeout = setTimeout(() => {
|
||||||
this.initTimeout = undefined;
|
this.initTimeout = undefined;
|
||||||
@@ -806,6 +847,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
|||||||
this.saveEmbedPdfDocument().finally(() => this.destroyDocViewerIframe());
|
this.saveEmbedPdfDocument().finally(() => this.destroyDocViewerIframe());
|
||||||
}
|
}
|
||||||
this.viewerMode.set(mode);
|
this.viewerMode.set(mode);
|
||||||
|
this.isInitialScrollDone.set(false);
|
||||||
this.initTimeout = setTimeout(() => {
|
this.initTimeout = setTimeout(() => {
|
||||||
this.initTimeout = undefined;
|
this.initTimeout = undefined;
|
||||||
this.initBookViewer();
|
this.initBookViewer();
|
||||||
@@ -822,18 +864,30 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
|||||||
this.embedPdfInitTime = t0;
|
this.embedPdfInitTime = t0;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const headers: Record<string, string> = {};
|
let pdfBuffer: ArrayBuffer;
|
||||||
const token = this.authService.getInternalAccessToken();
|
|
||||||
if (token) {
|
|
||||||
headers['Authorization'] = `Bearer ${token}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = await fetch(this.bookData, { headers, credentials: 'include' });
|
if (this.cachedPdfBuffer) {
|
||||||
if (!response.ok) throw new Error(`PDF fetch failed: ${response.status}`);
|
// Use the in-memory cache — completely network-free
|
||||||
|
pdfBuffer = this.cachedPdfBuffer.slice(0);
|
||||||
|
} else {
|
||||||
|
const source = this.pdfBlobUrl || this.bookData;
|
||||||
|
if (source.startsWith('blob:')) {
|
||||||
|
const res = await fetch(source);
|
||||||
|
pdfBuffer = await res.arrayBuffer();
|
||||||
|
} else {
|
||||||
|
const headers: Record<string, string> = {};
|
||||||
|
const token = this.authService.getInternalAccessToken();
|
||||||
|
if (token) {
|
||||||
|
headers['Authorization'] = `Bearer ${token}`;
|
||||||
|
}
|
||||||
|
const response = await fetch(source, { headers, credentials: 'include' });
|
||||||
|
if (!response.ok) throw new Error(`PDF fetch failed: ${response.status}`);
|
||||||
|
pdfBuffer = await response.arrayBuffer();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (this.viewerMode() !== 'document') return;
|
if (this.viewerMode() !== 'document') return;
|
||||||
|
|
||||||
const pdfBuffer = await response.arrayBuffer();
|
|
||||||
const targetEl = document.getElementById('embedpdf-viewer');
|
const targetEl = document.getElementById('embedpdf-viewer');
|
||||||
if (!targetEl) throw new Error('#embedpdf-viewer not found');
|
if (!targetEl) throw new Error('#embedpdf-viewer not found');
|
||||||
|
|
||||||
@@ -889,6 +943,14 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case 'documentOpened':
|
case 'documentOpened':
|
||||||
|
// Scroll to the page the user was on in book mode and re-enable progress saving
|
||||||
|
if (this.embedPdfIframe?.contentWindow && this.page() > 1) {
|
||||||
|
this.embedPdfIframe.contentWindow.postMessage(
|
||||||
|
{ type: 'scrollToPage', pageNumber: this.page() },
|
||||||
|
location.origin
|
||||||
|
);
|
||||||
|
}
|
||||||
|
setTimeout(() => { this.suppressProgressSave = false; }, 500);
|
||||||
break;
|
break;
|
||||||
case 'documentError':
|
case 'documentError':
|
||||||
console.error('[EmbedPDF] Document error:', msg.error);
|
console.error('[EmbedPDF] Document error:', msg.error);
|
||||||
@@ -1018,6 +1080,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
updateProgress(): void {
|
updateProgress(): void {
|
||||||
|
if (this.suppressProgressSave) return;
|
||||||
const currentPage = this.page();
|
const currentPage = this.page();
|
||||||
const total = this.totalPages();
|
const total = this.totalPages();
|
||||||
const percentage = total > 0 ? Math.round((currentPage / total) * 1000) / 10 : 0;
|
const percentage = total > 0 ? Math.round((currentPage / total) * 1000) / 10 : 0;
|
||||||
@@ -1057,6 +1120,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
|||||||
this.touchCleanup?.();
|
this.touchCleanup?.();
|
||||||
|
|
||||||
this.revokePdfBlobUrl();
|
this.revokePdfBlobUrl();
|
||||||
|
this.cachedPdfBuffer = null;
|
||||||
if (this.bookData?.startsWith('blob:')) {
|
if (this.bookData?.startsWith('blob:')) {
|
||||||
URL.revokeObjectURL(this.bookData);
|
URL.revokeObjectURL(this.bookData);
|
||||||
}
|
}
|
||||||
@@ -1289,41 +1353,78 @@ 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' || !this.annotationsDirty) {
|
||||||
|
console.info('[PDF Annotations] Skip save: loaded=', this.annotationsLoaded, 'dirty=', this.annotationsDirty);
|
||||||
|
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);
|
||||||
const data = serializeAnnotations(items);
|
const data = serializeAnnotations(items);
|
||||||
|
|
||||||
|
console.info(`[PDF Annotations] Initiating save: exported ${allItems.length}, kept ${items.length}`);
|
||||||
|
|
||||||
this.lastAnnotationData = data;
|
this.lastAnnotationData = data;
|
||||||
this.annotationsDirty = false;
|
this.annotationsDirty = false; // Speculatively clear to avoid double-save
|
||||||
await firstValueFrom(this.pdfAnnotationService.saveAnnotations(this.bookId, data));
|
|
||||||
console.info('[PDF Annotations] Saved', items.length, 'annotations for book', this.bookId);
|
// Use raw fetch() instead of HttpClient so the auth interceptor cannot
|
||||||
|
// trigger forceLogout() on an expired token during viewer-mode switches.
|
||||||
|
const saveUrl = `${API_CONFIG.BASE_URL}/api/v1/pdf-annotations/book/${this.bookId}`;
|
||||||
|
const saveHeaders: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||||
|
const saveToken = this.authService.getInternalAccessToken();
|
||||||
|
if (saveToken) {
|
||||||
|
saveHeaders['Authorization'] = `Bearer ${saveToken}`;
|
||||||
|
}
|
||||||
|
fetch(saveUrl, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: saveHeaders,
|
||||||
|
credentials: 'include',
|
||||||
|
body: JSON.stringify({ data }),
|
||||||
|
}).then(res => {
|
||||||
|
if (res.ok) {
|
||||||
|
console.info('[PDF Annotations] Saved', items.length, 'annotations for book', this.bookId);
|
||||||
|
} else {
|
||||||
|
this.annotationsDirty = true;
|
||||||
|
console.error('[PDF Annotations] Save failed:', res.status);
|
||||||
|
}
|
||||||
|
}).catch(err => {
|
||||||
|
this.annotationsDirty = true;
|
||||||
|
console.error('[PDF Annotations] Failed to save annotations:', err);
|
||||||
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('[PDF Annotations] Failed to save annotations:', e);
|
console.error('[PDF Annotations] Failed to export annotations:', e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private persistAnnotationsSync(): void {
|
private persistAnnotationsSync(): void {
|
||||||
if (!this.bookId || this.lastAnnotationData === null) return;
|
if (!this.bookId || this.lastAnnotationData === null || !this.annotationsDirty) {
|
||||||
|
console.info('[PDF Annotations Sync] Skip sync save: dirty=', this.annotationsDirty);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.annotationsDirty = false;
|
||||||
|
|
||||||
const url = `${API_CONFIG.BASE_URL}/api/v1/pdf-annotations/book/${this.bookId}`;
|
const url = `${API_CONFIG.BASE_URL}/api/v1/pdf-annotations/book/${this.bookId}`;
|
||||||
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
const headers: Record<string, string> = { 'Content-Type': 'application/json' };
|
||||||
const syncToken = this.authService.getInternalAccessToken();
|
const syncToken = this.authService.getInternalAccessToken();
|
||||||
if (syncToken) {
|
if (syncToken) {
|
||||||
headers['Authorization'] = `Bearer ${syncToken}`;
|
headers['Authorization'] = `Bearer ${syncToken}`;
|
||||||
}
|
}
|
||||||
|
console.info('[PDF Annotations Sync] Sending sync save request');
|
||||||
fetch(url, {
|
fetch(url, {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
headers,
|
headers,
|
||||||
credentials: 'include',
|
credentials: 'include',
|
||||||
body: JSON.stringify({ data: this.lastAnnotationData }),
|
body: JSON.stringify({ data: this.lastAnnotationData }),
|
||||||
keepalive: true,
|
keepalive: true,
|
||||||
}).catch(() => { /* fire-and-forget */ });
|
}).catch((err) => { console.error('[PDF Annotations Sync] Sync save failed:', err); });
|
||||||
}
|
}
|
||||||
|
|
||||||
private cacheAnnotationData(): void {
|
private cacheAnnotationData(): void {
|
||||||
this.embedPdfBook.exportAnnotations().then(allItems => {
|
this.embedPdfBook.exportAnnotations().then(allItems => {
|
||||||
const items = this.filterAndDeduplicateAnnotations(allItems);
|
const items = this.filterAndDeduplicateAnnotations(allItems);
|
||||||
this.lastAnnotationData = serializeAnnotations(items);
|
this.lastAnnotationData = serializeAnnotations(items);
|
||||||
|
console.info(`[PDF Annotations] Cache updated: ${items.length} items`);
|
||||||
}).catch(() => { /* fire-and-forget */ });
|
}).catch(() => { /* fire-and-forget */ });
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1349,6 +1450,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
|||||||
if (progressToken) {
|
if (progressToken) {
|
||||||
headers['Authorization'] = `Bearer ${progressToken}`;
|
headers['Authorization'] = `Bearer ${progressToken}`;
|
||||||
}
|
}
|
||||||
|
console.info('[PDF Progress Sync] Sending progress sync request');
|
||||||
fetch(url, {
|
fetch(url, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers,
|
headers,
|
||||||
@@ -1362,7 +1464,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
|||||||
const seenIds = new Set<string>();
|
const seenIds = new Set<string>();
|
||||||
const allowedSubtypes = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15]);
|
const allowedSubtypes = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15]);
|
||||||
|
|
||||||
return allItems.filter(item => {
|
const filtered = allItems.filter(item => {
|
||||||
const ann = item.annotation;
|
const ann = item.annotation;
|
||||||
const id = ann?.id;
|
const id = ann?.id;
|
||||||
if (!id || seenIds.has(id)) return false;
|
if (!id || seenIds.has(id)) return false;
|
||||||
@@ -1372,11 +1474,16 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
|
|||||||
if (!allowedSubtypes.has(type)) return false;
|
if (!allowedSubtypes.has(type)) return false;
|
||||||
|
|
||||||
// Only allow if it's in our DB-tracked set (for sync)
|
// Only allow if it's in our DB-tracked set (for sync)
|
||||||
if (!this.dbAnnotationIds.has(id)) return false;
|
if (!this.dbAnnotationIds.has(id)) {
|
||||||
|
// console.warn(`[PDF Annotations] Filtered out unknown ID: ${id} (type: ${type})`);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
seenIds.add(id);
|
seenIds.add(id);
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
return filtered;
|
||||||
}
|
}
|
||||||
|
|
||||||
private normalizeZoom(zoom: string): string {
|
private normalizeZoom(zoom: string): string {
|
||||||
|
|||||||
@@ -78,6 +78,7 @@ export class EmbedPdfBookService {
|
|||||||
|
|
||||||
const wasmUrl = new URL('/assets/pdfium/pdfium.wasm', location.origin).href;
|
const wasmUrl = new URL('/assets/pdfium/pdfium.wasm', location.origin).href;
|
||||||
const requestedLocale = localeCode || 'en';
|
const requestedLocale = localeCode || 'en';
|
||||||
|
const isSmallViewport = window.innerWidth <= 768;
|
||||||
|
|
||||||
this.container = EmbedPDF.init({
|
this.container = EmbedPDF.init({
|
||||||
type: 'container',
|
type: 'container',
|
||||||
@@ -102,18 +103,28 @@ export class EmbedPdfBookService {
|
|||||||
annotations: {
|
annotations: {
|
||||||
autoCommit: true,
|
autoCommit: true,
|
||||||
autoOpenLinks: false,
|
autoOpenLinks: false,
|
||||||
|
tools: [
|
||||||
|
{
|
||||||
|
id: 'highlight',
|
||||||
|
defaults: {
|
||||||
|
opacity: 0.4,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'inkHighlighter',
|
||||||
|
defaults: {
|
||||||
|
opacity: 0.4,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
},
|
},
|
||||||
zoom: {
|
zoom: {
|
||||||
defaultZoomLevel: 'fit-page' as ZoomMode,
|
defaultZoomLevel: 'fit-page' as ZoomMode,
|
||||||
},
|
},
|
||||||
render: {
|
render: {
|
||||||
defaultImageQuality: 4,
|
defaultImageQuality: isSmallViewport ? 0.85 : 0.92,
|
||||||
},
|
|
||||||
tiling: {
|
|
||||||
tileSize: 1024,
|
|
||||||
overlapPx: 2,
|
|
||||||
extraRings: 1,
|
|
||||||
},
|
},
|
||||||
|
tiling: this.getTilingConfig(),
|
||||||
}) ?? null;
|
}) ?? null;
|
||||||
|
|
||||||
if (!this.container) {
|
if (!this.container) {
|
||||||
@@ -449,20 +460,47 @@ export class EmbedPdfBookService {
|
|||||||
* The library reads window.devicePixelRatio at tile-render time; if the
|
* The library reads window.devicePixelRatio at tile-render time; if the
|
||||||
* browser reports 1 (e.g. some WebViews or forced-desktop viewports),
|
* browser reports 1 (e.g. some WebViews or forced-desktop viewports),
|
||||||
* PDF pages appear noticeably pixelated.
|
* PDF pages appear noticeably pixelated.
|
||||||
|
*
|
||||||
|
* On small viewports (phones / responsive mode) we use a lower minimum
|
||||||
|
* to avoid exceeding the browser's image-memory budget once that budget
|
||||||
|
* is breached the browser silently degrades earlier tile bitmaps, which
|
||||||
|
* makes the PDF text appear blurry. Annotation appearance images amplify
|
||||||
|
* the problem because they add extra high-resolution bitmaps on top of
|
||||||
|
* the page tiles.
|
||||||
*/
|
*/
|
||||||
private ensureHighDpiRendering(): void {
|
private ensureHighDpiRendering(): void {
|
||||||
const MIN_DPR = 2.5;
|
const isSmallViewport = window.innerWidth <= 768;
|
||||||
if (window.devicePixelRatio < MIN_DPR) {
|
const currentDpr = window.devicePixelRatio || 1;
|
||||||
|
|
||||||
|
// On small screens, we CAP the DPR at 2.0.
|
||||||
|
// Modern phones often have DPR 3.0+, which combined with annotation layers
|
||||||
|
// exceeds the browser's texture memory budget, leading to "emergency" downsampling (blurriness).
|
||||||
|
const targetDpr = isSmallViewport ? Math.min(currentDpr, 2) : Math.max(currentDpr, 2.5);
|
||||||
|
|
||||||
|
if (currentDpr !== targetDpr) {
|
||||||
// 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;
|
||||||
w.__grimmoryOrigDprDescriptor = Object.getOwnPropertyDescriptor(window, 'devicePixelRatio');
|
w.__grimmoryOrigDprDescriptor = Object.getOwnPropertyDescriptor(window, 'devicePixelRatio');
|
||||||
Object.defineProperty(window, 'devicePixelRatio', {
|
Object.defineProperty(window, 'devicePixelRatio', {
|
||||||
get: () => MIN_DPR,
|
get: () => targetDpr,
|
||||||
configurable: true,
|
configurable: true,
|
||||||
});
|
});
|
||||||
|
console.info(`[EmbedPDF] Adjusted DPR from ${currentDpr} to ${targetDpr} (viewport: ${window.innerWidth}px)`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return tiling config tuned for the current viewport.
|
||||||
|
* Small screens get smaller tiles and no extra rings to stay within
|
||||||
|
* the browser's image-memory budget when annotations are present.
|
||||||
|
*/
|
||||||
|
private getTilingConfig(): {tileSize: number; overlapPx: number; extraRings: number} {
|
||||||
|
const isSmallViewport = window.innerWidth <= 768;
|
||||||
|
return isSmallViewport
|
||||||
|
? {tileSize: 512, overlapPx: 2, extraRings: 0}
|
||||||
|
: {tileSize: 1024, overlapPx: 2, extraRings: 1};
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Apply the same Worker/Blob shims that embedpdf-frame.html uses.
|
* Apply the same Worker/Blob shims that embedpdf-frame.html uses.
|
||||||
* EmbedPDF creates a blob-URL module Worker for PDFium WASM. Some browsers
|
* EmbedPDF creates a blob-URL module Worker for PDFium WASM. Some browsers
|
||||||
@@ -648,7 +686,9 @@ export class EmbedPdfBookService {
|
|||||||
[class*="notification"],
|
[class*="notification"],
|
||||||
[class*="bottom-bar"],
|
[class*="bottom-bar"],
|
||||||
[class*="status-bar"],
|
[class*="status-bar"],
|
||||||
[class*="statusbar"] {
|
[class*="statusbar"],
|
||||||
|
footer,
|
||||||
|
[class*="footer"] {
|
||||||
display: none !important;
|
display: none !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -661,8 +701,6 @@ export class EmbedPdfBookService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/* Improve annotation layer rendering on touch devices.
|
|
||||||
|
|
||||||
/* Improve annotation layer rendering on touch devices.
|
/* Improve annotation layer rendering on touch devices.
|
||||||
FreeText annotation overlays can bleed through when the
|
FreeText annotation overlays can bleed through when the
|
||||||
appearance-stream image has not finished loading. Prevent the
|
appearance-stream image has not finished loading. Prevent the
|
||||||
@@ -670,6 +708,19 @@ export class EmbedPdfBookService {
|
|||||||
[role="textbox"][contenteditable="false"] {
|
[role="textbox"][contenteditable="false"] {
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Prevent mix-blend-mode:multiply on highlight annotation
|
||||||
|
wrappers from forcing the browser to re-rasterise the
|
||||||
|
tile compositing group at a lower resolution on mobile.
|
||||||
|
The PDFium appearance image already carries the correct
|
||||||
|
visual so the CSS blend mode is redundant for committed
|
||||||
|
annotations. During live creation the highlight still
|
||||||
|
renders as a semi-transparent overlay (acceptable). */
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
[data-no-interaction] > div {
|
||||||
|
mix-blend-mode: normal !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
`;
|
`;
|
||||||
shadow.appendChild(style);
|
shadow.appendChild(style);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -120,6 +120,10 @@ function convertHighlight(legacy: Record<string, unknown>): AnnotationTransferIt
|
|||||||
const w = rect[2] - rect[0];
|
const w = rect[2] - rect[0];
|
||||||
const h = rect[3] - rect[1];
|
const h = rect[3] - rect[1];
|
||||||
|
|
||||||
|
// Cap opacity for highlights to prevent solid blocks
|
||||||
|
const rawOpacity = (legacy['opacity'] as number) ?? 0.4;
|
||||||
|
const opacity = Math.min(rawOpacity, 0.6);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
annotation: {
|
annotation: {
|
||||||
type: 9, // PdfAnnotationSubtype.HIGHLIGHT
|
type: 9, // PdfAnnotationSubtype.HIGHLIGHT
|
||||||
@@ -127,7 +131,7 @@ function convertHighlight(legacy: Record<string, unknown>): AnnotationTransferIt
|
|||||||
rect: {origin: {x, y}, size: {width: w, height: h}},
|
rect: {origin: {x, y}, size: {width: w, height: h}},
|
||||||
segmentRects: [{origin: {x, y}, size: {width: w, height: h}}],
|
segmentRects: [{origin: {x, y}, size: {width: w, height: h}}],
|
||||||
color: hexColor,
|
color: hexColor,
|
||||||
opacity: (legacy['opacity'] as number) ?? 1,
|
opacity,
|
||||||
id: crypto.randomUUID(),
|
id: crypto.randomUUID(),
|
||||||
} as never,
|
} as never,
|
||||||
};
|
};
|
||||||
@@ -233,6 +237,12 @@ function base64ToArrayBuffer(base64: string): ArrayBuffer {
|
|||||||
|
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
function restoreArrayBuffers(item: any): AnnotationTransferItem {
|
function restoreArrayBuffers(item: any): AnnotationTransferItem {
|
||||||
|
// Cap opacity for highlights to prevent solid blocks
|
||||||
|
if (item.annotation?.type === 9) {
|
||||||
|
const rawOpacity = item.annotation.opacity ?? 0.4;
|
||||||
|
item.annotation.opacity = Math.min(rawOpacity, 0.6);
|
||||||
|
}
|
||||||
|
|
||||||
if (item.ctx?._dataEncoding === 'base64' && typeof item.ctx.data === 'string') {
|
if (item.ctx?._dataEncoding === 'base64' && typeof item.ctx.data === 'string') {
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
const {_dataEncoding: _, ...rest} = item.ctx;
|
const {_dataEncoding: _, ...rest} = item.ctx;
|
||||||
|
|||||||
@@ -168,6 +168,20 @@
|
|||||||
display: none !important;
|
display: none !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Hide bottom notification / popup bar */
|
||||||
|
[class*="fixed"][class*="bottom-"],
|
||||||
|
[class*="absolute"][class*="bottom-"],
|
||||||
|
[class*="snackbar"],
|
||||||
|
[class*="toast"],
|
||||||
|
[class*="notification"],
|
||||||
|
[class*="bottom-bar"],
|
||||||
|
[class*="status-bar"],
|
||||||
|
[class*="statusbar"],
|
||||||
|
footer,
|
||||||
|
[class*="footer"] {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
[data-epdf-i="open-document"],
|
[data-epdf-i="open-document"],
|
||||||
[data-epdf-i="close-document"],
|
[data-epdf-i="close-document"],
|
||||||
button[title="Open Document"],
|
button[title="Open Document"],
|
||||||
|
|||||||
Reference in New Issue
Block a user