From 6c8a9073258faba17618c2ed82d9306ac8b5266a Mon Sep 17 00:00:00 2001 From: brios <127139797+balazs-szucs@users.noreply.github.com> Date: Wed, 8 Apr 2026 10:44:03 +0200 Subject: [PATCH] feat(pdf): move ebook reader to embedpdf, add bookmarks, remove old pdf.js stuff (#393) * feat(pdf): move ebook reader to embedpdf, add bookmarks, remove old pdf.js stuff * feat(pdf): add page number support for bookmarks and enhance mobile navigation * feat(pdf): implement document ID tracking for search functionality * feat(pdf): add page number column to book marks and update unique index * feat(pdf): enhance annotation handling and improve search result scrolling * feat(pdf): improve layout handling and enhance resize observer functionality * feat(pdf): improve document viewer initialization and improve close button styling * fix(pdf): remove 'form' from disabled categories * feat(pdf): add pan mode functionality and enhance sidebar layout * feat(pdf): improve book viewer initialization with enhanced element detection * feat(pdf): add link handling to text selection and improve popup actions * feat(pdf): enhance link detection and improve selection handling in event service * feat(pdf): improve accessibility and improve resource management in PDF viewer * feat(pdf): add resize observer for improved layout handling * feat(pdf): error handling and improve navigation in PDF reader --- .../java/org/booklore/model/dto/BookMark.java | 1 + .../model/dto/CreateBookMarkRequest.java | 12 + .../model/dto/UpdateBookMarkRequest.java | 3 + .../booklore/model/entity/BookMarkEntity.java | 4 + .../repository/BookMarkRepository.java | 6 + .../service/book/BookMarkService.java | 26 + .../V136__Add_page_number_to_book_marks.sql | 3 + .../src/app/features/book/model/book.model.ts | 5 +- .../ebook-reader/core/event.service.spec.ts | 30 + .../ebook-reader/core/event.service.ts | 46 +- .../ebook-reader/ebook-reader.component.html | 1 + .../ebook-reader/ebook-reader.component.ts | 20 +- .../features/selection/selection.service.ts | 12 +- .../ebook-reader/shared/icon.component.ts | 7 +- .../shared/selection-popup.component.html | 7 + .../shared/selection-popup.component.ts | 9 +- .../components/pdf-sidebar.component.html | 141 ++ .../components/pdf-sidebar.component.scss | 478 +++++++ .../components/pdf-sidebar.component.ts | 104 ++ .../pdf-reader/pdf-reader.component.html | 368 +++++- .../pdf-reader/pdf-reader.component.scss | 733 +++++------ .../pdf-reader/pdf-reader.component.ts | 1165 +++++++++++++---- .../services/embedpdf-book.service.ts | 669 ++++++++++ .../services/pdf-bookmark.service.ts | 117 ++ .../pdf-reader/utils/annotation-converter.ts | 248 ++++ .../app/shared/service/book-mark.service.ts | 3 + frontend/src/assets/embedpdf-frame.html | 130 +- frontend/src/i18n/en/reader-ebook.json | 2 + frontend/src/i18n/en/reader-pdf.json | 55 +- 29 files changed, 3681 insertions(+), 724 deletions(-) create mode 100644 booklore-api/src/main/resources/db/migration/V136__Add_page_number_to_book_marks.sql create mode 100644 frontend/src/app/features/readers/pdf-reader/components/pdf-sidebar.component.html create mode 100644 frontend/src/app/features/readers/pdf-reader/components/pdf-sidebar.component.scss create mode 100644 frontend/src/app/features/readers/pdf-reader/components/pdf-sidebar.component.ts create mode 100644 frontend/src/app/features/readers/pdf-reader/services/embedpdf-book.service.ts create mode 100644 frontend/src/app/features/readers/pdf-reader/services/pdf-bookmark.service.ts create mode 100644 frontend/src/app/features/readers/pdf-reader/utils/annotation-converter.ts diff --git a/booklore-api/src/main/java/org/booklore/model/dto/BookMark.java b/booklore-api/src/main/java/org/booklore/model/dto/BookMark.java index 151e36adf..d286a35ab 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/BookMark.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/BookMark.java @@ -18,6 +18,7 @@ public class BookMark { private String cfi; // For EPUB bookmarks private Long positionMs; // For audiobook bookmarks private Integer trackIndex; // For folder-based audiobooks + private Integer pageNumber; // For PDF bookmarks private String title; private String color; private String notes; diff --git a/booklore-api/src/main/java/org/booklore/model/dto/CreateBookMarkRequest.java b/booklore-api/src/main/java/org/booklore/model/dto/CreateBookMarkRequest.java index 038050c4b..f0a78bea3 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/CreateBookMarkRequest.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/CreateBookMarkRequest.java @@ -1,5 +1,6 @@ package org.booklore.model.dto; +import jakarta.validation.constraints.Min; import jakarta.validation.constraints.NotNull; import lombok.AllArgsConstructor; import lombok.Builder; @@ -21,6 +22,10 @@ public class CreateBookMarkRequest { private Long positionMs; private Integer trackIndex; + // For PDF bookmarks + @Min(value = 1, message = "Page number must be at least 1") + private Integer pageNumber; + private String title; /** @@ -29,4 +34,11 @@ public class CreateBookMarkRequest { public boolean isAudiobookBookmark() { return positionMs != null; } + + /** + * Check if this is a PDF bookmark (has pageNumber, no cfi or positionMs) + */ + public boolean isPdfBookmark() { + return pageNumber != null && cfi == null && positionMs == null; + } } diff --git a/booklore-api/src/main/java/org/booklore/model/dto/UpdateBookMarkRequest.java b/booklore-api/src/main/java/org/booklore/model/dto/UpdateBookMarkRequest.java index b73c05bae..1b876c6d4 100644 --- a/booklore-api/src/main/java/org/booklore/model/dto/UpdateBookMarkRequest.java +++ b/booklore-api/src/main/java/org/booklore/model/dto/UpdateBookMarkRequest.java @@ -30,4 +30,7 @@ public class UpdateBookMarkRequest { @Min(value = 1, message = "Priority must be at least 1") @Max(value = 5, message = "Priority must not exceed 5") private Integer priority; + + @Min(value = 1, message = "Page number must be at least 1") + private Integer pageNumber; } \ No newline at end of file diff --git a/booklore-api/src/main/java/org/booklore/model/entity/BookMarkEntity.java b/booklore-api/src/main/java/org/booklore/model/entity/BookMarkEntity.java index f30b3b506..ae92bd800 100644 --- a/booklore-api/src/main/java/org/booklore/model/entity/BookMarkEntity.java +++ b/booklore-api/src/main/java/org/booklore/model/entity/BookMarkEntity.java @@ -45,6 +45,10 @@ public class BookMarkEntity { @Column(name = "track_index") private Integer trackIndex; + // For PDF bookmarks + @Column(name = "page_number") + private Integer pageNumber; + @Column(name = "title") private String title; diff --git a/booklore-api/src/main/java/org/booklore/repository/BookMarkRepository.java b/booklore-api/src/main/java/org/booklore/repository/BookMarkRepository.java index 609868aa9..ecf5582f9 100644 --- a/booklore-api/src/main/java/org/booklore/repository/BookMarkRepository.java +++ b/booklore-api/src/main/java/org/booklore/repository/BookMarkRepository.java @@ -27,6 +27,12 @@ public interface BookMarkRepository extends JpaRepository "AND ((:trackIndex IS NULL AND b.trackIndex IS NULL) OR b.trackIndex = :trackIndex)") boolean existsByPositionMsNearAndBookIdAndUserId(@Param("positionMs") Long positionMs, @Param("trackIndex") Integer trackIndex, @Param("bookId") Long bookId, @Param("userId") Long userId); + // PDF bookmark duplicate check (exact page match) + boolean existsByPageNumberAndBookIdAndUserId(Integer pageNumber, Long bookId, Long userId); + + @Query("SELECT COUNT(b) > 0 FROM BookMarkEntity b WHERE b.pageNumber = :pageNumber AND b.bookId = :bookId AND b.userId = :userId AND b.id != :excludeId") + boolean existsByPageNumberAndBookIdAndUserIdExcludeId(@Param("pageNumber") Integer pageNumber, @Param("bookId") Long bookId, @Param("userId") Long userId, @Param("excludeId") Long excludeId); + // New: count bookmarks per book long countByBookIdAndUserId(Long bookId, Long userId); diff --git a/booklore-api/src/main/java/org/booklore/service/book/BookMarkService.java b/booklore-api/src/main/java/org/booklore/service/book/BookMarkService.java index a583751de..6bcfc717a 100644 --- a/booklore-api/src/main/java/org/booklore/service/book/BookMarkService.java +++ b/booklore-api/src/main/java/org/booklore/service/book/BookMarkService.java @@ -56,6 +56,8 @@ public class BookMarkService { // Validate no duplicate based on bookmark type if (request.isAudiobookBookmark()) { validateNoDuplicateAudiobookBookmark(request.getPositionMs(), request.getTrackIndex(), request.getBookId(), userId); + } else if (request.isPdfBookmark()) { + validateNoDuplicatePdfBookmark(request.getPageNumber(), request.getBookId(), userId); } else if (request.getCfi() != null) { validateNoDuplicateBookmark(request.getCfi(), request.getBookId(), userId); } @@ -64,6 +66,7 @@ public class BookMarkService { .cfi(request.getCfi()) .positionMs(request.getPositionMs()) .trackIndex(request.getTrackIndex()) + .pageNumber(request.getPageNumber()) .title(request.getTitle()) .book(findBook(request.getBookId())) .user(findUser(userId)) @@ -83,6 +86,11 @@ public class BookMarkService { validateNoDuplicateBookmark(request.getCfi(), bookmark.getBookId(), bookmark.getUserId(), bookmarkId); } + // Validate page-number uniqueness if page number is being updated + if (request.getPageNumber() != null) { + validateNoDuplicatePdfBookmark(request.getPageNumber(), bookmark.getBookId(), bookmark.getUserId(), bookmarkId); + } + applyUpdates(bookmark, request); log.info("Updating bookmark {}", bookmarkId); @@ -144,11 +152,29 @@ public class BookMarkService { } } + /** + * Validate no duplicate PDF bookmark exists for the exact page number. + */ + private void validateNoDuplicatePdfBookmark(Integer pageNumber, Long bookId, Long userId) { + validateNoDuplicatePdfBookmark(pageNumber, bookId, userId, null); + } + + private void validateNoDuplicatePdfBookmark(Integer pageNumber, Long bookId, Long userId, Long excludeBookmarkId) { + boolean exists = (excludeBookmarkId == null) + ? bookMarkRepository.existsByPageNumberAndBookIdAndUserId(pageNumber, bookId, userId) + : bookMarkRepository.existsByPageNumberAndBookIdAndUserIdExcludeId(pageNumber, bookId, userId, excludeBookmarkId); + + if (exists) { + throw new APIException("A bookmark already exists on this page", HttpStatus.CONFLICT); + } + } + private void applyUpdates(BookMarkEntity bookmark, UpdateBookMarkRequest request) { Optional.ofNullable(request.getTitle()).ifPresent(bookmark::setTitle); Optional.ofNullable(request.getCfi()).ifPresent(bookmark::setCfi); Optional.ofNullable(request.getColor()).ifPresent(bookmark::setColor); Optional.ofNullable(request.getNotes()).ifPresent(bookmark::setNotes); Optional.ofNullable(request.getPriority()).ifPresent(bookmark::setPriority); + Optional.ofNullable(request.getPageNumber()).ifPresent(bookmark::setPageNumber); } } diff --git a/booklore-api/src/main/resources/db/migration/V136__Add_page_number_to_book_marks.sql b/booklore-api/src/main/resources/db/migration/V136__Add_page_number_to_book_marks.sql new file mode 100644 index 000000000..97c9bbbfe --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V136__Add_page_number_to_book_marks.sql @@ -0,0 +1,3 @@ +ALTER TABLE book_marks ADD COLUMN page_number INT NULL; +CREATE UNIQUE INDEX uq_book_marks_user_book_page_number + ON book_marks (user_id, book_id, page_number); diff --git a/frontend/src/app/features/book/model/book.model.ts b/frontend/src/app/features/book/model/book.model.ts index d3386d6a2..d25536439 100644 --- a/frontend/src/app/features/book/model/book.model.ts +++ b/frontend/src/app/features/book/model/book.model.ts @@ -1,7 +1,6 @@ import {Shelf} from './shelf.model'; import {CbxBackgroundColor, CbxFitMode, CbxPageSpread, CbxPageSplitOption, CbxPageViewMode, CbxScrollMode, NewPdfReaderSetting} from '../../settings/user-management/user.service'; import {BookReview} from '../components/book-reviews/book-review-service'; -import {ZoomType} from 'ngx-extended-pdf-viewer'; export type BookType = "PDF" | "EPUB" | "CBX" | "FB2" | "MOBI" | "AZW3" | "AUDIOBOOK"; @@ -303,8 +302,8 @@ export interface MetadataUpdateWrapper { } export interface PdfViewerSetting { - zoom: ZoomType; - spread: 'off' | 'even' | 'odd'; + zoom: string; + spread: 'none' | 'even' | 'odd'; isDarkTheme?: boolean; } diff --git a/frontend/src/app/features/readers/ebook-reader/core/event.service.spec.ts b/frontend/src/app/features/readers/ebook-reader/core/event.service.spec.ts index 0e2f78af7..96594253b 100644 --- a/frontend/src/app/features/readers/ebook-reader/core/event.service.spec.ts +++ b/frontend/src/app/features/readers/ebook-reader/core/event.service.spec.ts @@ -12,12 +12,18 @@ interface TestView extends HTMLDivElement { interface RangeLike { toString: () => string; getBoundingClientRect: () => DOMRect; + commonAncestorContainer: Node; + startContainer: Node; + endContainer: Node; + intersectsNode: (node: Node) => boolean; } interface TestSelection { isCollapsed: boolean; rangeCount: number; getRangeAt: (index: number) => RangeLike; + anchorNode: Node | null; + focusNode: Node | null; } interface PrivateReaderEventService { @@ -138,7 +144,13 @@ describe('ReaderEventService', () => { getRangeAt: () => ({ toString: () => '', getBoundingClientRect: () => new DOMRect(0, 0, 0, 0), + commonAncestorContainer: doc.body, + startContainer: doc.body, + endContainer: doc.body, + intersectsNode: () => false, }), + anchorNode: null, + focusNode: null, }; defaultView = { frameElement: iframe, @@ -296,11 +308,17 @@ describe('ReaderEventService', () => { const selectedRange: RangeLike = { toString: () => 'Highlighted text', getBoundingClientRect: () => new DOMRect(20, 15, 80, 20), + commonAncestorContainer: doc.body, + startContainer: doc.body, + endContainer: doc.body, + intersectsNode: () => false, }; installSelection(doc, { isCollapsed: false, rangeCount: 1, getRangeAt: () => selectedRange, + anchorNode: doc.body, + focusNode: doc.body, }); getContents.mockReturnValue([{index: 7, doc}]); getCFI.mockReturnValue('epubcfi(/6/2!/4/2:0)'); @@ -324,11 +342,17 @@ describe('ReaderEventService', () => { const emptyRange: RangeLike = { toString: () => ' ', getBoundingClientRect: () => new DOMRect(0, 0, 0, 0), + commonAncestorContainer: doc.body, + startContainer: doc.body, + endContainer: doc.body, + intersectsNode: () => false, }; installSelection(doc, { isCollapsed: false, rangeCount: 1, getRangeAt: () => emptyRange, + anchorNode: doc.body, + focusNode: doc.body, }); privateService.handleSelectionChange(doc); @@ -338,11 +362,17 @@ describe('ReaderEventService', () => { const visibleRange: RangeLike = { toString: () => 'Visible note', getBoundingClientRect: () => new DOMRect(10, 10, 60, 25), + commonAncestorContainer: doc.body, + startContainer: doc.body, + endContainer: doc.body, + intersectsNode: () => false, }; installSelection(doc, { isCollapsed: false, rangeCount: 1, getRangeAt: () => visibleRange, + anchorNode: doc.body, + focusNode: doc.body, }); getContents.mockReturnValue([{index: 3, doc}]); getCFI.mockReturnValueOnce(null).mockReturnValueOnce('epubcfi(/6/8!/4/2:0)'); diff --git a/frontend/src/app/features/readers/ebook-reader/core/event.service.ts b/frontend/src/app/features/readers/ebook-reader/core/event.service.ts index 1da9eeb1d..4cd46c39d 100644 --- a/frontend/src/app/features/readers/ebook-reader/core/event.service.ts +++ b/frontend/src/app/features/readers/ebook-reader/core/event.service.ts @@ -7,6 +7,7 @@ export interface TextSelection { cfi: string; range: Range; index: number; + linkUrl?: string; } interface PopupPosition { @@ -476,15 +477,58 @@ export class ReaderEventService { popupX = Math.max(100, Math.min(popupX, window.innerWidth - 150)); + const linkUrl = this.getLinkUrl(range, selection); + this.eventSubject.next({ type: 'text-selected', - detail: {text, cfi, range, index}, + detail: {text, cfi, range, index, linkUrl}, popupPosition: {x: popupX, y: popupY, showBelow} }); } }, 10); } + private getLinkUrl(range: Range, selection: Selection): string | undefined { + const getLinkFromNode = (node: Node | null | undefined): string | undefined => { + let current: Node | null | undefined = node; + while (current && current.nodeType !== Node.DOCUMENT_NODE) { + if (current.nodeType === Node.ELEMENT_NODE) { + const element = current as HTMLElement; + if (element.tagName?.toLowerCase() === 'a') { + return element.getAttribute('href') || undefined; + } + const closestLink = typeof element.closest === 'function' ? element.closest('a') : null; + if (closestLink?.getAttribute('href')) { + return closestLink.getAttribute('href')!; + } + } + current = current.parentNode; + } + return undefined; + }; + + // Check ancestors and self for common ancestor, start, end, anchor and focus nodes + let linkUrl = getLinkFromNode(range.commonAncestorContainer) || + getLinkFromNode(range.startContainer) || + getLinkFromNode(range.endContainer) || + getLinkFromNode(selection.anchorNode) || + getLinkFromNode(selection.focusNode); + + // If still not found, check if the range contains any links + if (!linkUrl && range.commonAncestorContainer?.nodeType === Node.ELEMENT_NODE) { + const containerElement = range.commonAncestorContainer as HTMLElement; + // Find all links in the container + if (typeof containerElement.querySelectorAll === 'function') { + const links = Array.from(containerElement.querySelectorAll('a')); + // Find the first link that intersects with the selection range + const internalLink = links.find(link => typeof range.intersectsNode === 'function' && range.intersectsNode(link)); + linkUrl = internalLink?.getAttribute('href') || undefined; + } + } + + return linkUrl; + } + private handleIframeClickMessage(data: IframeClickMessage): void { if (!this.view) return; diff --git a/frontend/src/app/features/readers/ebook-reader/ebook-reader.component.html b/frontend/src/app/features/readers/ebook-reader/ebook-reader.component.html index 81a42780f..394e65593 100644 --- a/frontend/src/app/features/readers/ebook-reader/ebook-reader.component.html +++ b/frontend/src/app/features/readers/ebook-reader/ebook-reader.component.html @@ -73,6 +73,7 @@ [showBelow]="selectionState().showBelow" [overlappingAnnotationId]="selectionState().overlappingAnnotationId" [selectedText]="selectionState().selectedText" + [linkUrl]="selectionState().linkUrl" (action)="handleSelectionAction($event)" > diff --git a/frontend/src/app/features/readers/ebook-reader/ebook-reader.component.ts b/frontend/src/app/features/readers/ebook-reader/ebook-reader.component.ts index 54d7cf421..36e83ca7e 100644 --- a/frontend/src/app/features/readers/ebook-reader/ebook-reader.component.ts +++ b/frontend/src/app/features/readers/ebook-reader/ebook-reader.component.ts @@ -345,12 +345,12 @@ export class EbookReaderComponent implements OnInit, OnDestroy { this.toggleImmersiveMode(); break; case 'go-first-section': - this.viewManager.goToSection(0).subscribe(); + this.viewManager.goToSection(0).pipe(catchError(() => of(undefined))).subscribe(); break; case 'go-last-section': { const s = this.progressService.currentProgressData?.section; if (s && s.total > 0) { - this.viewManager.goToSection(s.total - 1).subscribe(); + this.viewManager.goToSection(s.total - 1).pipe(catchError(() => of(undefined))).subscribe(); } break; } @@ -429,7 +429,10 @@ export class EbookReaderComponent implements OnInit, OnDestroy { onProgressChange(fraction: number): void { this.viewManager.goToFraction(fraction) - .pipe(takeUntil(this.destroy$)) + .pipe( + takeUntil(this.destroy$), + catchError(() => of(undefined)) + ) .subscribe(); } @@ -481,6 +484,17 @@ export class EbookReaderComponent implements OnInit, OnDestroy { handleSelectionAction(action: TextSelectionAction): void { if (action.type === 'note') { this.noteService.openNewNoteDialog(); + } else if (action.type === 'go-to-link') { + const linkUrl = this.selectionState().linkUrl; + if (linkUrl) { + this.viewManager.goTo(linkUrl) + .pipe( + takeUntil(this.destroy$), + catchError(() => of(undefined)) + ) + .subscribe(); + } + this.selectionService.handleAction(action); } else { this.selectionService.handleAction(action); } diff --git a/frontend/src/app/features/readers/ebook-reader/features/selection/selection.service.ts b/frontend/src/app/features/readers/ebook-reader/features/selection/selection.service.ts index 7dc345253..71a5eb5a3 100644 --- a/frontend/src/app/features/readers/ebook-reader/features/selection/selection.service.ts +++ b/frontend/src/app/features/readers/ebook-reader/features/selection/selection.service.ts @@ -14,6 +14,7 @@ export interface SelectionState { showBelow: boolean; overlappingAnnotationId: number | null; selectedText: string; + linkUrl?: string; } export interface SelectionDetail { @@ -21,6 +22,7 @@ export interface SelectionDetail { cfi: string; range: Range; index: number; + linkUrl?: string; } @Injectable() @@ -48,7 +50,8 @@ export class ReaderSelectionService { position: {x: 0, y: 0}, showBelow: false, overlappingAnnotationId: null, - selectedText: '' + selectedText: '', + linkUrl: undefined }; private readonly _state = signal(this.defaultState); @@ -121,6 +124,10 @@ export class ReaderSelectionService { action.color || '#FFFF00', action.style || 'highlight' ); + } else if (action.type === 'go-to-link' && this.currentSelection?.linkUrl) { + // Handled by component, but we clear state here + this.clearPreview(); + this.viewManager.clearSelection(); } this.currentSelection = null; @@ -283,7 +290,8 @@ export class ReaderSelectionService { position: this._position, showBelow: this._showBelow, overlappingAnnotationId: this._overlappingAnnotationId, - selectedText: this.currentSelection?.text || '' + selectedText: this.currentSelection?.text || '', + linkUrl: this.currentSelection?.linkUrl }); } diff --git a/frontend/src/app/features/readers/ebook-reader/shared/icon.component.ts b/frontend/src/app/features/readers/ebook-reader/shared/icon.component.ts index 6f0f7ecb9..d297eff92 100644 --- a/frontend/src/app/features/readers/ebook-reader/shared/icon.component.ts +++ b/frontend/src/app/features/readers/ebook-reader/shared/icon.component.ts @@ -35,7 +35,8 @@ export type ReaderIconName = | 'long-strip' | 'direction-ltr' | 'direction-rtl' - | 'magnifier'; + | 'magnifier' + | 'link'; interface IconPath { d: string; @@ -199,6 +200,10 @@ const ICONS: Record = { {d: 'M21 21l-5-5'}, {d: 'M7,10 L13,10', type: 'line'}, {d: 'M10,7 L10,13', type: 'line'} + ], + 'link': [ + {d: 'M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71'}, + {d: 'M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71'} ] }; diff --git a/frontend/src/app/features/readers/ebook-reader/shared/selection-popup.component.html b/frontend/src/app/features/readers/ebook-reader/shared/selection-popup.component.html index a1ef641ca..650266cd6 100644 --- a/frontend/src/app/features/readers/ebook-reader/shared/selection-popup.component.html +++ b/frontend/src/app/features/readers/ebook-reader/shared/selection-popup.component.html @@ -10,6 +10,13 @@ + @if (linkUrl) { +
+ + } +
+ + + + + + +
+ @switch (activeTab()) { + @case ('contents') { + @if (outline().length > 0) { +
    + @for (item of outline(); track item.title) { + + } +
+ + +
  • + + @if (item.children?.length) { +
      + @for (child of item.children; track child.title) { + + } +
    + } +
  • +
    + } @else { +
    + +

    {{ t('noContents') }}

    +
    + } + } + + @case ('bookmarks') { + @if (bookmarks().length > 0) { +
      + @for (bookmark of bookmarks(); track bookmark.id) { +
    • +
      + {{ bookmark.title }} + {{ t('page') }} {{ bookmark.pageNumber }} +
      + +
    • + } +
    + } @else { +
    + +

    {{ t('noBookmarks') }}

    + {{ t('bookmarkHint') }} +
    + } + } + + @case ('annotations') { + @if (annotations().length > 0) { +
      + @for (annotation of annotations(); track annotation.id) { +
    • + @if (annotation.color) { +
      + } +
      +
      + {{ t('page') }} {{ annotation.pageIndex + 1 }} · {{ annotation.type }} +
      + @if (annotation.text) { +

      "{{ annotation.text }}"

      + } +
      + +
    • + } +
    + } @else { +
    + +

    {{ t('noAnnotations') }}

    + {{ t('annotationHint') }} +
    + } + } + } +
    + + +} + diff --git a/frontend/src/app/features/readers/pdf-reader/components/pdf-sidebar.component.scss b/frontend/src/app/features/readers/pdf-reader/components/pdf-sidebar.component.scss new file mode 100644 index 000000000..650a90d57 --- /dev/null +++ b/frontend/src/app/features/readers/pdf-reader/components/pdf-sidebar.component.scss @@ -0,0 +1,478 @@ +$sidebar-width: 320px; +$sidebar-bg: #141414; +$sidebar-bg-light: #fff; +$text-primary: #fff; +$text-primary-light: #1a1a1a; +$text-secondary: rgb(255 255 255 / 70%); +$text-secondary-light: rgb(0 0 0 / 60%); +$text-muted: rgb(255 255 255 / 45%); +$text-muted-light: rgb(0 0 0 / 40%); +$border-color: rgb(255 255 255 / 10%); +$border-color-light: rgb(0 0 0 / 8%); +$hover-bg: rgb(255 255 255 / 6%); +$hover-bg-light: rgb(0 0 0 / 4%); +$active-bg: #3b82f6; +$active-color: #3b82f6; +$transition-base: 250ms cubic-bezier(0.4, 0, 0.2, 1); +$transition-fast: 150ms ease; + +:host { + display: block; +} + +.sidebar-overlay { + position: fixed; + inset: 0; + background: rgb(0 0 0 / 60%); + z-index: 12000; + animation: fade-in 300ms ease; + + &.closing { + animation: fade-out 300ms ease forwards; + } +} + +.sidebar { + position: fixed; + top: 0; + left: 0; + bottom: 0; + width: $sidebar-width; + background: $sidebar-bg; + color: $text-primary; + display: flex; + flex-direction: column; + box-shadow: 12px 0 32px rgb(0 0 0 / 40%); + animation: slide-in $transition-base; + overflow: hidden; + border-right: 1px solid $border-color; + + &.closing { + animation: slide-out $transition-base forwards; + } + + .sidebar-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 20px 24px; + background: rgb(255 255 255 / 2%); + border-bottom: 1px solid $border-color; + flex-shrink: 0; + + .sidebar-title { + font-size: 11px; + font-weight: 700; + color: $text-muted; + margin: 0; + text-transform: uppercase; + letter-spacing: 0.12em; + } + + .sidebar-close-btn { + background: none; + border: none; + color: $text-muted; + cursor: pointer; + padding: 6px; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + transition: all $transition-fast; + + &:hover { + color: $text-primary; + background: $hover-bg; + } + } + } +} + +.tabs { + display: flex; + padding: 0 12px; + background: rgb(255 255 255 / 1%); + border-bottom: 1px solid $border-color; + gap: 4px; +} + +.tab { + flex: 1; + display: flex; + align-items: center; + justify-content: center; + gap: 4px; + padding: 14px 2px; + background: none; + border: none; + position: relative; + color: $text-secondary; + font-size: 12px; + font-weight: 600; + cursor: pointer; + transition: all $transition-fast; + min-width: 0; + + span { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + &::after { + content: ''; + position: absolute; + bottom: 0; + left: 12px; + right: 12px; + height: 3px; + background: transparent; + border-radius: 3px 3px 0 0; + transition: all $transition-fast; + } + + &:hover { + color: $text-primary; + background: rgb(255 255 255 / 3%); + } + + &.active { + color: $active-color; + + &::after { + background: $active-color; + box-shadow: 0 -4px 10px rgb(59 130 246 / 40%); + } + } + + .tab-icon { + font-size: 14px; + opacity: 0.8; + flex-shrink: 0; + } +} + +.badge { + background: rgb(59 130 246 / 15%); + color: $active-color; + font-size: 9px; + font-weight: 700; + padding: 1px 6px; + border-radius: 20px; + margin-left: 2px; + flex-shrink: 0; +} + +.content { + flex: 1; + overflow-y: auto; + padding: 12px 0; + overscroll-behavior: contain; + + &::-webkit-scrollbar { + width: 5px; + } + + &::-webkit-scrollbar-track { + background: transparent; + } + + &::-webkit-scrollbar-thumb { + background: rgb(255 255 255 / 15%); + border-radius: 10px; + + &:hover { + background: rgb(255 255 255 / 25%); + } + } +} + +// --- Outline / Chapter list --- + +.chapter-list, +.subchapter-list { + list-style: none; + margin: 0; + padding: 0; +} + +.chapter-row { + display: flex; + align-items: center; + justify-content: space-between; + width: 100%; + padding: 12px 24px 12px calc(24px + var(--depth, 0) * 20px); + background: none; + border: none; + color: $text-secondary; + font-size: 13.5px; + font-weight: 500; + cursor: pointer; + transition: all $transition-fast; + text-align: left; + line-height: 1.4; + + &:hover { + background: $hover-bg; + color: $text-primary; + } + + .chapter-label { + flex: 1; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .chapter-page { + flex-shrink: 0; + font-size: 11px; + font-weight: 700; + color: $text-muted; + margin-left: 12px; + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + } +} + +// --- Item lists (bookmarks, annotations) --- + +.item-list { + list-style: none; + margin: 0; + padding: 0 12px; + display: flex; + flex-direction: column; + gap: 4px; +} + +.list-item { + display: flex; + align-items: center; + gap: 12px; + padding: 14px 16px; + border-radius: 12px; + cursor: pointer; + background: rgb(255 255 255 / 1%); + border: 1px solid transparent; + transition: all $transition-fast; + + &:hover { + background: $hover-bg; + border-color: $border-color; + transform: translateY(-1px); + + .delete-btn { + opacity: 1; + transform: translateX(0); + } + } + + &.highlight-item { + padding-left: 0; + overflow: hidden; + + .highlight-bar { + width: 4px; + margin-right: 12px; + flex-shrink: 0; + align-self: stretch; + } + + .item-content { + padding: 2px 0; + } + } +} + +.item-content { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 4px; +} + +.item-title { + font-size: 14px; + font-weight: 600; + color: $text-primary; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.item-meta { + font-size: 11px; + font-weight: 600; + color: $text-muted; + text-transform: uppercase; + letter-spacing: 0.02em; +} + +.highlight-text { + font-size: 13px; + line-height: 1.5; + color: $text-secondary; + font-style: italic; + display: -webkit-box; + -webkit-line-clamp: 2; + line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; + overflow-wrap: break-word; +} + +.delete-btn { + background: rgb(239 68 68 / 10%); + border: none; + color: #ef4444; + padding: 8px; + border-radius: 8px; + cursor: pointer; + opacity: 0; + transform: translateX(8px); + transition: all $transition-fast; + flex-shrink: 0; + + &:hover { + background: #ef4444; + color: white; + box-shadow: 0 4px 12px rgb(239 68 68 / 30%); + } +} + +// --- Empty state --- + +.empty-state { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 64px 32px; + text-align: center; + + .empty-icon { + color: $text-muted; + margin-bottom: 20px; + opacity: 0.3; + filter: drop-shadow(0 8px 16px rgb(0 0 0 / 20%)); + } + + p { + font-size: 15px; + font-weight: 600; + color: $text-secondary; + margin: 0 0 8px; + } + + .empty-hint { + font-size: 13px; + color: $text-muted; + line-height: 1.6; + } +} + +// --- Animations --- + +@keyframes fade-in { + from { opacity: 0; } + to { opacity: 1; } +} + +@keyframes fade-out { + from { opacity: 1; } + to { opacity: 0; } +} + +@keyframes slide-in { + from { transform: translateX(-100%); } + to { transform: translateX(0); } +} + +@keyframes slide-out { + from { transform: translateX(0); } + to { transform: translateX(-100%); } +} + +// --- Light Theme Support --- + +:host-context([data-color-scheme="light"]) { + .sidebar-overlay { + background: rgb(0 0 0 / 20%); + } + + .sidebar { + background: $sidebar-bg-light; + color: $text-primary-light; + border-right-color: $border-color-light; + box-shadow: 12px 0 32px rgb(0 0 0 / 10%); + + .sidebar-header { + background: rgb(0 0 0 / 1%); + border-bottom-color: $border-color-light; + + .sidebar-title { + color: $text-muted-light; + } + } + } + + .tabs { + border-bottom-color: $border-color-light; + } + + .tab { + color: $text-secondary-light; + + &:hover { + background: $hover-bg-light; + color: $text-primary-light; + } + } + + .tab-item:hover, .chapter-row:hover { + background: $hover-bg-light; + } + + .chapter-row { + color: $text-secondary-light; + + &:hover { + color: $text-primary-light; + } + + .chapter-page { + color: $text-muted-light; + } + } + + .list-item { + background: rgb(0 0 0 / 2%); + + &:hover { + background: $hover-bg-light; + border-color: $border-color-light; + } + } + + .item-title { + color: $text-primary-light; + } + + .item-meta { + color: $text-muted-light; + } + + .highlight-text { + color: $text-secondary-light; + } + + .content::-webkit-scrollbar-thumb { + background: rgb(0 0 0 / 10%); + + &:hover { + background: rgb(0 0 0 / 20%); + } + } +} diff --git a/frontend/src/app/features/readers/pdf-reader/components/pdf-sidebar.component.ts b/frontend/src/app/features/readers/pdf-reader/components/pdf-sidebar.component.ts new file mode 100644 index 000000000..21ede42d4 --- /dev/null +++ b/frontend/src/app/features/readers/pdf-reader/components/pdf-sidebar.component.ts @@ -0,0 +1,104 @@ +import {Component, DestroyRef, inject, input, output, signal, effect} from '@angular/core'; +import {NgTemplateOutlet} from '@angular/common'; +import {TranslocoDirective} from '@jsverse/transloco'; +import {ReaderIconComponent} from '../../ebook-reader/shared/icon.component'; +import {BookMark} from '../../../../shared/service/book-mark.service'; +import {PdfOutlineItem} from '../services/embedpdf-book.service'; + +export type PdfSidebarTab = 'contents' | 'bookmarks' | 'annotations'; + +export interface PdfAnnotationListItem { + id: string; + pageIndex: number; + type: string; + color?: string; + text?: string; +} + +@Component({ + selector: 'app-pdf-sidebar', + standalone: true, + imports: [TranslocoDirective, NgTemplateOutlet, ReaderIconComponent], + templateUrl: './pdf-sidebar.component.html', + styleUrl: './pdf-sidebar.component.scss', +}) +export class PdfSidebarComponent { + private readonly destroyRef = inject(DestroyRef); + private closeAnimationTimeout: ReturnType | null = null; + + isOpen = input.required(); + outline = input([]); + bookmarks = input([]); + annotations = input([]); + + closed = output(); + navigateToPage = output(); + deleteBookmark = output(); + deleteAnnotation = output(); + + readonly activeTab = signal('contents'); + readonly visible = signal(false); + readonly closing = signal(false); + + constructor() { + effect(() => { + if (this.isOpen()) { + this.clearCloseAnimation(); + this.visible.set(true); + this.closing.set(false); + } else if (this.visible()) { + this.closeWithAnimation(); + } + }); + + this.destroyRef.onDestroy(() => this.clearCloseAnimation()); + } + + private closeWithAnimation(): void { + this.closing.set(true); + this.closeAnimationTimeout = setTimeout(() => { + this.visible.set(false); + this.closing.set(false); + this.closeAnimationTimeout = null; + }, 250); + } + + private clearCloseAnimation(): void { + if (this.closeAnimationTimeout) { + clearTimeout(this.closeAnimationTimeout); + this.closeAnimationTimeout = null; + } + } + + onOverlayClick(): void { + this.closed.emit(); + } + + setActiveTab(tab: PdfSidebarTab): void { + this.activeTab.set(tab); + } + + onOutlineClick(item: PdfOutlineItem): void { + this.navigateToPage.emit(item.pageIndex + 1); + } + + onBookmarkClick(bookmark: BookMark): void { + if (bookmark.pageNumber != null) { + this.navigateToPage.emit(bookmark.pageNumber); + } + } + + onDeleteBookmark(event: MouseEvent, bookmarkId: number): void { + event.stopPropagation(); + this.deleteBookmark.emit(bookmarkId); + } + + onAnnotationClick(annotation: PdfAnnotationListItem): void { + this.navigateToPage.emit(annotation.pageIndex + 1); + } + + onDeleteAnnotation(event: MouseEvent, annotationId: string): void { + event.stopPropagation(); + this.deleteAnnotation.emit(annotationId); + } +} diff --git a/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.html b/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.html index 48ab59edf..34c7d9d37 100644 --- a/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.html +++ b/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.html @@ -16,48 +16,162 @@ } @if (viewerMode === 'document') { - - - @if (isDocViewerInfoVisible) { -
    - {{ 'readerPdf.docViewer.changesSavedInfo' | transloco }} - -
    + } + + @if (isDocViewerInfoVisible) { +
    + {{ 'readerPdf.docViewer.changesSavedInfo' | transloco }} + +
    + } + +
    } -
    - } - - + @if (viewerMode === 'book') { - - - } + +
    +
    + +
    + + {{ bookTitle }} + +
    + +
    + + - -
    -
    - - -
    - {{ bookTitle }} -
    - - -
    - + + + + + + +
    + + + + +
    + + + +
    + + @if (isZoomMenuOpen) { +
    + @for (preset of zoomPresets; track preset.value) { + + } +
    + } +
    + + +
    + + + + + + + +
    + + + + +
    - -
    + + +
    + + +
    + + +
    -
    +
    + + + @if (isToolbarOverflowOpen) { + +
    + + + + +
    + + + + + +
    + } + + + @if (isSearchOpen) { + + } + + +
    + + + + + } diff --git a/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.scss b/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.scss index f5fef1146..0aa90241d 100644 --- a/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.scss +++ b/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.scss @@ -1,6 +1,6 @@ @use 'sass:color'; -/* stylelint-disable selector-id-pattern, selector-class-pattern -- targets ngx-extended-pdf-viewer / pdf.js internals */ +/* stylelint-disable selector-id-pattern, selector-class-pattern */ // Design tokens matching CBX/E-Book readers $header-height: 38px; @@ -28,10 +28,15 @@ $transition-fast: 150ms ease; .pdf-reader-container { position: fixed; inset: 0; - display: flex; - flex-direction: column; + height: 100dvh; background: #1a1a1a; z-index: 900; + overflow: hidden; + box-sizing: border-box; + + * { + box-sizing: border-box; + } } // --- Trigger zones --- @@ -62,10 +67,35 @@ $transition-fast: 150ms ease; } } -// --- Header --- -// Child element styles for .pdf-header-toolbar (positioning is in ::ng-deep #toolbarViewer) +// --- Header toolbar --- .pdf-header-toolbar { + position: fixed; + top: 0; + left: 0; + right: 0; + height: $header-height; + box-sizing: border-box; + padding: 0 16px; + display: flex; + align-items: center; + justify-content: space-between; + z-index: 1002; + background: $gradient-bg; + border-bottom: 1px solid $border-color; + box-shadow: 0 2px 8px rgb(0 0 0 / 30%); + color: #fff; + opacity: 1; + pointer-events: auto; + transform: translateY(0); + transition: opacity 0.25s ease-out, transform 0.25s ease-out; + + &.chrome-hidden { + opacity: 0; + pointer-events: none; + transform: translateY(-100%); + } + .header-left, .header-right { display: flex; @@ -75,40 +105,6 @@ $transition-fast: 150ms ease; flex-shrink: 0; } - .header-right { - // Style zoom toolbar within header - ::ng-deep { - pdf-zoom-toolbar { - display: flex; - align-items: center; - } - - .zoom { - display: flex; - align-items: center; - gap: 2px; - } - - #scaleSelect { - background: rgb(255 255 255 / 8%) !important; - color: #fff !important; - border: 1px solid rgb(255 255 255 / 15%) !important; - border-radius: 4px !important; - padding: 2px 4px !important; - font-size: 12px !important; - cursor: pointer; - height: 26px !important; - max-width: 85px; - appearance: none; - - option { - background: #2d2d2d; - color: #fff; - } - } - } - } - .book-title { position: absolute; left: 50%; @@ -156,46 +152,140 @@ $transition-fast: 150ms ease; background: rgb(239 68 68 / 20%); color: #ef4444; } + + &.annotation-tool-btn.active { + color: $active-color; + background: rgb(74 144 226 / 15%); + } + + &.bookmark-btn.bookmarked { + color: #f59e0b; + } } -// --- Override pdf.js component button styles --- +// --- Search bar --- -::ng-deep .pdf-btn-wrap { - button { - background: none !important; - border: none !important; - color: #fff !important; +.search-bar { + position: fixed; + top: $header-height; + left: 0; + right: 0; + height: 36px; + z-index: 1002; + background: color.adjust(#2d2d2d, $lightness: -3%); + border-bottom: 1px solid $border-color; + display: flex; + align-items: center; + padding: 0 16px; + gap: 8px; + opacity: 1; + transform: translateY(0); + transition: opacity 0.25s ease-out, transform 0.25s ease-out; + + &.chrome-hidden { + opacity: 0; + pointer-events: none; + transform: translateY(-100%); + } + + .search-input-wrapper { + display: flex; + align-items: center; + gap: 6px; + flex: 1; + max-width: 360px; + background: #404040; + border-radius: 4px; + padding: 0 8px; + color: $text-secondary; + } + + .search-input { + flex: 1; + border: none; + background: transparent; + color: $text-primary; + font-size: 13px; + padding: 5px 0; + outline: none; + + &::placeholder { + color: rgb(255 255 255 / 30%); + } + } + + .search-close { + padding: 4px; + } +} + +// --- Zoom menu --- + +.zoom-menu-wrapper { + position: relative; +} + +.zoom-label-btn { + padding: 4px 6px !important; + + .zoom-label { + font-size: 12px; + font-weight: 500; + min-width: 50px; + text-align: center; + } +} + +.zoom-dropdown { + position: absolute; + top: 100%; + left: 50%; + transform: translateX(-50%); + margin-top: 4px; + background: #333; + border: 1px solid $border-color; + border-radius: 6px; + padding: 4px 0; + min-width: 120px; + box-shadow: 0 4px 12px rgb(0 0 0 / 40%); + z-index: 1010; + + .zoom-option { + display: block; + width: 100%; + padding: 6px 16px; + border: none; + background: none; + color: $text-primary; + font-size: 13px; + text-align: left; cursor: pointer; - width: 30px !important; - height: 30px !important; - padding: 0 !important; - border-radius: 6px !important; - display: flex !important; - align-items: center !important; - justify-content: center !important; - transition: background $transition-fast !important; - margin: 0 !important; - box-shadow: none !important; - opacity: 1 !important; + transition: background $transition-fast; &:hover { - background: $hover-bg !important; + background: $hover-bg; } - &.toggled, - &[aria-pressed="true"] { - color: $active-color !important; - background: rgb(74 144 226 / 15%) !important; + &.active { + color: $active-color; + font-weight: 600; } + } +} - span { - display: none !important; - } +// --- Book viewer container --- - &::before { - color: inherit !important; - opacity: 1 !important; - } +.book-viewer-container { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + overflow: hidden; + + embedpdf-container { + width: 100%; + height: 100%; + display: block; } } @@ -448,11 +538,29 @@ $transition-fast: 150ms ease; .embed-close-btn { position: fixed; - top: 4px; - right: 12px; - z-index: 1010; - color: $text-primary; - padding: 7px; + top: 0; + right: 0; + z-index: 11000; + color: #fff; + width: 44px; + height: 38px; + display: flex; + align-items: center; + justify-content: center; + background: #2d2d2d; + border: none; + border-bottom: 1px solid #404040; + cursor: pointer; + padding: 0; + transition: background $transition-fast; + + &:hover { + background: #3a3a3a; + } + + &:active { + background: #444; + } } .doc-viewer-info { @@ -472,7 +580,7 @@ $transition-fast: 150ms ease; border: 1px solid $border-color; box-shadow: 0 2px 8px rgb(0 0 0 / 30%); backdrop-filter: blur(4px); - animation: docViewerInfoFadeIn 0.3s ease-out; + animation: doc-viewer-info-fade-in 0.3s ease-out; .dismiss-btn { background: none; @@ -492,7 +600,7 @@ $transition-fast: 150ms ease; } } -@keyframes docViewerInfoFadeIn { +@keyframes doc-viewer-info-fade-in { from { opacity: 0; transform: translateY(-10px); @@ -505,9 +613,10 @@ $transition-fast: 150ms ease; } #embedpdf-viewer { + position: absolute; + inset: 0; width: 100%; height: 100%; - flex: 1; display: flex; iframe { @@ -570,331 +679,90 @@ $transition-fast: 150ms ease; } } -// --- Override pdf.js viewer inner styles --- +// --- Mobile actions (hidden on desktop) --- -::ng-deep { - // Make pdf viewer fill container - ngx-extended-pdf-viewer { - flex: 1; - display: block; - overflow: hidden; +.mobile-actions { + display: none; + align-items: center; + gap: 2px; +} - #mainContainer { - background: #1a1a1a !important; +// --- Desktop actions --- + +.desktop-actions { + display: flex; + align-items: center; + gap: 2px; +} + +// --- Toolbar overflow menu (mobile) --- + +.toolbar-overflow-backdrop { + position: fixed; + inset: 0; + z-index: 1009; + background: rgb(0 0 0 / 40%); +} + +.toolbar-overflow-menu { + position: fixed; + top: $header-height; + right: 8px; + z-index: 1010; + background: #2d2d2d; + border: 1px solid $border-color; + border-radius: 8px; + padding: 4px 0; + min-width: 200px; + box-shadow: 0 8px 24px rgb(0 0 0 / 50%); + + .overflow-item { + display: flex; + align-items: center; + gap: 10px; + width: 100%; + padding: 10px 16px; + border: none; + background: none; + color: $text-primary; + font-size: 14px; + cursor: pointer; + transition: background $transition-fast; + + &:hover { + background: $hover-bg; } - // Override pdf.js defaults on #toolbarViewer - our custom fixed header - #toolbarViewer { - position: fixed !important; - top: 0 !important; - left: 0 !important; - right: 0 !important; - height: $header-height !important; - min-height: 0 !important; - box-sizing: border-box !important; - padding: 0 16px !important; - display: flex !important; - align-items: center !important; - justify-content: space-between !important; - z-index: 1002 !important; - background: $gradient-bg !important; - border-bottom: 1px solid $border-color !important; - box-shadow: 0 2px 8px rgb(0 0 0 / 30%) !important; - color: #fff !important; - opacity: 1 !important; - pointer-events: auto !important; - transform: translateY(0) !important; - transition: opacity 0.25s ease-out, transform 0.25s ease-out !important; - - &.chrome-hidden { - opacity: 0 !important; - pointer-events: none !important; - transform: translateY(-100%) !important; - } + svg, + app-reader-icon { + flex-shrink: 0; } + } - // Style the annotation editor params toolbars (color picker, thickness, etc.) - .editorParamsToolbar { - position: fixed !important; - top: $header-height !important; - right: 8px !important; - left: auto !important; - z-index: 1003 !important; - background: #2d2d2d !important; - border: 1px solid $border-color !important; - border-radius: 0 0 8px 8px !important; - box-shadow: 0 4px 12px rgb(0 0 0 / 40%) !important; - padding: 8px 12px !important; - color: #fff !important; - min-width: 180px !important; - - .editorParamsToolbarContainer { - display: flex; - flex-direction: column; - gap: 8px; - } - - .editorParamsLabel { - color: $text-secondary !important; - font-size: 12px !important; - } - - .editorParamsSetter { - display: flex; - align-items: center; - gap: 8px; - } - - .editorParamsSlider { - flex: 1; - accent-color: $active-color; - } - - .editorParamsColor { - border: 1px solid #555 !important; - border-radius: 4px !important; - cursor: pointer !important; - } - - // Highlight color picker dots - .colorPicker { - display: flex; - align-items: center; - gap: 6px; - flex-wrap: wrap; - - button { - width: 24px !important; - height: 24px !important; - min-width: 24px !important; - border-radius: 50% !important; - border: 2px solid transparent !important; - padding: 0 !important; - cursor: pointer !important; - - &[aria-selected="true"], - &.selected { - border-color: #fff !important; - box-shadow: 0 0 4px rgb(255 255 255 / 40%) !important; - } - } - } - - // Toggle button for "show all highlights" - .toggle-button { - background: #555 !important; - border: none !important; - border-radius: 12px !important; - width: 36px !important; - height: 20px !important; - cursor: pointer !important; - position: relative !important; - - &[aria-pressed="true"] { - background: $active-color !important; - } - } - - .thicknessPicker { - flex: 1; - } - - .toggler { - display: flex; - align-items: center; - justify-content: space-between; - gap: 8px; - } - - .divider { - height: 1px; - background: $border-color; - margin: 4px 0; - } - - // Generic button styling inside params toolbars - button.secondaryToolbarButton, - button.toolbarButton { - background: none !important; - color: #fff !important; - border: none !important; - border-radius: 6px !important; - padding: 6px 10px !important; - cursor: pointer !important; - display: flex !important; - align-items: center !important; - gap: 6px !important; - width: 100% !important; - - &:hover { - background: $hover-bg !important; - } - - span { - display: inline !important; - color: inherit !important; - } - } - - // Injected close button wrapper - .custom-close-btn-wrapper { - display: flex; - justify-content: flex-end; - align-items: center; - width: 100%; - margin-bottom: 6px; - border-bottom: 1px solid rgb(255 255 255 / 10%); - padding-bottom: 6px; - } - - // Injected close button - .custom-close-btn { - display: flex !important; - align-items: center !important; - justify-content: center !important; - width: 34px !important; - height: 34px !important; - padding: 0 !important; - background: transparent !important; - border: none !important; - border-radius: 4px !important; - - svg { - display: block; - } - - &:hover { - background: rgb(239 68 68 / 20%) !important; - color: #ef4444 !important; - } - } - } - - // Style the secondary toolbar dropdown - #secondaryToolbar { - top: $header-height !important; - background: #2d2d2d !important; - border: 1px solid $border-color !important; - border-radius: 0 0 8px 8px !important; - box-shadow: 0 4px 16px rgb(0 0 0 / 40%) !important; - padding: 4px !important; - - button { - background: none !important; - border: none !important; - color: #fff !important; - border-radius: 6px !important; - padding: 8px 12px !important; - font-size: 13px !important; - width: 100% !important; - text-align: left !important; - display: flex !important; - align-items: center !important; - gap: 8px !important; - - &:hover { - background: $hover-bg !important; - } - - &[aria-pressed="true"], - &.toggled { - color: $active-color !important; - background: rgb(74 144 226 / 15%) !important; - } - - span { - display: inline !important; - color: inherit !important; - } - } - } - - // Style the find bar - #findbar { - background: #2d2d2d !important; - border: 1px solid $border-color !important; - border-radius: 0 0 8px 8px !important; - box-shadow: 0 4px 12px rgb(0 0 0 / 30%) !important; - padding: 8px !important; - top: 0 !important; - - input { - background: #404040 !important; - color: #fff !important; - border: 1px solid #555 !important; - border-radius: 4px !important; - padding: 4px 8px !important; - } - - button { - background: none !important; - color: #fff !important; - border: none !important; - border-radius: 4px !important; - - &:hover { - background: $hover-bg !important; - } - } - - label { - color: $text-secondary !important; - } - } - - // Style the sidebar - #sidebarContainer { - background: #1f1f1f !important; - border-right: 1px solid $border-color !important; - - #toolbarSidebar { - background: #2d2d2d !important; - border-bottom: 1px solid $border-color !important; - - button { - color: #fff !important; - - &.toggled { - color: $active-color !important; - } - } - } - - #sidebarContent { - background: #1f1f1f !important; - } - - .treeItem { - color: #fff !important; - - >a { - color: #fff !important; - - &:hover { - background: $hover-bg !important; - } - } - } - } - - // Hide the default toolbar container chrome completely - our custom toolbar is positioned fixed - #toolbarContainer { - position: absolute !important; - height: 0 !important; - min-height: 0 !important; - max-height: 0 !important; - padding: 0 !important; - margin: 0 !important; - border: none !important; - background: transparent !important; - overflow: visible !important; - } + .overflow-divider { + height: 1px; + background: $border-color; + margin: 4px 0; } } // --- Responsive --- -@media (width <= 768px) { +// Tablet (portrait) switches to mobile toolbar layout +@media (width <= 1024px) { + .pdf-header-toolbar { + height: $header-height + 4px; + padding: 0 8px; + } + + .desktop-actions { + display: none; + } + + .mobile-actions { + display: flex; + } + .pdf-footer { height: auto; padding: 8px 12px; @@ -911,22 +779,25 @@ $transition-fast: 150ms ease; display: none; } - .zoom-controls { + .footer-spacer { display: none; } - .header-right { - ::ng-deep pdf-zoom-toolbar { - display: none !important; + .page-nav-left { + flex: 1; + justify-content: center; + } + + .viewer-mode-toggle { + .toggle-btn span { + display: none; } } - pdf-highlight-editor, - pdf-text-editor, - pdf-draw-editor, - pdf-find-button, - .separator { - display: none !important; + .search-bar { + .search-input-wrapper { + max-width: none; + } } .doc-viewer-info { @@ -939,4 +810,66 @@ $transition-fast: 150ms ease; .book-title { display: none; } + + // Larger touch targets for trigger zones + .header-trigger-zone { + height: 40px; + } + + .footer-trigger-zone { + height: 50px; + } +} + +// Small phones +@media (width <= 480px) { + .pdf-header-toolbar { + padding: 0 6px; + } + + .pdf-footer { + padding: 6px 8px; + } + + .page-nav-left { + gap: 4px; + } + + .nav-btn { + padding: 8px; + min-width: 36px; + min-height: 36px; + } + + .page-info { + min-width: 70px; + font-size: 12px; + padding: 4px 8px; + } + + .slider-wrapper { + .page-slider { + &::-webkit-slider-thumb { + width: 22px; + height: 22px; + margin-top: calc((6px - 22px) / 2); + } + + &::-moz-range-thumb { + width: 22px; + height: 22px; + } + } + } + + .viewer-mode-toggle .toggle-btn { + padding: 0 8px; + height: 34px; + } + + .icon-btn { + padding: 8px; + min-width: 36px; + min-height: 36px; + } } diff --git a/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.ts b/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.ts index 82fe4b926..9371fdf18 100644 --- a/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.ts +++ b/frontend/src/app/features/readers/pdf-reader/pdf-reader.component.ts @@ -1,16 +1,21 @@ -import { Component, HostListener, inject, OnDestroy, OnInit, AfterViewInit } from '@angular/core'; -import { ActivatedRoute } from '@angular/router'; -import { NgxExtendedPdfViewerModule, NgxExtendedPdfViewerService, pdfDefaultOptions, ZoomType } from 'ngx-extended-pdf-viewer'; +import { Component, ElementRef, inject, NgZone, OnDestroy, OnInit, ViewChild, afterNextRender } 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, from, Observable, of, Subject, Subscription } from "rxjs"; -import { debounceTime, map, switchMap } from 'rxjs/operators'; +import { forkJoin, firstValueFrom, from, Observable, of, Subject, Subscription, takeUntil } from "rxjs"; +import { debounceTime, filter, map, switchMap } from 'rxjs/operators'; import { BookSetting } from '../../book/model/book.model'; import { UserService } from '../../settings/user-management/user.service'; import { AuthService } from '../../../shared/service/auth.service'; import { API_CONFIG } from '../../../core/config/api-config'; import { PdfAnnotationService } from '../../../shared/service/pdf-annotation.service'; import { ReaderIconComponent } from '../../readers/ebook-reader/shared/icon.component'; +import { BookMark } from '../../../shared/service/book-mark.service'; +import { EmbedPdfBookService, PdfOutlineItem } from './services/embedpdf-book.service'; +import type { AnnotationTransferItem } from '@embedpdf/snippet'; +import { PdfBookmarkService } from './services/pdf-bookmark.service'; +import { PdfSidebarComponent, PdfAnnotationListItem } from './components/pdf-sidebar.component'; +import { parseStoredAnnotations, serializeAnnotations } from './utils/annotation-converter'; import { ProgressSpinner } from 'primeng/progressspinner'; import { MessageService } from 'primeng/api'; @@ -27,33 +32,29 @@ type EmbedPdfMessage = | { type: 'documentOpened'; pageCount?: number } | { type: 'documentError'; error: string } | { type: 'saved'; buffer?: ArrayBuffer } - | { type: 'saveError'; error: string }; + | { type: 'saveError'; error: string } + | { type: 'pageChange'; pageNumber: number; totalPages: number }; @Component({ selector: 'app-pdf-reader', standalone: true, - imports: [NgxExtendedPdfViewerModule, ProgressSpinner, TranslocoPipe, ReaderIconComponent, FormsModule], + imports: [ProgressSpinner, TranslocoPipe, ReaderIconComponent, FormsModule, PdfSidebarComponent], + providers: [EmbedPdfBookService, PdfBookmarkService], templateUrl: './pdf-reader.component.html', styleUrl: './pdf-reader.component.scss', }) -export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { - constructor() { - pdfDefaultOptions.rangeChunkSize = 512 * 1024; - pdfDefaultOptions.disableAutoFetch = true; - pdfDefaultOptions.disableStream = true; - } +export class PdfReaderComponent implements OnInit, OnDestroy { isLoading = true; totalPages: number = 0; isDarkTheme = true; canPrint = false; - rotation: 0 | 90 | 180 | 270 = 0; authorization = ''; page!: number; - spread!: 'off' | 'even' | 'odd'; - zoom!: ZoomType; + spread!: 'none' | 'even' | 'odd'; + zoom!: string; bookData!: string; bookId!: number; @@ -62,18 +63,80 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { isFullscreen = false; viewerMode: 'book' | 'document' = 'book'; isDocViewerInfoVisible = false; + docViewerReady = false; private readonly DOC_VIEWER_DISMISSED_KEY = 'grimmory_doc_viewer_info_dismissed'; + + // Doc mode (iframe) state private embedPdfIframe: HTMLIFrameElement | null = null; private embedPdfMessageHandler?: (e: MessageEvent) => void; private embedPdfSaveResolve?: (buffer: ArrayBuffer | null) => void; private embedPdfSaveTimer?: ReturnType; private embedPdfInitTime = 0; + private initTimeout?: ReturnType; + private isInitializingBookViewer = false; + private pdfFetchAbortController?: AbortController; - // Auto-hide chrome + // Book mode state + private bookViewerInitialized = false; + + // Chrome auto-hide headerVisible = true; footerVisible = true; private chromeAutoHideTimer?: ReturnType; private readonly CHROME_HIDE_DELAY = 3000; + private mouseMoveCleanup?: () => void; + private documentClickCleanup?: () => void; + private keydownCleanup?: () => void; + private touchCleanup?: () => void; + private lastMouseMoveTime = 0; + + // Mobile touch navigation + isMobile = false; + isToolbarOverflowOpen = false; + @ViewChild('overflowMenu') overflowMenuRef?: ElementRef; + 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[] = []; + + // 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; + private readonly searchQuery$ = new Subject(); + private dbAnnotationIds = new Set(); + + + // 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; @@ -89,8 +152,15 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { private altBookType?: string; private appSettingsSubscription!: Subscription; private annotationSaveSubject = new Subject(); + private annotationCacheSubject = new Subject(); private annotationSaveSubscription!: Subscription; + private annotationCacheSubscription!: Subscription; private annotationsLoaded = false; + private isImportingAnnotations = false; + private lastAnnotationData: string | null = null; + private annotationsDirty = false; + private pdfBlobUrl: string | null = null; + private readonly destroy$ = new Subject(); private bookService = inject(BookService); private userService = inject(UserService); @@ -100,27 +170,138 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { private pageTitle = inject(PageTitleService); private readingSessionService = inject(ReadingSessionService); private location = inject(Location); - private pdfViewerService = inject(NgxExtendedPdfViewerService); + private router = inject(Router); private pdfAnnotationService = inject(PdfAnnotationService); private cacheStorageService = inject(CacheStorageService); private localSettingsService = inject(LocalSettingsService); private readonly t = inject(TranslocoService); private wakeLockService = inject(WakeLockService); - private annotationToolbarObserver?: MutationObserver; + readonly embedPdfBook = inject(EmbedPdfBookService); + readonly pdfBookmarkService = inject(PdfBookmarkService); + private readonly ngZone = inject(NgZone); ngOnInit(): void { const dismissed = localStorage.getItem(this.DOC_VIEWER_DISMISSED_KEY); this.isDocViewerInfoVisible = dismissed !== 'true'; + this.isMobile = 'ontouchstart' in window || navigator.maxTouchPoints > 0; setTimeout(() => this.wakeLockService.enable(), 1000); this.startChromeAutoHide(); document.addEventListener('fullscreenchange', this.onFullscreenChange); + // Listen for mousemove outside Angular zone to avoid constant change detection + this.ngZone.runOutsideAngular(() => { + const mouseMoveHandler = () => { + const now = Date.now(); + if (now - this.lastMouseMoveTime < 200) return; + this.lastMouseMoveTime = now; + this.ngZone.run(() => { + this.showChrome(); + this.startChromeAutoHide(); + }); + }; + document.addEventListener('mousemove', mouseMoveHandler); + this.mouseMoveCleanup = () => document.removeEventListener('mousemove', mouseMoveHandler); + + const clickHandler = (e: MouseEvent) => { + 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; + }); + } + }; + document.addEventListener('click', clickHandler, true); + this.documentClickCleanup = () => document.removeEventListener('click', clickHandler, true); + + // Intercept 'x' key to prevent EmbedPDF from reloading the page; + // instead close the reader via SPA navigation. + const keydownHandler = (e: KeyboardEvent) => { + const tag = (e.target as HTMLElement)?.tagName; + const isEditing = tag === 'INPUT' || tag === 'TEXTAREA' || (e.target as HTMLElement)?.isContentEditable; + + if (e.key === 'x' || e.key === 'X') { + if (isEditing) return; + e.preventDefault(); + e.stopPropagation(); + this.ngZone.run(() => this.closeReader()); + } + + // Search: Ctrl+F, Cmd+F, or "/" + if (((e.ctrlKey || e.metaKey) && (e.key === 'f' || e.key === 'F')) || (e.key === '/' && !isEditing)) { + if (isEditing) return; + e.preventDefault(); + e.stopPropagation(); + this.ngZone.run(() => { + if (!this.isSearchOpen) { + this.toggleSearch(); + } else { + // Focus search input if already open + this.searchInputRef?.nativeElement.focus(); + } + }); + } + + if (e.key === 'Escape') { + if (this.isSearchOpen) { + e.preventDefault(); + e.stopPropagation(); + this.ngZone.run(() => this.closeSearch()); + } else if (this.sidebarOpen) { + e.preventDefault(); + e.stopPropagation(); + this.ngZone.run(() => this.sidebarOpen = false); + } + } + }; + document.addEventListener('keydown', keydownHandler, true); + this.keydownCleanup = () => document.removeEventListener('keydown', keydownHandler, true); + + // Touch gestures for mobile navigation + const touchStartHandler = (e: TouchEvent) => { + this.touchStartX = e.changedTouches[0].clientX; + this.touchStartY = e.changedTouches[0].clientY; + this.touchStartTime = Date.now(); + this.touchMoveCount = 0; + }; + const touchMoveHandler = () => { this.touchMoveCount++; }; + const touchEndHandler = (e: TouchEvent) => { + this.handleTouchEnd(e); + }; + document.addEventListener('touchstart', touchStartHandler, { passive: true }); + document.addEventListener('touchmove', touchMoveHandler, { passive: true }); + document.addEventListener('touchend', touchEndHandler, { passive: true }); + this.touchCleanup = () => { + document.removeEventListener('touchstart', touchStartHandler); + document.removeEventListener('touchmove', touchMoveHandler); + document.removeEventListener('touchend', touchEndHandler); + }; + }); + this.annotationSaveSubscription = this.annotationSaveSubject .pipe(debounceTime(1500)) .subscribe(() => this.persistAnnotations()); + // Debounced search + this.searchQuery$.pipe( + takeUntil(this.destroy$), + debounceTime(400), + filter(() => this.isSearchOpen) + ).subscribe(query => { + if (query.length > 1) { + this.embedPdfBook.searchAllPages(query); + } + }); + + // Keep lastAnnotationData warm so persistAnnotationsSync() always has fresh data + + this.annotationCacheSubscription = this.annotationCacheSubject + .pipe(debounceTime(500)) + .subscribe(() => this.cacheAnnotationData()); + this.route.paramMap.pipe( + takeUntil(this.destroy$), switchMap((params) => { this.isLoading = true; this.bookId = +params.get('bookId')!; @@ -158,18 +339,24 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { const globalOrIndividual = myself.userSettings.perBookSetting.pdf; if (globalOrIndividual === 'Global') { this.zoom = myself.userSettings.pdfReaderSetting.pageZoom || 'page-fit'; - this.spread = myself.userSettings.pdfReaderSetting.pageSpread || 'off'; + this.spread = (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'; - this.spread = pdfPrefs.pdfSettings?.spread || myself.userSettings.pdfReaderSetting.pageSpread || 'off'; + 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; } + this.spreadMode = this.spread; this.canPrint = myself.permissions.canDownload || myself.permissions.admin; this.page = pdfMeta.pdfProgress?.page || 1; + this.zoom = this.normalizeZoom(this.zoom); this.bookData = bookData; const token = this.authService.getInternalAccessToken(); this.authorization = token ? `Bearer ${token}` : ''; this.isLoading = false; + + // Initialize book viewer after loading completes + this.ngZone.runOutsideAngular(() => this.ensureViewerElementAndInitialize()); }, error: () => { this.messageService.add({ severity: 'error', summary: this.t.translate('common.error'), detail: this.t.translate('readerPdf.toast.failedToLoadBook') }); @@ -178,102 +365,460 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { }); } - ngAfterViewInit(): void { - this.setupAnnotationToolbarCloseObserver(); - } - - private setupAnnotationToolbarCloseObserver(): void { - this.annotationToolbarObserver = new MutationObserver((mutations) => { - mutations.forEach((mutation) => { - mutation.addedNodes.forEach((node) => { - if (node instanceof HTMLElement) { - if (node.classList.contains('editorParamsToolbar')) { - this.injectCloseButton(node); - } - const toolbars = node.querySelectorAll?.('.editorParamsToolbar'); - toolbars?.forEach(t => this.injectCloseButton(t as HTMLElement)); - } - }); - }); - }); - - this.annotationToolbarObserver.observe(document.body, { childList: true, subtree: true }); - - // Also check immediately in case they are already in the DOM - setTimeout(() => { - document.querySelectorAll('.editorParamsToolbar').forEach(t => this.injectCloseButton(t as HTMLElement)); - }, 1000); - } - - private injectCloseButton(toolbar: HTMLElement): void { - if (toolbar.querySelector('.custom-close-btn-wrapper') || toolbar.querySelector('.custom-close-btn')) return; - - const wrapper = document.createElement('div'); - wrapper.className = 'custom-close-btn-wrapper'; - - const btn = document.createElement('button'); - btn.className = 'custom-close-btn icon-btn'; - btn.innerHTML = ``; - - // Attempt to translate, fallback to 'Close' - try { - btn.title = this.t.translate('common.close') || 'Close'; - } catch { - btn.title = 'Close'; - } - - btn.onclick = () => { - // Dispatching ESC doesn't always work natively for pdf.js. - // The most reliable way to close it is to click the tool that is currently active. - const activeBtn = document.querySelector(` - #editorHighlight.toggled, - #editorFreeText.toggled, - #editorInk.toggled, - #editorStamp.toggled, - .header-right button.toggled, - .header-right button[aria-pressed="true"] - `) as HTMLElement; - - if (activeBtn) { - activeBtn.click(); - } else { - // Fallback: dispatch a custom event or switch to hand tool if the button isn't found - const editorNone = document.querySelector('#editorNone') as HTMLElement; - if (editorNone) { - editorNone.click(); - } else { - // Last resort: click outside - document.body.click(); - } - } - }; - - wrapper.appendChild(btn); - toolbar.prepend(wrapper); - } - dismissDocViewerInfo(): void { this.isDocViewerInfoVisible = false; localStorage.setItem(this.DOC_VIEWER_DISMISSED_KEY, 'true'); } - async setViewerMode(mode: 'book' | 'document') { - if (mode !== 'document' && this.embedPdfIframe) { - await this.saveEmbedPdfDocument(); - await this.destroyEmbedPdf(); + // --- Book viewer (EmbedPDF direct) --- + + private async ensureViewerElementAndInitialize(attempt = 0): Promise { + 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.viewerMode = mode; - if (mode === 'document') { - // Pause the body-wide MutationObserver it causes massive lag when EmbedPDF mutates the DOM - this.annotationToolbarObserver?.disconnect(); - setTimeout(() => this.initEmbedPdf(), 100); - } else { - // Re-enable it for book mode - this.setupAnnotationToolbarCloseObserver(); + + this.ngZone.run(() => this.initBookViewer()); + } + + private async initBookViewer(): Promise { + if (this.viewerMode !== 'book' || this.bookViewerInitialized || this.isInitializingBookViewer) return; + + const targetEl = document.getElementById('book-viewer'); + if (!targetEl) return; + + this.isInitializingBookViewer = true; + + // Capture current book state to ensure consistency across async calls + const currentBookId = this.bookId; + const currentBookData = this.bookData; + + try { + // Abort any pending fetch from a previous (stale) initialization attempt + if (this.pdfFetchAbortController) { + this.pdfFetchAbortController.abort(); + } + this.pdfFetchAbortController = new AbortController(); + + let pdfUrl: string; + if (currentBookData.startsWith('blob:')) { + pdfUrl = currentBookData; + } else { + pdfUrl = await this.fetchAsObjectUrl(currentBookData, this.pdfFetchAbortController.signal); + this.revokePdfBlobUrl(); + this.pdfBlobUrl = pdfUrl; + } + + // Check if we were aborted or navigated away during the fetch + if (this.pdfFetchAbortController.signal.aborted || currentBookId !== this.bookId || this.viewerMode !== 'book') { + return; + } + + await this.embedPdfBook.init( + targetEl, + pdfUrl, + this.isDarkTheme ? 'dark' : 'light' + ); + this.bookViewerInitialized = true; + + // Initialize bookmark service early so toggleBookmark works before documentOpened$ + this.pdfBookmarkService.initialize(this.bookId); + + // Subscribe to page changes (outside zone, debounced) + this.embedPdfBook.pageChange$.pipe( + takeUntil(this.destroy$), + debounceTime(100) + ).subscribe(ev => { + this.ngZone.run(() => { + this.onPageChange(ev.pageNumber); + this.totalPages = ev.totalPages; + }); + }); + + // Subscribe to annotation events for debounced save + this.embedPdfBook.annotationEvent$.pipe( + takeUntil(this.destroy$) + ).subscribe((ev) => { + this.ngZone.run(() => { + if (this.annotationsLoaded && !this.isImportingAnnotations) { + // Update the set of tracked IDs for synchronization + if (ev.type === 'create' || ev.type === 'update') { + const id = ev.annotation?.id; + // Only track specifically allowed user annotation types (exclude links, etc.) + const type = ev.annotation?.type as number; + const isAllowed = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15].includes(type); + + if (id && isAllowed) { + this.dbAnnotationIds.add(id); + } + } else if (ev.type === 'delete') { + const id = ev.annotation?.id; + if (id) { + this.dbAnnotationIds.delete(id); + } + } + + this.annotationsDirty = true; + this.annotationSaveSubject.next(); + this.annotationCacheSubject.next(); + this.refreshAnnotationList(); + } + }); + }); + + // Subscribe to document opened + this.embedPdfBook.documentOpened$.pipe( + takeUntil(this.destroy$) + ).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); + + // Apply saved zoom level + if (this.zoom && this.zoom !== 'fit-page') { + this.embedPdfBook.setZoomLevel(this.zoom); + } + + // Apply saved spread mode + if (this.spread && this.spread !== 'none') { + this.embedPdfBook.setSpreadMode(this.spread); + this.spreadMode = 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$) + ).subscribe(() => { + if (this.page > 1) { + this.embedPdfBook.scrollToPage(this.page, 'instant'); + } + }); + + } catch (err) { + console.error('[BookViewer] Init failed:', err); + this.messageService.add({ + severity: 'error', + summary: this.t.translate('common.error'), + detail: this.t.translate('readerPdf.toast.failedToLoadBook') + }); + } finally { + this.isInitializingBookViewer = false; } } - private async initEmbedPdf() { + private async fetchAsObjectUrl(url: string, signal?: AbortSignal): Promise { + const headers: Record = {}; + if (this.authorization) { + headers['Authorization'] = this.authorization; + } + try { + const response = await fetch(url, { headers, credentials: 'include', signal }); + if (!response.ok) throw new Error(`PDF fetch failed: ${response.status}`); + const blob = await response.blob(); + return URL.createObjectURL(blob); + } catch (err: unknown) { + if (err instanceof Error && err.name === 'AbortError') { + console.info('[PDF Reader] Fetch aborted for:', url); + return ''; + } + throw err; + } + } + + private destroyBookViewer(): void { + this.embedPdfBook.destroy(); + this.bookViewerInitialized = false; + this.revokePdfBlobUrl(); + } + + private async loadOutline(): Promise { + this.outline = await this.embedPdfBook.getOutline(); + } + + private loadBookmarks(): void { + this.pdfBookmarkService.loadBookmarks().subscribe(bookmarks => { + this.pdfBookmarks = bookmarks; + }); + } + + private loadAnnotations(): void { + this.pdfAnnotationService.getAnnotations(this.bookId).subscribe({ + next: async (response) => { + console.info('[PDF Annotations] GET response:', response); + if (response?.data) { + 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 + const seenIds = new Set(); + const items = allItems.filter(item => { + if (seenIds.has(item.annotation.id)) return false; + seenIds.add(item.annotation.id); + return true; + }); + + if (allItems.length !== items.length) { + console.warn('[PDF Annotations] Deduplicated from', allItems.length, 'to', items.length); + } + + if (items.length > 0) { + this.isImportingAnnotations = true; + try { + // Chunk the import to prevent script timeout and keep UI responsive + const CHUNK_SIZE = 500; + for (let i = 0; i < items.length; i += CHUNK_SIZE) { + const chunk = items.slice(i, i + CHUNK_SIZE); + await this.embedPdfBook.importAnnotations(chunk); + // Breathe to prevent long-task timeouts + if (items.length > CHUNK_SIZE) { + await new Promise(r => setTimeout(r, 0)); + } + } + console.info('[PDF Annotations] Import complete'); + } catch (err) { + console.error('[PDF Annotations] Import failed:', err); + } finally { + this.isImportingAnnotations = false; + this.annotationsLoaded = true; + this.cacheAnnotationData(); + this.refreshAnnotationList(); + } + return; + } + } + console.info('[PDF Annotations] No stored annotations, annotationsLoaded=true'); + this.annotationsLoaded = true; + this.refreshAnnotationList(); + }, + error: (err) => { + console.warn('[PDF Annotations] GET error:', err); + this.annotationsLoaded = true; + } + }); + } + + private async refreshAnnotationList(): Promise { + if (!this.annotationsLoaded || this.viewerMode === 'document') return; + try { + const allItems = await this.embedPdfBook.exportAnnotations(); + const items = this.filterAndDeduplicateAnnotations(allItems); + this.annotationListItems = items.map(item => { + const ann = item.annotation as unknown as Record; + return { + id: String(ann['id'] || ''), + pageIndex: (ann['pageIndex'] as number) ?? 0, + type: this.getAnnotationTypeName(ann['type'] as number), + color: (ann['strokeColor'] ?? ann['color']) as string | undefined, + text: ann['contents'] as string | undefined, + }; + }); + } catch { + this.annotationListItems = []; + } + } + + private getAnnotationTypeName(type: number): string { + switch (type) { + case 9: return 'Highlight'; + case 15: return 'Ink'; + case 3: return 'Text'; + default: return 'Annotation'; + } + } + + // --- Annotation tools --- + + toggleAnnotationTool(toolId: string | null): void { + if (this.activeAnnotationTool === toolId) { + this.activeAnnotationTool = null; + } else { + this.isPanActive = false; + this.embedPdfBook.setPanMode(false); + this.activeAnnotationTool = toolId; + } + this.embedPdfBook.setActiveTool(this.activeAnnotationTool); + } + + togglePanMode(): void { + this.isPanActive = !this.isPanActive; + if (this.isPanActive) { + this.activeAnnotationTool = null; + this.embedPdfBook.setActiveTool(null); + } + this.embedPdfBook.setPanMode(this.isPanActive); + } + + setAnnotationColor(color: string): void { + this.activeAnnotationColor = color; + } + + // --- Search --- + + toggleSearch(): void { + this.isSearchOpen = !this.isSearchOpen; + if (this.isSearchOpen) { + afterNextRender(() => this.searchInputRef?.nativeElement.focus()); + this.embedPdfBook.startSearch(); + } else { + this.searchQuery = ''; + this.embedPdfBook.stopSearch(); + } + } + + closeSearch(): void { + this.isSearchOpen = false; + this.searchQuery = ''; + this.embedPdfBook.stopSearch(); + } + + onSearchInput(): void { + this.searchQuery$.next(this.searchQuery); + } + + + onSearchNext(): void { + this.embedPdfBook.nextSearchResult(); + } + + onSearchPrevious(): void { + this.embedPdfBook.previousSearchResult(); + } + + // --- Zoom --- + + toggleZoomMenu(): void { + this.isZoomMenuOpen = !this.isZoomMenuOpen; + } + + setZoomPreset(value: string): void { + this.zoom = value; + this.embedPdfBook.setZoomLevel(value); + this.isZoomMenuOpen = false; + this.updateViewerSetting(); + } + + // --- Spread --- + + 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); + this.updateViewerSetting(); + } + + // --- Rotate --- + + rotateClockwise(): void { + this.embedPdfBook.rotateClockwise(); + } + + // --- Bookmarks --- + + get isCurrentPageBookmarked(): boolean { + return this.pdfBookmarkService.isPageBookmarked(this.page); + } + + toggleBookmark(): void { + this.pdfBookmarkService.toggleBookmark(this.page).subscribe(success => { + if (success) { + this.pdfBookmarks = this.pdfBookmarkService.getAllBookmarks(); + } + }); + } + + onDeleteBookmark(bookmarkId: number): void { + this.pdfBookmarkService.deleteBookmark(bookmarkId).subscribe(success => { + if (success) { + this.pdfBookmarks = this.pdfBookmarkService.getAllBookmarks(); + } + }); + } + + onDeleteAnnotation(annotationId: string): void { + const item = this.annotationListItems.find(a => a.id === annotationId); + if (item) { + this.embedPdfBook.deleteAnnotation(item.pageIndex, annotationId); + this.annotationListItems = this.annotationListItems.filter(a => a.id !== annotationId); + this.annotationSaveSubject.next(); + } + } + + // --- Sidebar --- + + toggleSidebar(): void { + this.sidebarOpen = !this.sidebarOpen; + } + + onSidebarClosed(): void { + this.sidebarOpen = false; + } + + onSidebarNavigateToPage(pageNumber: number): void { + this.sidebarOpen = false; + if (this.viewerMode === 'book') { + this.embedPdfBook.scrollToPage(pageNumber); + } + this.onPageChange(pageNumber); + } + + // --- Viewer mode switching --- + + async setViewerMode(mode: 'book' | 'document') { + if (mode === this.viewerMode) return; + + this.docViewerReady = false; + if (this.initTimeout) { + clearTimeout(this.initTimeout); + this.initTimeout = undefined; + } + + if (mode === 'document') { + // Save annotations before switching + await this.persistAnnotations(); + this.destroyBookViewer(); + this.viewerMode = mode; + this.initTimeout = setTimeout(() => { + this.initTimeout = undefined; + this.initDocViewerIframe(); + }, 100); + } else { + // Switching from doc to book — save in background, don't block the switch + if (this.embedPdfIframe) { + this.saveEmbedPdfDocument().finally(() => this.destroyDocViewerIframe()); + } + this.viewerMode = mode; + this.initTimeout = setTimeout(() => { + this.initTimeout = undefined; + this.initBookViewer(); + }, 150); + } + } + + // --- Doc viewer (iframe) --- + + private async initDocViewerIframe() { if (this.embedPdfIframe) return; const t0 = performance.now(); @@ -288,18 +833,17 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { 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; + const pdfBuffer = await response.arrayBuffer(); const targetEl = document.getElementById('embedpdf-viewer'); if (!targetEl) throw new Error('#embedpdf-viewer not found'); - // Create iframe — EmbedPDF + its WASM memory live entirely inside the iframe. - // Destroying the iframe releases all WASM linear memory, solving the leak. const iframe = document.createElement('iframe'); iframe.src = '/assets/embedpdf-frame.html'; iframe.style.cssText = 'width:100%;height:100%;border:none;'; iframe.setAttribute('allow', 'fullscreen'); - // Listen for messages from the iframe this.embedPdfMessageHandler = (e: MessageEvent) => { if (e.origin !== location.origin) return; if (e.source !== iframe.contentWindow) return; @@ -307,7 +851,6 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { }; window.addEventListener('message', this.embedPdfMessageHandler); - // Wait for iframe to load before sending PDF data await new Promise((resolve) => { iframe.onload = () => resolve(); targetEl.appendChild(iframe); @@ -315,7 +858,6 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { this.embedPdfIframe = iframe; - // Transfer the PDF buffer to the iframe (zero-copy via Transferable) iframe.contentWindow!.postMessage({ type: 'init', buffer: pdfBuffer, @@ -333,10 +875,10 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { } } - /** Handle postMessage events from the EmbedPDF iframe */ private handleEmbedPdfMessage(msg: EmbedPdfMessage): void { switch (msg.type) { case 'ready': + this.docViewerReady = true; break; case 'documentOpened': break; @@ -352,27 +894,26 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { this.embedPdfSaveResolve?.(null); this.embedPdfSaveResolve = undefined; break; + case 'pageChange': + this.onPageChange(msg.pageNumber); + this.totalPages = msg.totalPages; + break; } } private async saveEmbedPdfDocument(): Promise { - if (!this.embedPdfIframe?.contentWindow) { - return; - } + if (!this.embedPdfIframe?.contentWindow) return; try { - // Request save from iframe and wait for response const buffer: ArrayBuffer | null = await new Promise((resolve) => { this.embedPdfSaveResolve = resolve; this.embedPdfIframe!.contentWindow!.postMessage({ type: 'save' }, location.origin); - // Timeout after 30 seconds const timer = setTimeout(() => { if (this.embedPdfSaveResolve === resolve) { resolve(null); this.embedPdfSaveResolve = undefined; } - }, 30000); - // Store timer so we can clear it on success + }, 5000); this.embedPdfSaveTimer = timer; }); @@ -381,9 +922,7 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { this.embedPdfSaveTimer = undefined; } - if (!buffer) { - return; - } + if (!buffer) return; const headers: Record = { 'Content-Type': 'application/pdf' }; if (this.authorization) { @@ -408,6 +947,29 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { } } + private async destroyDocViewerIframe(): Promise { + if (this.embedPdfMessageHandler) { + window.removeEventListener('message', this.embedPdfMessageHandler); + this.embedPdfMessageHandler = undefined; + } + + if (this.embedPdfSaveTimer) { + clearTimeout(this.embedPdfSaveTimer); + this.embedPdfSaveTimer = undefined; + } + this.embedPdfSaveResolve?.(null); + this.embedPdfSaveResolve = undefined; + + if (this.embedPdfIframe) { + this.embedPdfIframe.remove(); + this.embedPdfIframe = null; + } + + this.embedPdfInitTime = 0; + } + + // --- Common viewer methods --- + onPageChange(page: number): void { if (page !== this.page) { this.page = page; @@ -417,25 +979,13 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { } } - onZoomChange(zoom: ZoomType): void { - if (zoom !== this.zoom) { - this.zoom = zoom; - this.updateViewerSetting(); - } - } - - onSpreadChange(spread: 'off' | 'even' | 'odd'): void { - if (spread !== this.spread) { - this.spread = spread; - this.updateViewerSetting(); - } - } - toggleDarkTheme(): void { this.isDarkTheme = !this.isDarkTheme; this.updateViewerSetting(); - // Sync EmbedPDF theme if active - if (this.embedPdfIframe?.contentWindow) { + // Sync theme with active viewer + 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' }, location.origin @@ -459,53 +1009,57 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { this.bookService.savePdfProgress(this.bookId, this.page, percentage, this.bookFileId).subscribe(); } - onPdfPagesLoaded(event: { pagesCount: number }): void { - this.totalPages = event.pagesCount; - 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); - // Delay annotation loading to ensure annotation editor layers are initialized - setTimeout(() => this.loadAnnotations(), 800); - } - - onAnnotationEditorEvent(): void { - if (this.annotationsLoaded) { - this.annotationSaveSubject.next(); - } - } - ngOnDestroy(): void { + if (this.initTimeout) clearTimeout(this.initTimeout); + if (this.pdfFetchAbortController) this.pdfFetchAbortController.abort(); this.wakeLockService.disable(); if (this.chromeAutoHideTimer) clearTimeout(this.chromeAutoHideTimer); - if (this.annotationToolbarObserver) this.annotationToolbarObserver.disconnect(); + + // 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); } this.annotationSaveSubscription?.unsubscribe(); - this.persistAnnotations(); - this.destroyEmbedPdf(); + this.annotationCacheSubscription?.unsubscribe(); + // Cannot await async export in ngOnDestroy — use cached annotation data + this.persistAnnotationsSync(); + this.destroyBookViewer(); + this.destroyDocViewerIframe(); if (this.appSettingsSubscription) { this.appSettingsSubscription.unsubscribe(); } - this.updateProgress(); document.removeEventListener('fullscreenchange', this.onFullscreenChange); + this.mouseMoveCleanup?.(); + this.documentClickCleanup?.(); + this.keydownCleanup?.(); + this.touchCleanup?.(); + this.revokePdfBlobUrl(); if (this.bookData?.startsWith('blob:')) { URL.revokeObjectURL(this.bookData); } + + this.pdfBookmarkService.reset(); + } + + private revokePdfBlobUrl(): void { + if (this.pdfBlobUrl) { + URL.revokeObjectURL(this.pdfBlobUrl); + this.pdfBlobUrl = null; + } } // --- Chrome auto-hide --- - @HostListener('document:mousemove') - onMouseMove(): void { - this.showChrome(); - this.startChromeAutoHide(); - } - showChrome(): void { this.headerVisible = true; this.footerVisible = true; @@ -531,6 +1085,71 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { this.startChromeAutoHide(); } + // --- Touch navigation --- + + private handleTouchEnd(e: TouchEvent): void { + if (this.viewerMode !== 'book') return; + + // Ignore touches on interactive elements + const target = e.target instanceof Element ? e.target : (e.target as Node)?.parentElement; + if (target instanceof Element && target.closest('.pdf-header-toolbar, .pdf-footer, .pdf-sidebar, .search-bar, .toolbar-overflow-menu, button, input, a')) return; + + const endX = e.changedTouches[0].clientX; + const endY = e.changedTouches[0].clientY; + const deltaX = endX - this.touchStartX; + const deltaY = endY - this.touchStartY; + const elapsed = Date.now() - this.touchStartTime; + + // Swipe detection: enough horizontal movement, more horizontal than vertical + if (this.touchMoveCount >= 3 && Math.abs(deltaX) > this.SWIPE_THRESHOLD && Math.abs(deltaX) > Math.abs(deltaY) * 1.5) { + this.ngZone.run(() => { + if (deltaX < 0) { + this.goToNextPage(); + } else { + this.goToPreviousPage(); + } + }); + return; + } + + // Tap detection: short duration, minimal movement + if (elapsed < this.TAP_MAX_DURATION && this.touchMoveCount < 3) { + const screenWidth = window.innerWidth; + const tapX = this.touchStartX; + + this.ngZone.run(() => { + if (tapX < screenWidth * this.TAP_ZONE_RATIO) { + // Left zone: previous page + this.goToPreviousPage(); + } else if (tapX > screenWidth * (1 - this.TAP_ZONE_RATIO)) { + // Right zone: next page + this.goToNextPage(); + } else { + // Center zone: toggle chrome + if (this.headerVisible || this.footerVisible) { + this.hideChrome(); + } else { + this.showChrome(); + this.startChromeAutoHide(); + } + } + }); + } + } + + // --- Toolbar overflow menu --- + + toggleToolbarOverflow(): void { + this.isToolbarOverflowOpen = !this.isToolbarOverflowOpen; + if (this.isToolbarOverflowOpen) { + afterNextRender(() => this.overflowMenuRef?.nativeElement.focus()); + } + } + + closeToolbarOverflow(): void { + this.isToolbarOverflowOpen = false; + } + // --- Fullscreen --- toggleFullscreen(): void { @@ -548,14 +1167,22 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { // --- Footer page navigation --- goToFirstPage(): void { - this.page = 1; + if (this.viewerMode === 'book') { + this.embedPdfBook.scrollToPage(1); + } else if (this.embedPdfIframe?.contentWindow) { + this.embedPdfIframe.contentWindow.postMessage({ type: 'scrollToPage', pageNumber: 1 }, location.origin); + } this.onPageChange(1); } goToPreviousPage(): void { if (this.page > 1) { const p = this.page - 1; - this.page = p; + if (this.viewerMode === 'book') { + this.embedPdfBook.scrollToPreviousPage(); + } else if (this.embedPdfIframe?.contentWindow) { + this.embedPdfIframe.contentWindow.postMessage({ type: 'prevPage' }, location.origin); + } this.onPageChange(p); } } @@ -563,48 +1190,67 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { goToNextPage(): void { if (this.page < this.totalPages) { const p = this.page + 1; - this.page = p; + if (this.viewerMode === 'book') { + this.embedPdfBook.scrollToNextPage(); + } else if (this.embedPdfIframe?.contentWindow) { + this.embedPdfIframe.contentWindow.postMessage({ type: 'nextPage' }, location.origin); + } this.onPageChange(p); } } goToLastPage(): void { - this.page = this.totalPages; + if (this.viewerMode === 'book') { + this.embedPdfBook.scrollToPage(this.totalPages); + } else if (this.embedPdfIframe?.contentWindow) { + this.embedPdfIframe.contentWindow.postMessage({ type: 'scrollToPage', pageNumber: this.totalPages }, location.origin); + } this.onPageChange(this.totalPages); } onSliderChange(event: Event): void { const value = +(event.target as HTMLInputElement).value; - this.page = value; + if (this.viewerMode === 'book') { + this.embedPdfBook.scrollToPage(value, 'instant'); + } else if (this.embedPdfIframe?.contentWindow) { + this.embedPdfIframe.contentWindow.postMessage({ type: 'scrollToPage', pageNumber: value }, location.origin); + } this.onPageChange(value); } onGoToPage(): void { if (this.goToPageInput && this.goToPageInput >= 1 && this.goToPageInput <= this.totalPages) { - this.page = this.goToPageInput; + if (this.viewerMode === 'book') { + this.embedPdfBook.scrollToPage(this.goToPageInput); + } else if (this.embedPdfIframe?.contentWindow) { + this.embedPdfIframe.contentWindow.postMessage({ type: 'scrollToPage', pageNumber: this.goToPageInput }, location.origin); + } this.onPageChange(this.goToPageInput); this.goToPageInput = null; } } - // --- Rotation --- - - rotateClockwise(): void { - this.rotation = ((this.rotation + 90) % 360) as 0 | 90 | 180 | 270; - } - closeReader = async (): Promise => { - if (this.embedPdfIframe) { - await this.saveEmbedPdfDocument(); - await this.destroyEmbedPdf(); - } else { - this.persistAnnotations(); + try { + if (this.viewerMode === 'document' && this.embedPdfIframe) { + await this.saveEmbedPdfDocument(); + await this.destroyDocViewerIframe(); + } else { + await this.persistAnnotations(); + } + } catch (e) { + console.error('[PDF Reader] Error saving on close:', e); } 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); } - this.location.back(); + // Navigate back within the SPA; fall back to home if there's no history + if (window.history.length > 1) { + this.location.back(); + } else { + this.router.navigate(['/']); + } } private getBookData( @@ -621,68 +1267,103 @@ export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit { ) } - private loadAnnotations(): void { - this.pdfAnnotationService.getAnnotations(this.bookId).subscribe({ - next: async (response) => { - if (response?.data) { - try { - const annotations = JSON.parse(response.data); - if (Array.isArray(annotations)) { - for (const annotation of annotations) { - await this.pdfViewerService.addEditorAnnotation(annotation); - } - } - } catch (e) { - console.error('[PDF Annotations] Failed to load annotations:', e); - } - } - this.annotationsLoaded = true; - }, - error: () => { - this.annotationsLoaded = true; - } - }); - } - - private async destroyEmbedPdf(): Promise { - - - // Remove message listener - if (this.embedPdfMessageHandler) { - window.removeEventListener('message', this.embedPdfMessageHandler); - this.embedPdfMessageHandler = undefined; - } - - // Cancel any pending save - if (this.embedPdfSaveTimer) { - clearTimeout(this.embedPdfSaveTimer); - this.embedPdfSaveTimer = undefined; - } - this.embedPdfSaveResolve?.(null); - this.embedPdfSaveResolve = undefined; - - // Remove the iframe — this destroys the entire browsing context, - // freeing all WASM linear memory, JS heap, and DOM within it. - if (this.embedPdfIframe) { - this.embedPdfIframe.remove(); - this.embedPdfIframe = null; - } - - this.embedPdfInitTime = 0; - } - - private persistAnnotations(): void { - if (!this.annotationsLoaded || !this.bookId || this.viewerMode === 'document') { - return; - } + private async persistAnnotations(): Promise { + if (!this.annotationsLoaded || !this.bookId || this.viewerMode === 'document') return; try { - const serialized = this.pdfViewerService.getSerializedAnnotations(); - if (serialized && serialized.length > 0) { - const data = JSON.stringify(serialized); - this.pdfAnnotationService.saveAnnotations(this.bookId, data).subscribe(); - } + const allItems = await this.embedPdfBook.exportAnnotations(); + const items = this.filterAndDeduplicateAnnotations(allItems); + const data = serializeAnnotations(items); + this.lastAnnotationData = data; + this.annotationsDirty = false; + await firstValueFrom(this.pdfAnnotationService.saveAnnotations(this.bookId, data)); + console.info('[PDF Annotations] Saved', items.length, 'annotations for book', this.bookId); } catch (e) { console.error('[PDF Annotations] Failed to save annotations:', e); } } + + private persistAnnotationsSync(): void { + if (!this.bookId || this.lastAnnotationData === null) return; + const url = `${API_CONFIG.BASE_URL}/api/v1/pdf-annotations/book/${this.bookId}`; + const headers: Record = { 'Content-Type': 'application/json' }; + if (this.authorization) { + headers['Authorization'] = this.authorization; + } + fetch(url, { + method: 'PUT', + headers, + credentials: 'include', + body: JSON.stringify({ data: this.lastAnnotationData }), + keepalive: true, + }).catch(() => { /* fire-and-forget */ }); + } + + private cacheAnnotationData(): void { + this.embedPdfBook.exportAnnotations().then(allItems => { + const items = this.filterAndDeduplicateAnnotations(allItems); + this.lastAnnotationData = serializeAnnotations(items); + }).catch(() => { /* fire-and-forget */ }); + } + + private saveProgressSync(): void { + if (!this.bookId || !this.page) return; + const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0; + const body: Record = { + bookId: this.bookId, + pdfProgress: { page: this.page, percentage } + }; + if (this.bookFileId) { + body['fileProgress'] = { + bookFileId: this.bookFileId, + positionData: String(this.page), + progressPercent: percentage + }; + } + const url = `${API_CONFIG.BASE_URL}/api/v1/books/progress`; + const headers: Record = { 'Content-Type': 'application/json' }; + if (this.authorization) { + headers['Authorization'] = this.authorization; + } + fetch(url, { + method: 'POST', + headers, + credentials: 'include', + body: JSON.stringify(body), + keepalive: true, + }).catch(() => { /* fire-and-forget */ }); + } + + private filterAndDeduplicateAnnotations(allItems: AnnotationTransferItem[]): AnnotationTransferItem[] { + const seenIds = new Set(); + const allowedSubtypes = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15]); + + return allItems.filter(item => { + const ann = item.annotation; + const id = ann?.id; + if (!id || seenIds.has(id)) return false; + + // Strict whitelist check + const type = ann?.type as number; + if (!allowedSubtypes.has(type)) return false; + + // Only allow if it's in our DB-tracked set (for sync) + if (!this.dbAnnotationIds.has(id)) return false; + + seenIds.add(id); + return true; + }); + } + + private normalizeZoom(zoom: string): string { + const map: Record = { + 'page-fit': 'fit-page', + 'page-width': 'fit-width', + }; + const mapped = map[zoom] ?? zoom; + // Ensure numerical zoom has % suffix for EmbedPDF + if (mapped && /^\d+$/.test(mapped)) { + return mapped + '%'; + } + return mapped; + } } diff --git a/frontend/src/app/features/readers/pdf-reader/services/embedpdf-book.service.ts b/frontend/src/app/features/readers/pdf-reader/services/embedpdf-book.service.ts new file mode 100644 index 000000000..dfe496f32 --- /dev/null +++ b/frontend/src/app/features/readers/pdf-reader/services/embedpdf-book.service.ts @@ -0,0 +1,669 @@ +import {Injectable, NgZone, inject} from '@angular/core'; +import {ReplaySubject, Subject} from 'rxjs'; +import type { + EmbedPdfContainer, + PluginRegistry, + ScrollCapability, + ZoomCapability, + ZoomMode, + AnnotationCapability, + AnnotationTransferItem, + BookmarkCapability, + PageChangeEvent, + AnnotationEvent, + SearchCapability, + SpreadCapability, + SpreadMode, + RotateCapability, + PanCapability, +} from '@embedpdf/snippet'; + +export interface PdfOutlineItem { + title: string; + pageIndex: number; + children: PdfOutlineItem[]; +} + +@Injectable() +export class EmbedPdfBookService { + private zone = inject(NgZone); + + private container: EmbedPdfContainer | null = null; + private registry: PluginRegistry | null = null; + private scroll: ScrollCapability | null = null; + private zoom: ZoomCapability | null = null; + private annotation: AnnotationCapability | null = null; + private bookmark: BookmarkCapability | null = null; + private search: SearchCapability | null = null; + private spread: SpreadCapability | null = null; + private rotate: RotateCapability | null = null; + private pan: PanCapability | null = null; + + private currentDocumentId: string | null = null; + + private pageChangeUnsub?: () => void; + + private annotationEventUnsub?: () => void; + private layoutReadyUnsub?: () => void; + private documentOpenedUnsub?: () => void; + private resizeObserver?: ResizeObserver; + + pageChange$ = new Subject(); + annotationEvent$ = new Subject(); + documentOpened$ = new ReplaySubject<{pageCount: number}>(1); + layoutReady$ = new ReplaySubject(1); + + get currentPage(): number { + return this.scroll?.getCurrentPage() ?? 1; + } + + get totalPages(): number { + return this.scroll?.getTotalPages() ?? 0; + } + + async init(target: HTMLElement, pdfUrl: string, theme: 'dark' | 'light'): Promise { + // Recreate event streams so the service is reusable after destroy() + this.pageChange$ = new Subject(); + this.annotationEvent$ = new Subject(); + this.documentOpened$ = new ReplaySubject<{pageCount: number}>(1); + this.layoutReady$ = new ReplaySubject(1); + + this.applyWorkerShims(); + this.ensureHighDpiRendering(); + this.patchReleasePointerCapture(); + + const EmbedPDF = (await import('@embedpdf/snippet')).default; + + const wasmUrl = new URL('/assets/pdfium/pdfium.wasm', location.origin).href; + + this.container = EmbedPDF.init({ + type: 'container', + target, + src: pdfUrl, + wasmUrl, + worker: true, + log: false, + theme: {preference: theme}, + disabledCategories: [ + 'redaction', + 'stamp', + 'document-print', + 'document-export', + 'document-open', + 'document-close', + ], + annotations: { + autoCommit: true, + autoOpenLinks: false, + }, + zoom: { + defaultZoomLevel: 'fit-page' as ZoomMode, + }, + render: { + defaultImageQuality: 2, + }, + tiling: { + tileSize: 1024, + overlapPx: 2, + extraRings: 1, + }, + }) ?? null; + + if (!this.container) { + throw new Error('EmbedPDF.init() returned undefined'); + } + + this.zone.runOutsideAngular(() => { + this.injectBookModeStyles(target); + this.setupResizeObserver(target); + }); + + this.registry = await this.container.registry; + + const scrollPlugin = this.registry.getPlugin('scroll'); + this.scroll = scrollPlugin?.provides?.() as ScrollCapability ?? null; + + const zoomPlugin = this.registry.getPlugin('zoom'); + this.zoom = zoomPlugin?.provides?.() as ZoomCapability ?? null; + + const annotationPlugin = this.registry.getPlugin('annotation'); + this.annotation = annotationPlugin?.provides?.() as AnnotationCapability ?? null; + + const bookmarkPlugin = this.registry.getPlugin('bookmark'); + this.bookmark = bookmarkPlugin?.provides?.() as BookmarkCapability ?? null; + + const searchPlugin = this.registry.getPlugin('search'); + this.search = searchPlugin?.provides?.() as SearchCapability ?? null; + + const spreadPlugin = this.registry.getPlugin('spread'); + this.spread = spreadPlugin?.provides?.() as SpreadCapability ?? null; + + const rotatePlugin = this.registry.getPlugin('rotate'); + this.rotate = rotatePlugin?.provides?.() as RotateCapability ?? null; + + const panPlugin = this.registry.getPlugin('pan'); + this.pan = panPlugin?.provides?.() as PanCapability ?? null; + + // wire events + if (this.scroll) { + this.pageChangeUnsub = this.scroll.onPageChange((ev: PageChangeEvent) => { + this.pageChange$.next(ev); + }); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (typeof (this.scroll as any).onLayoutReady === 'function') { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.layoutReadyUnsub = (this.scroll as any).onLayoutReady(() => { + this.zone.run(() => this.layoutReady$.next()); + }); + } + } + + // Listen for document opened via document-manager plugin + const dmPlugin = this.registry.getPlugin('document-manager'); + const dm = dmPlugin?.provides?.() as Record | null; + if (dm && typeof dm['onDocumentOpened'] === 'function') { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.documentOpenedUnsub = (dm['onDocumentOpened'] as (cb: (ev: any) => void) => () => void)((ev: {id: string, pageCount?: number}) => { + this.zone.run(() => { + this.currentDocumentId = ev.id; + this.documentOpened$.next({pageCount: ev?.pageCount ?? this.scroll?.getTotalPages() ?? 0}); + }); + }); + } else { + // Fallback: emit after a delay once scroll is ready + this.zone.runOutsideAngular(() => { + setTimeout(() => { + this.zone.run(() => { + this.documentOpened$.next({pageCount: this.scroll?.getTotalPages() ?? 0}); + }); + }, 500); + }); + } + + if (this.annotation) { + console.info('[EmbedPDF] Annotation plugin found, hooking events'); + this.annotationEventUnsub = this.annotation.onAnnotationEvent((ev: AnnotationEvent) => { + console.info('[EmbedPDF] Annotation event:', ev.type); + this.annotationEvent$.next(ev); + }); + } else { + console.warn('[EmbedPDF] Annotation plugin NOT found — events will not fire'); + } + } + + setTheme(theme: 'dark' | 'light'): void { + this.container?.setTheme(theme); + } + + scrollToPage(pageNumber: number, behavior: 'instant' | 'smooth' = 'smooth'): void { + this.scroll?.scrollToPage({pageNumber, behavior}); + } + + scrollToNextPage(): void { + this.scroll?.scrollToNextPage('smooth'); + } + + scrollToPreviousPage(): void { + this.scroll?.scrollToPreviousPage('smooth'); + } + + zoomIn(): void { + this.zoom?.zoomIn(); + } + + zoomOut(): void { + this.zoom?.zoomOut(); + } + + setZoomLevel(level: string): void { + this.zoom?.requestZoom(level as ZoomMode); + } + + // --- Search --- + + startSearch(): void { + this.search?.startSearch(); + } + + stopSearch(): void { + this.search?.stopSearch(); + } + + searchAllPages(keyword: string): void { + if (!this.search) return; + const docId = this.currentDocumentId || undefined; + const task = this.search.searchAllPages(keyword, docId); + // After search completes, scroll to the first result + task.wait(() => { + this.scrollToActiveSearchResult(); + }, () => { /* search failed or cancelled */ }); + } + + nextSearchResult(): void { + if (!this.search) return; + const docId = this.currentDocumentId || undefined; + this.search.nextResult(docId); + this.scrollToActiveSearchResult(); + } + + previousSearchResult(): void { + if (!this.search) return; + const docId = this.currentDocumentId || undefined; + this.search.previousResult(docId); + this.scrollToActiveSearchResult(); + } + + private scrollToActiveSearchResult(): void { + if (!this.search) return; + const docId = this.currentDocumentId || undefined; + const state = this.search.getState(docId); + if (!state || state.results.length === 0 || state.activeResultIndex < 0) return; + const result = state.results[state.activeResultIndex]; + if (result) { + this.scrollToPage(result.pageIndex + 1, 'smooth'); + } + } + + // --- Spread/Layout --- + + getSpreadMode(): string { + return this.spread?.getSpreadMode?.() ?? 'none'; + } + + setSpreadMode(mode: string): void { + this.spread?.setSpreadMode?.(mode as SpreadMode); + } + + // --- Rotation --- + + rotateClockwise(): void { + this.rotate?.rotateForward?.(); + } + + rotateCounterClockwise(): void { + this.rotate?.rotateBackward?.(); + } + + // --- Pan --- + + isPanMode(): boolean { + return this.pan?.isPanMode() ?? false; + } + + setPanMode(enabled: boolean): void { + if (enabled) { + this.pan?.enablePan(); + } else { + this.pan?.disablePan(); + } + } + + setActiveTool(toolId: string | null): void { + this.annotation?.setActiveTool(toolId); + } + + getActiveTool(): string | null { + const tool = this.annotation?.getActiveTool(); + return tool?.id ?? null; + } + + async importAnnotations(items: AnnotationTransferItem[]): Promise { + if (!this.annotation || items.length === 0) return; + const result = this.annotation.importAnnotations(items) as unknown; + interface EpdfTask { wait: (res: (v?: unknown) => void, rej: (e?: unknown) => void) => void; } + + if (result && typeof result === 'object' && 'wait' in result) { + const task = result as EpdfTask; + if (typeof task.wait === 'function') { + return new Promise((resolve, reject) => { + task.wait(() => resolve(), (err) => reject(err)); + }); + } + } + } + + deleteAnnotation(pageIndex: number, annotationId: string): void { + this.annotation?.deleteAnnotation(pageIndex, annotationId); + } + + async exportAnnotations(): Promise { + if (!this.annotation) return []; + return this.annotation.exportAnnotations().toPromise(); + } + + async getOutline(): Promise { + if (!this.bookmark) return []; + try { + const result = await new Promise<{bookmarks: unknown[]}>((resolve, reject) => { + this.bookmark!.getBookmarks().wait(resolve, reject); + }); + return this.convertBookmarks(result.bookmarks); + } catch { + return []; + } + } + + destroy(): void { + this.pageChangeUnsub?.(); + this.annotationEventUnsub?.(); + this.layoutReadyUnsub?.(); + this.documentOpenedUnsub?.(); + this.resizeObserver?.disconnect(); + this.resizeObserver = undefined; + + this.pageChange$.complete(); + this.annotationEvent$.complete(); + this.documentOpened$.complete(); + this.layoutReady$.complete(); + + if (this.container) { + this.container.remove(); + this.container = null; + } + + this.registry = null; + this.scroll = null; + this.zoom = null; + this.annotation = null; + this.bookmark = null; + this.search = null; + this.spread = null; + this.rotate = null; + this.pan = null; + this.currentDocumentId = null; + + this.restoreWorkerShims(); + this.restoreReleasePointerCapture(); + this.restoreDevicePixelRatio(); + } + + private convertBookmarks(items: unknown[]): PdfOutlineItem[] { + if (!Array.isArray(items)) return []; + + interface EpdfBookmark { + title?: string; + target?: { + type?: 'destination' | 'action' | string; + destination?: {pageIndex?: number}; + action?: { + type?: number; + destination?: {pageIndex?: number}; + }; + }; + children?: unknown[]; + } + + return items.map((item: unknown) => { + const entry = item as EpdfBookmark; + let pageIndex = 0; + + const target = entry.target; + if (target) { + if (target.type === 'destination') { + pageIndex = target.destination?.pageIndex ?? 0; + } else if (target.type === 'action' && target.action?.type === 1) { + // Type 1 is PdfActionType.Goto (internal to PDF viewer) + pageIndex = target.action.destination?.pageIndex ?? 0; + } + } + + return { + title: String(entry.title || ''), + pageIndex: pageIndex, + children: this.convertBookmarks(entry.children || []), + }; + }); + } + + /** + * Ensure devicePixelRatio reports at least 2 so that the EmbedPDF tiling + * and render layers always produce high-resolution bitmaps. + * The library reads window.devicePixelRatio at tile-render time; if the + * browser reports 1 (e.g. some WebViews or forced-desktop viewports), + * PDF pages appear noticeably pixelated. + */ + private ensureHighDpiRendering(): void { + const MIN_DPR = 2; + if (window.devicePixelRatio < MIN_DPR) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const w = window as any; + w.__grimmoryOrigDprDescriptor = Object.getOwnPropertyDescriptor(window, 'devicePixelRatio'); + Object.defineProperty(window, 'devicePixelRatio', { + get: () => MIN_DPR, + configurable: true, + }); + } + } + + /** + * Apply the same Worker/Blob shims that embedpdf-frame.html uses. + * EmbedPDF creates a blob-URL module Worker for PDFium WASM. Some browsers + * (or bundler setups) swallow the "ready" postMessage from the worker. + * These shims: + * 1) Patch Blob to inject `self.postMessage({type:"ready"})` after `runner.prepare()`. + * 2) Patch Worker to inject a fallback synthetic "ready" if the real one never arrives. + * Idempotent — safe to call multiple times. + */ + private applyWorkerShims(): void { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const w = window as any; + if (w.__grimmoryShimsApplied) return; + w.__grimmoryShimsApplied = true; + + // --- Blob shim --- + const OrigBlob = window.Blob; + w.__grimmoryOrigBlob = OrigBlob; + w.Blob = function PatchedBlob(parts: BlobPart[], opts?: BlobPropertyBag) { + if (parts?.length >= 1 && typeof parts[0] === 'string') { + const src = parts[0] as string; + if (src.includes('wasmInit') && src.includes('runner.prepare()')) { + let patched = src; + patched = patched.replace( + 'self.postMessage({ type: "wasmError", error: message });', + 'console.error("[Worker] WASM init FAILED:", message);\n' + + ' self.postMessage({ type: "wasmError", error: message });' + ); + patched = patched.replace( + 'await runner.prepare();', + 'await runner.prepare();\n' + + ' console.log("[Worker] prepare() OK, posting ready");\n' + + ' self.postMessage({ type: "ready" });' + ); + parts = [patched]; + } + } + return new OrigBlob(parts, opts); + }; + w.Blob.prototype = OrigBlob.prototype; + Object.setPrototypeOf(w.Blob, OrigBlob); + + // --- Worker shim --- + const OrigWorker = window.Worker; + w.__grimmoryOrigWorker = OrigWorker; + w.Worker = function PatchedWorker(url: string | URL, opts?: WorkerOptions) { + const worker = new OrigWorker(url, opts); + const urlStr = typeof url === 'string' ? url : url.toString(); + if (urlStr.startsWith('blob:') && opts?.type === 'module') { + let readySent = false; + let wasmError = false; + setTimeout(() => { + if (!readySent && !wasmError) { + readySent = true; + worker.dispatchEvent(new MessageEvent('message', { + data: {type: 'ready'} + })); + } + }, 5000); + worker.addEventListener('message', (evt: MessageEvent) => { + if (evt.data?.type === 'ready') readySent = true; + if (evt.data?.type === 'wasmError') wasmError = true; + }); + } + return worker; + }; + w.Worker.prototype = OrigWorker.prototype; + Object.setPrototypeOf(w.Worker, OrigWorker); + } + + private restoreWorkerShims(): void { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const w = window as any; + if (!w.__grimmoryShimsApplied) return; + if (w.__grimmoryOrigBlob) { + window.Blob = w.__grimmoryOrigBlob; + delete w.__grimmoryOrigBlob; + } + if (w.__grimmoryOrigWorker) { + window.Worker = w.__grimmoryOrigWorker; + delete w.__grimmoryOrigWorker; + } + delete w.__grimmoryShimsApplied; + } + + /** + * Patch Element.prototype.releasePointerCapture to swallow "Invalid pointer id" + * DOMExceptions thrown by EmbedPDF's internal Svelte rendering during + * annotation drag/resize interactions. The error is benign—the pointer has + * already been released by the time the cleanup call fires. + */ + private patchReleasePointerCapture(): void { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const w = window as any; + if (w.__grimmoryOrigRelease) return; + const orig = Element.prototype.releasePointerCapture; + w.__grimmoryOrigRelease = orig; + Element.prototype.releasePointerCapture = function (pointerId: number) { + try { + orig.call(this, pointerId); + } catch (e) { + if (!(e instanceof DOMException && e.message.includes('pointer'))) throw e; + } + }; + } + + private restoreReleasePointerCapture(): void { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const w = window as any; + if (w.__grimmoryOrigRelease) { + Element.prototype.releasePointerCapture = w.__grimmoryOrigRelease; + delete w.__grimmoryOrigRelease; + } + } + + private restoreDevicePixelRatio(): void { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const w = window as any; + if (w.__grimmoryOrigDprDescriptor) { + Object.defineProperty(window, 'devicePixelRatio', w.__grimmoryOrigDprDescriptor); + delete w.__grimmoryOrigDprDescriptor; + } else if (Object.getOwnPropertyDescriptor(window, 'devicePixelRatio')?.configurable) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + delete (window as any)['devicePixelRatio']; + } + } + + private injectBookModeStyles(target: HTMLElement): void { + const waitForShadow = (attempt = 0): void => { + const epContainer = target.querySelector('embedpdf-container'); + const shadow = epContainer?.shadowRoot; + if (!shadow) { + if (attempt < 25) setTimeout(() => waitForShadow(attempt + 1), 200); + return; + } + if (shadow.querySelector('style[data-grimmory-book]')) return; + + const style = document.createElement('style'); + style.setAttribute('data-grimmory-book', ''); + style.textContent = ` + /* ── Grimmory book-mode overrides ── */ + + /* Force high-quality image rendering for PDF tiles */ + img { + image-rendering: high-quality; + -webkit-font-smoothing: antialiased; + } + + :host { + --ep-background-app: #1a1a1a; + --ep-background-surface: #2d2d2d; + --ep-border-default: #404040; + --ep-border-subtle: #333333; + --ep-foreground-primary: rgba(255,255,255,0.95); + --ep-foreground-secondary: rgba(255,255,255,0.60); + --ep-accent-primary: #4a90e2; + } + + :host([data-color-scheme="light"]) { + --ep-background-app: #f5f5f5; + --ep-background-surface: #ffffff; + --ep-border-default: #d0d0d0; + --ep-border-subtle: #e0e0e0; + --ep-foreground-primary: rgba(0,0,0,0.87); + --ep-foreground-secondary: rgba(0,0,0,0.54); + } + + /* Hide the built-in header toolbar */ + [class*="border-b"][class*="bg-bg-surface"][class*="px-4"][class*="py-2"] { + display: none !important; + } + + /* Hide the built-in footer/status bar */ + [class*="border-t"][class*="bg-bg-surface"][class*="px-4"][class*="py-1"] { + display: none !important; + } + + /* Hide bottom notification / popup bar */ + [class*="fixed"][class*="bottom-"], + [class*="absolute"][class*="bottom-"], + [class*="snackbar"], + [class*="toast"], + [class*="notification"], + [class*="bottom-bar"], + [class*="status-bar"], + [class*="statusbar"] { + display: none !important; + } + + /* Hide open/close document buttons */ + [data-epdf-i="open-document"], + [data-epdf-i="close-document"], + button[title="Open Document"], + button[title="Close Document"] { + display: none !important; + } + + + /* Improve annotation layer rendering on touch devices. + + /* Improve annotation layer rendering on touch devices. + FreeText annotation overlays can bleed through when the + appearance-stream image has not finished loading. Prevent the + interactive text span from blocking the rendered image. */ + [role="textbox"][contenteditable="false"] { + pointer-events: none; + } + `; + shadow.appendChild(style); + }; + waitForShadow(); + } + + private setupResizeObserver(target: HTMLElement): void { + if (typeof ResizeObserver === 'undefined') return; + + this.resizeObserver = new ResizeObserver(() => { + // When the target container resizes (e.g. mobile chrome change), + // some engines might need a nudge to recalculate "fit-page" zoom correctly. + if (this.zoom && this.getSpreadMode() === 'none') { + const state = this.zoom.getState(); + if (state.zoomLevel === 'fit-page') { + // Re-request same zoom mode to trigger recalculation + this.zoom.requestZoom('fit-page' as ZoomMode); + } + } + }); + this.resizeObserver.observe(target); + this.layoutReady$.subscribe(() => this.resizeObserver?.disconnect()); + } +} diff --git a/frontend/src/app/features/readers/pdf-reader/services/pdf-bookmark.service.ts b/frontend/src/app/features/readers/pdf-reader/services/pdf-bookmark.service.ts new file mode 100644 index 000000000..85d0c4300 --- /dev/null +++ b/frontend/src/app/features/readers/pdf-reader/services/pdf-bookmark.service.ts @@ -0,0 +1,117 @@ +import {Injectable, inject} from '@angular/core'; +import {Observable, of} from 'rxjs'; +import {catchError, map, tap} from 'rxjs/operators'; +import {BookMark, BookMarkService, CreateBookMarkRequest} from '../../../../shared/service/book-mark.service'; +import {MessageService} from 'primeng/api'; +import {TranslocoService} from '@jsverse/transloco'; + +@Injectable() +export class PdfBookmarkService { + private bookMarkService = inject(BookMarkService); + private messageService = inject(MessageService); + private readonly t = inject(TranslocoService); + + private bookmarks = new Map(); + private bookId!: number; + + initialize(bookId: number): void { + this.bookId = bookId; + this.bookmarks.clear(); + } + + loadBookmarks(): Observable { + return this.bookMarkService.getBookmarksForBook(this.bookId).pipe( + tap(bookmarks => { + this.bookmarks.clear(); + for (const bm of bookmarks) { + if (bm.pageNumber != null) { + this.bookmarks.set(bm.pageNumber, bm); + } + } + }), + map(bookmarks => bookmarks.filter(bm => bm.pageNumber != null)), + catchError(() => { + this.bookmarks.clear(); + return of([]); + }) + ); + } + + isPageBookmarked(pageNumber: number): boolean { + return this.bookmarks.has(pageNumber); + } + + getBookmarkForPage(pageNumber: number): BookMark | undefined { + return this.bookmarks.get(pageNumber); + } + + getAllBookmarks(): BookMark[] { + return Array.from(this.bookmarks.values()).sort((a, b) => (a.pageNumber ?? 0) - (b.pageNumber ?? 0)); + } + + toggleBookmark(pageNumber: number, title?: string): Observable { + const existing = this.bookmarks.get(pageNumber); + if (existing) { + return this.deleteBookmark(existing.id); + } + return this.createBookmark(pageNumber, title); + } + + createBookmark(pageNumber: number, title?: string): Observable { + const request: CreateBookMarkRequest = { + bookId: this.bookId, + pageNumber, + title: title || `Page ${pageNumber}`, + }; + + return this.bookMarkService.createBookmark(request).pipe( + map(bookmark => { + this.bookmarks.set(pageNumber, bookmark); + this.messageService.add({ + severity: 'success', + summary: this.t.translate('readerPdf.toast.bookmarkAdded'), + }); + return true; + }), + catchError(error => { + const isDuplicate = error?.status === 409; + if (isDuplicate) { + // Hydrate cache: server already has this bookmark + this.loadBookmarks().subscribe(); + } + this.messageService.add( + isDuplicate + ? {severity: 'warn', summary: this.t.translate('readerPdf.toast.bookmarkExists')} + : {severity: 'error', summary: this.t.translate('common.error')} + ); + return of(false); + }) + ); + } + + deleteBookmark(bookmarkId: number): Observable { + return this.bookMarkService.deleteBookmark(bookmarkId).pipe( + map(() => { + for (const [page, bm] of this.bookmarks) { + if (bm.id === bookmarkId) { + this.bookmarks.delete(page); + break; + } + } + this.messageService.add({ + severity: 'info', + summary: this.t.translate('readerPdf.toast.bookmarkRemoved'), + }); + return true; + }), + catchError(() => { + this.messageService.add({severity: 'error', summary: this.t.translate('common.error')}); + return of(false); + }) + ); + } + + reset(): void { + this.bookmarks.clear(); + } +} diff --git a/frontend/src/app/features/readers/pdf-reader/utils/annotation-converter.ts b/frontend/src/app/features/readers/pdf-reader/utils/annotation-converter.ts new file mode 100644 index 000000000..201f78280 --- /dev/null +++ b/frontend/src/app/features/readers/pdf-reader/utils/annotation-converter.ts @@ -0,0 +1,248 @@ +import type {AnnotationTransferItem} from '@embedpdf/snippet'; + +/** + * Stored annotation wrapper format. + * Legacy pdf.js annotations are raw arrays with `annotationType` keys. + * New format wraps EmbedPDF AnnotationTransferItem[] in a versioned envelope. + */ +export interface StoredAnnotations { + format: 'embedpdf'; + version: 1; + annotations: AnnotationTransferItem[]; +} + +/** + * Detect and parse stored annotation data. + * Returns EmbedPDF AnnotationTransferItems ready for import, or empty array. + */ +export function parseStoredAnnotations(jsonString: string | null | undefined): AnnotationTransferItem[] { + if (!jsonString) return []; + + try { + const parsed = JSON.parse(jsonString); + + // New format: { format: 'embedpdf', version: 1, annotations: [...] } + if (parsed && parsed.format === 'embedpdf' && Array.isArray(parsed.annotations)) { + return parsed.annotations.map(restoreArrayBuffers); + } + + // Legacy pdf.js format: raw array of editor annotations + if (Array.isArray(parsed)) { + return convertLegacyAnnotations(parsed); + } + + return []; + } catch { + return []; + } +} + +/** + * Wrap EmbedPDF annotations in the versioned envelope for storage. + * Handles ArrayBuffer fields (e.g. stamp ctx.data) by encoding to base64. + */ +export function serializeAnnotations(items: AnnotationTransferItem[]): string { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const serializable = items.map((item: any) => { + if (item.ctx?.data instanceof ArrayBuffer) { + return { + ...item, + ctx: { + ...item.ctx, + data: arrayBufferToBase64(item.ctx.data), + _dataEncoding: 'base64', + }, + }; + } + return item; + }); + const wrapped = { + format: 'embedpdf' as const, + version: 1 as const, + annotations: serializable as AnnotationTransferItem[], + }; + return JSON.stringify(wrapped); +} + +/** + * Best-effort conversion of legacy pdf.js editor annotations. + * These are the serialized annotations from ngx-extended-pdf-viewer's + * getSerializedAnnotations() which outputs pdf.js editor format. + * + * This is a lossy conversion not all annotation types or properties + * can be fully mapped. After the first save in the new format, + * legacy data is overwritten. + */ +function convertLegacyAnnotations(legacyAnnotations: Record[]): AnnotationTransferItem[] { + const items: AnnotationTransferItem[] = []; + + for (const legacy of legacyAnnotations) { + try { + const item = convertSingleAnnotation(legacy); + if (item) { + items.push(item); + } + } catch { + // Skip annotations that can't be converted + } + } + + return items; +} + +function convertSingleAnnotation(legacy: Record): AnnotationTransferItem | null { + const annotationType = legacy['annotationType'] as number | undefined; + + // pdf.js annotation editor types: + // 3 = freetext, 9 = highlight, 15 = ink + switch (annotationType) { + case 9: // highlight + return convertHighlight(legacy); + case 15: // ink + return convertInk(legacy); + case 3: // freetext + return convertFreeText(legacy); + default: + return null; + } +} + +function convertHighlight(legacy: Record): AnnotationTransferItem | null { + const color = legacy['color'] as number[] | undefined; + const pageIndex = (legacy['pageIndex'] as number) ?? 0; + const rect = legacy['rect'] as number[] | undefined; + + if (!rect || rect.length < 4) return null; + + const hexColor = color ? rgbArrayToHex(color) : '#FFFF00'; + const x = rect[0]; + const y = rect[1]; + const w = rect[2] - rect[0]; + const h = rect[3] - rect[1]; + + return { + annotation: { + type: 9, // PdfAnnotationSubtype.HIGHLIGHT + pageIndex, + rect: {origin: {x, y}, size: {width: w, height: h}}, + segmentRects: [{origin: {x, y}, size: {width: w, height: h}}], + color: hexColor, + opacity: (legacy['opacity'] as number) ?? 1, + id: crypto.randomUUID(), + } as never, + }; +} + +function convertInk(legacy: Record): AnnotationTransferItem | null { + const color = legacy['color'] as number[] | undefined; + const pageIndex = (legacy['pageIndex'] as number) ?? 0; + const paths = legacy['paths'] as {bezier: number[]}[] | number[][][] | undefined; + const thickness = (legacy['thickness'] as number) ?? 1; + + if (!paths) return null; + + const hexColor = color ? rgbArrayToHex(color) : '#000000'; + + // pdf.js ink paths can be bezier arrays or point arrays + const inkList: {points: {x: number; y: number}[]}[] = []; + for (const path of paths) { + if (Array.isArray(path) && Array.isArray(path[0])) { + // Array of point pairs + const points = (path as number[][]).map(p => ({x: p[0], y: p[1]})); + inkList.push({points}); + } else if (typeof path === 'object' && 'bezier' in (path as Record)) { + // Bezier curve data - extract control points + const bezier = (path as {bezier: number[]}).bezier; + const points: {x: number; y: number}[] = []; + for (let i = 0; i < bezier.length; i += 2) { + points.push({x: bezier[i], y: bezier[i + 1]}); + } + inkList.push({points}); + } + } + + if (inkList.length === 0) return null; + + return { + annotation: { + type: 15, // PdfAnnotationSubtype.INK + pageIndex, + rect: {origin: {x: 0, y: 0}, size: {width: 0, height: 0}}, + color: hexColor, + strokeWidth: thickness, + opacity: 1, + inkList, + id: crypto.randomUUID(), + } as never, + }; +} + +function convertFreeText(legacy: Record): AnnotationTransferItem | null { + const pageIndex = (legacy['pageIndex'] as number) ?? 0; + const rect = legacy['rect'] as number[] | undefined; + const value = (legacy['value'] as string) ?? ''; + const fontSize = (legacy['fontSize'] as number) ?? 12; + const color = legacy['color'] as number[] | undefined; + + if (!rect || rect.length < 4) return null; + + const x = rect[0]; + const y = rect[1]; + const w = rect[2] - rect[0]; + const h = rect[3] - rect[1]; + + return { + annotation: { + type: 3, // PdfAnnotationSubtype.FREETEXT + pageIndex, + rect: {origin: {x, y}, size: {width: w, height: h}}, + contents: value, + fontSize, + fontColor: color ? rgbArrayToHex(color) : '#000000', + id: crypto.randomUUID(), + } as never, + }; +} + +function rgbArrayToHex(rgb: number[]): string { + const r = Math.round(Math.min(255, Math.max(0, rgb[0] * 255))); + const g = Math.round(Math.min(255, Math.max(0, rgb[1] * 255))); + const b = Math.round(Math.min(255, Math.max(0, rgb[2] * 255))); + return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`.toUpperCase(); +} + +// --- ArrayBuffer <-> base64 helpers --- + +function arrayBufferToBase64(buffer: ArrayBuffer): string { + const bytes = new Uint8Array(buffer); + let binary = ''; + for (const byte of bytes) { + binary += String.fromCharCode(byte); + } + return btoa(binary); +} + +function base64ToArrayBuffer(base64: string): ArrayBuffer { + const binary = atob(base64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + return bytes.buffer; +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function restoreArrayBuffers(item: any): AnnotationTransferItem { + if (item.ctx?._dataEncoding === 'base64' && typeof item.ctx.data === 'string') { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const {_dataEncoding: _, ...rest} = item.ctx; + return { + ...item, + ctx: { + ...rest, + data: base64ToArrayBuffer(item.ctx.data), + }, + }; + } + return item; +} diff --git a/frontend/src/app/shared/service/book-mark.service.ts b/frontend/src/app/shared/service/book-mark.service.ts index 3d77f2a14..fabfb7702 100644 --- a/frontend/src/app/shared/service/book-mark.service.ts +++ b/frontend/src/app/shared/service/book-mark.service.ts @@ -10,6 +10,7 @@ export interface BookMark { cfi?: string; // For EPUB bookmarks positionMs?: number; // For audiobook bookmarks trackIndex?: number; // For folder-based audiobooks + pageNumber?: number; // For PDF bookmarks title: string; color?: string; notes?: string; @@ -23,12 +24,14 @@ export interface CreateBookMarkRequest { cfi?: string; // For EPUB bookmarks positionMs?: number; // For audiobook bookmarks trackIndex?: number; // For folder-based audiobooks + pageNumber?: number; // For PDF bookmarks title?: string; } export interface UpdateBookMarkRequest { title?: string; cfi?: string; + pageNumber?: number; color?: string; notes?: string; priority?: number; diff --git a/frontend/src/assets/embedpdf-frame.html b/frontend/src/assets/embedpdf-frame.html index a937ac912..d31cd1609 100644 --- a/frontend/src/assets/embedpdf-frame.html +++ b/frontend/src/assets/embedpdf-frame.html @@ -140,7 +140,7 @@ border-bottom-color: #404040 !important; box-shadow: 0 2px 8px rgba(0,0,0,0.30) !important; height: 38px !important; - padding-right: 48px !important; + padding-right: 88px !important; padding-top: 0 !important; padding-bottom: 0 !important; box-sizing: border-box !important; @@ -162,6 +162,7 @@ button[title="Close Document"] { display: none !important; } + .pdf-btn-open { display: none !important; } @@ -241,32 +242,65 @@ color: rgba(0,0,0,0.87) !important; border: 1px solid #d0d0d0 !important; } + + /* Force high-quality image rendering for PDF tiles */ + img { + image-rendering: high-quality; + -webkit-font-smoothing: antialiased; + } + /* ── Silence non-editable selection menus EXCEPT for navigation links ── */ + + /* If the menu has no user-editing tools OR navigation, hide the whole menu. */ + [role="toolbar"]:not(:has([data-epdf-i*="appearance"])):not(:has([data-epdf-i*="comment"])):not(:has([data-epdf-i*="navigate"])), + [role="menu"]:not(:has([data-epdf-i*="appearance"])):not(:has([data-epdf-i*="comment"])):not(:has([data-epdf-i*="navigate"])) { + display: none !important; + } + + /* Hide the 'Add Link' tool to prevent manual link creation */ + [data-epdf-i="link"] { + display: none !important; + } + + /* If the selection menu has a 'navigate' icon (Go to Link), hide the 'remove' (trash) button */ + [role="toolbar"]:has([data-epdf-i*="navigate"]) [data-epdf-i*="remove"], + [role="menu"]:has([data-epdf-i*="navigate"]) [data-epdf-i*="remove"] { + display: none !important; + } `; shadow.appendChild(style); - targetEl.style.visibility = ''; } - window.addEventListener('message', async (e) => { - if (e.origin !== myOrigin) return; - const msg = e.data; + window.addEventListener('message', async (event) => { + const msg = event.data; if (msg.type === 'init') { - log('Init, buffer:', msg.buffer?.byteLength, 'bytes'); - - const blob = new Blob([msg.buffer], { type: 'application/pdf' }); - objectUrl = URL.createObjectURL(blob); - + log('Init requested'); const target = document.getElementById('viewer'); - target.style.visibility = 'hidden'; + if (viewer) { + viewer.destroy(); + viewer = null; + } viewer = EmbedPDF.init({ type: 'container', - target, - src: objectUrl, - wasmUrl: new URL(msg.wasmUrl || '/assets/pdfium/pdfium.wasm', location.origin).href, - worker: true, - log: true, - theme: { preference: msg.theme || 'dark' } + target: target, + disabledCategories: [ + 'redaction', + 'stamp', + 'document-print', + 'document-export', + 'document-open', + 'document-close', + ], + annotations: { + autoCommit: true, + autoOpenLinks: false, + }, + zoom: { + defaultZoomLevel: 'fit-page', + }, + render: { defaultImageQuality: 2 }, + tiling: { tileSize: 1024, overlapPx: 2, extraRings: 1 }, }); injectGrimmoryStyles(target); @@ -287,13 +321,60 @@ log('Document closed:', ev?.documentId); }); } + + const scrollPlugin = registry.getPlugin('scroll')?.provides(); + if (scrollPlugin) { + scrollPlugin.onPageChange((ev) => { + parent.postMessage({ + type: 'pageChange', + pageNumber: ev.pageNumber, + totalPages: ev.totalPages + }, myOrigin); + }); + } + parent.postMessage({ type: 'ready' }, myOrigin); + + if (typeof ResizeObserver !== 'undefined') { + const observer = new ResizeObserver(() => { + const zoomPlugin = registry.getPlugin('zoom')?.provides(); + if (zoomPlugin) { + const state = zoomPlugin.getState(); + if (state.zoomLevel === 'fit-page') { + zoomPlugin.requestZoom('fit-page'); + } + } + }); + observer.observe(target); + } } catch (err) { log('Registry error:', err); parent.postMessage({ type: 'documentError', error: String(err) }, myOrigin); } } + if (msg.type === 'load') { + try { + if (!viewer) { + log('Load requested before init'); + return; + } + const dm = registry.getPlugin('document-manager')?.provides(); + if (!dm) { + log('Document manager plugin not found'); + return; + } + + if (objectUrl) URL.revokeObjectURL(objectUrl); + objectUrl = URL.createObjectURL(new Blob([msg.buffer], { type: 'application/pdf' })); + log('Loading PDF buffer into viewer'); + await dm.loadUrl(objectUrl); + } catch (err) { + log('Load error:', err); + parent.postMessage({ type: 'documentError', error: String(err) }, myOrigin); + } + } + if (msg.type === 'save') { try { if (!registry) { @@ -321,6 +402,21 @@ if (msg.type === 'setTheme') { viewer?.setTheme?.(msg.theme); } + + if (msg.type === 'scrollToPage') { + const scrollPlugin = registry?.getPlugin('scroll')?.provides(); + scrollPlugin?.scrollToPage({ pageNumber: msg.pageNumber, behavior: 'smooth' }); + } + + if (msg.type === 'nextPage') { + const scrollPlugin = registry?.getPlugin('scroll')?.provides(); + scrollPlugin?.scrollToNextPage('smooth'); + } + + if (msg.type === 'prevPage') { + const scrollPlugin = registry?.getPlugin('scroll')?.provides(); + scrollPlugin?.scrollToPreviousPage('smooth'); + } }); log('Frame loaded, waiting for init'); diff --git a/frontend/src/i18n/en/reader-ebook.json b/frontend/src/i18n/en/reader-ebook.json index 3b629e31f..55f2b281f 100644 --- a/frontend/src/i18n/en/reader-ebook.json +++ b/frontend/src/i18n/en/reader-ebook.json @@ -136,6 +136,8 @@ "searchInBook": "Search in book", "annotate": "Annotate", "addNote": "Add Note", + "goToLink": "Go to Link", + "removeLink": "Remove Link", "deleteAnnotation": "Delete Annotation" }, "shortcutsHelp": { diff --git a/frontend/src/i18n/en/reader-pdf.json b/frontend/src/i18n/en/reader-pdf.json index 5727d4dfe..ecdbfd230 100644 --- a/frontend/src/i18n/en/reader-pdf.json +++ b/frontend/src/i18n/en/reader-pdf.json @@ -3,9 +3,31 @@ "switchToLightMode": "Switch to Light Mode", "switchToDarkMode": "Switch to Dark Mode", "closePdfReader": "Close PDF Reader", - "rotatePage": "Rotate Page", "fullscreen": "Fullscreen", - "exitFullscreen": "Exit Fullscreen" + "exitFullscreen": "Exit Fullscreen", + "sidebar": "Contents", + "search": "Search", + "searchPlaceholder": "Search in document...", + "searchNext": "Next Result", + "searchPrevious": "Previous Result", + "zoomIn": "Zoom In", + "zoomOut": "Zoom Out", + "spreadMode": "Page Layout", + "rotatePage": "Rotate Page", + "bookmarkAdd": "Add Bookmark", + "bookmarkRemove": "Remove Bookmark", + "addBookmark": "Add Bookmark", + "removeBookmark": "Remove Bookmark", + "freeText": "Text Note", + "highlight": "Highlight", + "textNote": "Text Note", + "ink": "Free Draw", + "draw": "Free Draw", + "annotationColor": "Annotation Color", + "deselectTool": "Deselect Tool", + "pan": "Pan Mode", + "moreOptions": "More options", + "closeSearch": "Close search" }, "footer": { "firstPage": "First Page", @@ -15,12 +37,35 @@ "of": "of", "pageSlider": "Page Slider", "pagePlaceholder": "Page", - "go": "Go" + "go": "Go", + "bookViewer": "Book Viewer", + "docViewer": "Doc Viewer" + }, + "sidebar": { + "title": "Sidebar", + "close": "Close sidebar", + "contentsTab": "Contents", + "bookmarksTab": "Bookmarks", + "annotationsTab": "Annotations", + "noContents": "No table of contents available", + "noBookmarks": "No bookmarks yet", + "bookmarkHint": "Tap the bookmark icon to save your place", + "noAnnotations": "No annotations yet", + "annotationHint": "Use the highlight tool to annotate text", + "deleteBookmark": "Delete bookmark", + "deleteAnnotation": "Delete annotation", + "page": "Page" }, "toast": { - "failedToLoadBook": "Failed to load the book" + "failedToLoadBook": "Failed to load the book", + "bookmarkAdded": "Bookmark Added", + "bookmarkRemoved": "Bookmark Removed", + "bookmarkExists": "Bookmark already exists on this page", + "annotationSaved": "Annotations Saved", + "annotationFailed": "Failed to save annotations" }, "docViewer": { - "changesSavedInfo": "Changes are written to file here" + "changesSavedInfo": "Changes are written to file here", + "dismiss": "Dismiss" } }