feat(reader): add document mode to the PDF viewer, overhaul PDF viewer, add different modes to CBX viewer (#306)

* feat(reader): add document mode to the PDF viewer, overhaul PDF viewer, add different modes to CBX viewer

* feat(reader): improve reader settings with brightness, emulate book mode, and click-to-paginate options

* feat(reader): add long strip scroll mode and update related settings
This commit is contained in:
brios
2026-04-22 17:26:57 -04:00
committed by Zach Yale
parent a3add5ded9
commit 61b9b53a60
47 changed files with 4458 additions and 874 deletions
@@ -1,79 +1,152 @@
@if (isLoading) {
<div class="loading-container">
<p-progressSpinner></p-progressSpinner>
</div>
<div class="loading-container">
<p-progressSpinner></p-progressSpinner>
</div>
}
@if (!isLoading) {
<ngx-extended-pdf-viewer
[src]="bookData"
[authorization]="authorization"
[textLayer]="true"
[showHandToolButton]="true"
[height]="'auto'"
[theme]="isDarkTheme ? 'dark' : 'light'"
[page]="page"
[rotation]="rotation"
[zoom]="zoom"
[spread]="spread"
[enablePrint]="canPrint"
[customToolbar]="additionalButtons"
(pagesLoaded)="onPdfPagesLoaded($event)"
(pageChange)="onPageChange($event)"
(zoomChange)="onZoomChange($event)"
(spreadChange)="onSpreadChange($event)"
(annotationEditorEvent)="onAnnotationEditorEvent()">
</ngx-extended-pdf-viewer>
<div class="pdf-reader-container" [class.dark]="isDarkTheme">
<ng-template #additionalButtons>
<div id="toolbarViewer">
<div id="toolbarViewerLeft">
<!-- Footer trigger zone -->
<div class="footer-trigger-zone" [class.inactive]="footerVisible" (mouseenter)="onFooterTriggerZoneEnter()"></div>
@if (viewerMode === 'book') {
<!-- Header trigger zone -->
<div class="header-trigger-zone" [class.inactive]="headerVisible" (mouseenter)="onHeaderTriggerZoneEnter()"></div>
}
@if (viewerMode === 'document') {
<button class="embed-close-btn icon-btn close-btn" [title]="'readerPdf.toolbar.closePdfReader' | transloco"
(click)="closeReader()">
<app-reader-icon name="close" [size]="20" />
</button>
<div id="embedpdf-viewer"></div>
}
<!-- Book PDF Viewer -->
@if (viewerMode === 'book') {
<ngx-extended-pdf-viewer [src]="bookData" [authorization]="authorization" [textLayer]="true"
[showHandToolButton]="true" [height]="'100%'" [theme]="isDarkTheme ? 'dark' : 'light'" [page]="page"
[rotation]="rotation" [zoom]="zoom" [spread]="spread" [enablePrint]="canPrint" [customToolbar]="pdfToolbar"
(pagesLoaded)="onPdfPagesLoaded($event)" (pageChange)="onPageChange($event)" (zoomChange)="onZoomChange($event)"
(spreadChange)="onSpreadChange($event)" (annotationEditorEvent)="onAnnotationEditorEvent()">
</ngx-extended-pdf-viewer>
}
<ng-template #pdfToolbar>
<div id="toolbarViewer" class="pdf-header-toolbar" [class.chrome-hidden]="!headerVisible">
<div class="header-left">
<pdf-toggle-sidebar></pdf-toggle-sidebar>
<pdf-find-button></pdf-find-button>
<pdf-paging-area></pdf-paging-area>
</div>
<pdf-zoom-toolbar></pdf-zoom-toolbar>
<div id="toolbarViewerRight" [class.pdf-dark]="isDarkTheme">
<pdf-hand-tool></pdf-hand-tool>
<pdf-select-tool></pdf-select-tool>
<pdf-rotate-page></pdf-rotate-page>
@if (canPrint) {
<pdf-print></pdf-print>
}
<pdf-no-spread></pdf-no-spread>
<pdf-even-spread></pdf-even-spread>
<pdf-odd-spread></pdf-odd-spread>
<pdf-infinite-scroll></pdf-infinite-scroll>
<pdf-horizontal-scroll></pdf-horizontal-scroll>
<pdf-vertical-scroll-mode></pdf-vertical-scroll-mode>
<pdf-wrapped-scroll-mode></pdf-wrapped-scroll-mode>
<pdf-single-page-mode></pdf-single-page-mode>
<pdf-book-mode></pdf-book-mode>
<div class="verticalToolbarSeparator hiddenSmallView"></div>
<pdf-toggle-secondary-toolbar></pdf-toggle-secondary-toolbar>
<div class="verticalToolbarSeparator"></div>
<span class="book-title">{{ bookTitle }}</span>
<div class="header-right">
<pdf-highlight-editor></pdf-highlight-editor>
<pdf-text-editor></pdf-text-editor>
<pdf-draw-editor></pdf-draw-editor>
<div class="verticalToolbarSeparator"></div>
<button class="toolbar-btn" [title]="isDarkTheme ? ('readerPdf.toolbar.switchToLightMode' | transloco) : ('readerPdf.toolbar.switchToDarkMode' | transloco)" (click)="isDarkTheme = !isDarkTheme">
<div class="separator"></div>
<pdf-zoom-toolbar></pdf-zoom-toolbar>
<div class="separator"></div>
<button class="icon-btn"
[title]="isDarkTheme ? ('readerPdf.toolbar.switchToLightMode' | transloco) : ('readerPdf.toolbar.switchToDarkMode' | transloco)"
(click)="toggleDarkTheme()">
@if (isDarkTheme) {
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="4" />
<path d="M12 2v2" />
<path d="M12 20v2" />
<path d="m4.93 4.93 1.41 1.41" />
<path d="m17.66 17.66 1.41 1.41" />
<path d="M2 12h2" />
<path d="M20 12h2" />
<path d="m6.34 17.66-1.41 1.41" />
<path d="m19.07 4.93-1.41 1.41" />
</svg>
} @else {
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none"
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" />
</svg>
}
</button>
<button id="closePdfReaderButton" class="close-reader-btn" [title]="'readerPdf.toolbar.closePdfReader' | transloco" (click)="closeReader()">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M18 6 6 18"/><path d="m6 6 12 12"/>
</svg>
<button class="icon-btn" (click)="toggleFullscreen()"
[title]="isFullscreen ? ('readerPdf.toolbar.exitFullscreen' | transloco) : ('readerPdf.toolbar.fullscreen' | transloco)">
@if (isFullscreen) {
<app-reader-icon name="fullscreen-exit" [size]="18" />
} @else {
<app-reader-icon name="fullscreen" [size]="18" />
}
</button>
<div class="separator"></div>
<pdf-toggle-secondary-toolbar></pdf-toggle-secondary-toolbar>
<button class="icon-btn close-btn" [title]="'readerPdf.toolbar.closePdfReader' | transloco"
(click)="closeReader()">
<app-reader-icon name="close" [size]="20" />
</button>
</div>
</div>
</ng-template>
}
<!-- Footer (shared across both viewer modes) -->
<div class="pdf-footer" [class.visible]="footerVisible">
<div class="page-nav-left">
<button class="nav-btn" (click)="goToFirstPage()" [disabled]="page <= 1"
[title]="'readerPdf.footer.firstPage' | transloco">
<app-reader-icon name="chevron-first" [size]="16" />
</button>
<button class="nav-btn" (click)="goToPreviousPage()" [disabled]="page <= 1"
[title]="'readerPdf.footer.previousPage' | transloco">
<app-reader-icon name="chevron-left" [size]="16" />
</button>
<div class="page-info">
<span class="current">{{ page }}</span>
<span class="total"> {{ 'readerPdf.footer.of' | transloco }} {{ totalPages }}</span>
</div>
<button class="nav-btn" (click)="goToNextPage()" [disabled]="page >= totalPages"
[title]="'readerPdf.footer.nextPage' | transloco">
<app-reader-icon name="chevron-right" [size]="16" />
</button>
<button class="nav-btn" (click)="goToLastPage()" [disabled]="page >= totalPages"
[title]="'readerPdf.footer.lastPage' | transloco">
<app-reader-icon name="chevron-last" [size]="16" />
</button>
</div>
<div class="page-controls">
<div class="slider-wrapper">
<input type="range" class="page-slider" [min]="1" [max]="totalPages" [value]="page"
(input)="onSliderChange($event)" list="pdf-page-ticks" [title]="'readerPdf.footer.pageSlider' | transloco" />
<datalist id="pdf-page-ticks">
@for (tick of sliderTicks; track tick) {
<option [value]="tick"></option>
}
</datalist>
</div>
<div class="goto-page">
<input type="number" [(ngModel)]="goToPageInput" [min]="1" [max]="totalPages"
[placeholder]="'readerPdf.footer.pagePlaceholder' | transloco" class="page-input"
(keyup.enter)="onGoToPage()" />
<button class="go-btn" (click)="onGoToPage()"
[disabled]="goToPageInput === null || goToPageInput < 1 || goToPageInput > totalPages">
{{ 'readerPdf.footer.go' | transloco }}
</button>
</div>
</div>
<div class="footer-spacer"></div>
<div class="viewer-mode-toggle">
<button class="toggle-btn toggle-book" [class.active]="viewerMode === 'book'" (click)="setViewerMode('book')">
<i class="pi pi-book"></i><span>Book Viewer</span>
</button>
<button class="toggle-btn toggle-doc" [class.active]="viewerMode === 'document'" (click)="setViewerMode('document')">
<i class="pi pi-file"></i><span>Doc Viewer</span>
</button>
</div>
</div>
</div>
}
@@ -1,46 +1,878 @@
@use 'sass:color';
/* stylelint-disable selector-id-pattern, selector-class-pattern -- targets ngx-extended-pdf-viewer / pdf.js internals */
// Design tokens matching CBX/E-Book readers
$header-height: 38px;
$footer-height: 52px;
$gradient-bg: linear-gradient(135deg, #2d2d2d 0%, #1f1f1f 100%);
$border-color: #404040;
$text-primary: rgb(255 255 255 / 95%);
$text-secondary: rgb(255 255 255 / 60%);
$active-color: #4a90e2;
$hover-bg: rgb(255 255 255 / 12%);
$transition-fast: 150ms ease;
// --- Loading ---
.loading-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
position: relative;
height: 100dvh;
background: #1a1a1a;
}
::ng-deep .toolbar-btn,
::ng-deep .close-reader-btn {
// --- Reader container ---
.pdf-reader-container {
position: fixed;
inset: 0;
display: flex;
flex-direction: column;
background: #1a1a1a;
z-index: 900;
}
// --- Trigger zones ---
.header-trigger-zone,
.footer-trigger-zone {
position: fixed;
left: 0;
right: 0;
z-index: 1001;
}
.header-trigger-zone {
top: 0;
height: 20px;
&.inactive {
pointer-events: none;
}
}
.footer-trigger-zone {
bottom: 0;
height: 30px;
&.inactive {
pointer-events: none;
}
}
// --- Header ---
// Child element styles for .pdf-header-toolbar (positioning is in ::ng-deep #toolbarViewer)
.pdf-header-toolbar {
.header-left,
.header-right {
display: flex;
align-items: center;
gap: 2px;
z-index: 1;
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%;
transform: translateX(-50%);
max-width: 40%;
padding: 0 12px;
text-align: center;
font-size: 14px;
font-weight: 500;
color: inherit;
pointer-events: none;
user-select: none;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.separator {
width: 1px;
height: 18px;
background: rgb(255 255 255 / 15%);
margin: 0 4px;
}
}
// --- Icon buttons ---
.icon-btn {
background: none;
border: none;
color: inherit;
cursor: pointer;
padding: 7px;
border-radius: 6px;
transition: background $transition-fast;
display: flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border: none;
border-radius: 6px;
background: transparent;
color: #2a2a2a;
&:hover {
background: $hover-bg;
}
&.close-btn:hover {
background: rgb(239 68 68 / 20%);
color: #ef4444;
}
}
// --- Override pdf.js component button styles ---
::ng-deep .pdf-btn-wrap {
button {
background: none !important;
border: none !important;
color: #fff !important;
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;
&:hover {
background: $hover-bg !important;
}
&.toggled,
&[aria-pressed="true"] {
color: $active-color !important;
background: rgb(74 144 226 / 15%) !important;
}
span {
display: none !important;
}
&::before {
color: inherit !important;
opacity: 1 !important;
}
}
}
// --- Footer ---
.pdf-footer {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: $footer-height;
padding: 0 16px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
z-index: 1002;
background: $gradient-bg;
border-top: 1px solid $border-color;
box-shadow: 0 -2px 8px rgb(0 0 0 / 30%);
color: $text-primary;
transform: translateY(100%);
opacity: 0;
pointer-events: none;
transition: transform 0.25s ease-out, opacity 0.25s ease-out;
&.visible {
transform: translateY(0);
opacity: 1;
pointer-events: auto;
}
}
.page-nav-left {
display: flex;
align-items: center;
gap: 8px;
flex: 0 0 auto;
}
.nav-btn {
background: rgb(51 51 51 / 90%);
border: 1px solid #555;
color: $text-primary;
padding: 6px 10px;
border-radius: 4px;
cursor: pointer;
margin-left: 4px;
margin-right: 2px;
transition: background-color 0.2s ease, color 0.2s ease;
transition: all $transition-fast;
display: flex;
align-items: center;
justify-content: center;
&:hover {
background: rgb(0 0 0 / 10%);
&:hover:not(:disabled) {
background: #4a4a4a;
border-color: #666;
}
svg {
flex-shrink: 0;
&:disabled {
background: #2a2a2a;
color: #666;
cursor: not-allowed;
border-color: #333;
}
}
::ng-deep .pdf-dark .toolbar-btn,
::ng-deep .pdf-dark .close-reader-btn {
color: #e8e8e8;
.page-info {
padding: 4px 12px;
background: rgb(255 255 255 / 10%);
border-radius: 4px;
font-size: 13px;
font-weight: 500;
min-width: 90px;
text-align: center;
&:hover {
background: rgb(255 255 255 / 15%);
.current {
color: $active-color;
font-weight: 600;
}
.total {
color: $text-secondary;
}
}
::ng-deep .close-reader-btn:hover {
color: #ff6b6b;
.page-controls {
display: flex;
align-items: center;
gap: 12px;
flex: 1;
justify-content: center;
}
.footer-spacer {
flex: 0 0 auto;
width: 0;
}
.slider-wrapper {
flex: 1;
display: flex;
align-items: center;
position: relative;
.page-slider {
width: 100%;
border-radius: 3px;
outline: none;
appearance: none;
background: none;
cursor: pointer;
&::-webkit-slider-runnable-track {
width: 100%;
height: 6px;
background: rgb(255 255 255 / 12%);
border-radius: 3px;
cursor: pointer;
}
&::-moz-range-track {
width: 100%;
height: 6px;
background: rgb(255 255 255 / 12%);
border-radius: 3px;
cursor: pointer;
}
&::-webkit-slider-thumb {
appearance: none;
width: 18px;
height: 18px;
border-radius: 50%;
background: $active-color;
cursor: pointer;
box-shadow: 0 2px 6px rgb(0 0 0 / 30%);
transition: transform $transition-fast;
margin-top: calc((6px - 18px) / 2);
}
&::-moz-range-thumb {
width: 18px;
height: 18px;
border-radius: 50%;
background: $active-color;
cursor: pointer;
border: none;
box-shadow: 0 2px 6px rgb(0 0 0 / 30%);
transition: transform $transition-fast;
}
}
datalist {
display: flex;
justify-content: space-between;
position: absolute;
width: 100%;
left: 0;
top: 50%;
transform: translateY(-50%);
pointer-events: none;
height: 10px;
option {
width: 0;
position: relative;
padding: 0;
&::before {
content: '';
position: absolute;
left: 50%;
transform: translateX(-50%);
width: 2px;
height: 10px;
background: rgb(255 255 255 / 50%);
top: 0;
}
}
}
}
.viewer-mode-toggle {
display: flex;
align-items: center;
.toggle-btn {
display: inline-flex;
align-items: center;
justify-content: center;
white-space: nowrap;
gap: 6px;
padding: 0 12px;
border: 1px solid var(--surface-border);
background: var(--surface-card);
color: var(--text-color-secondary);
cursor: pointer;
font-size: 0.85rem;
font-weight: 500;
transition: all 0.2s;
height: 30px;
&:hover {
color: var(--text-color);
background: var(--surface-hover);
}
&.active {
background: var(--primary-color);
color: var(--primary-color-text);
border-color: var(--primary-color);
z-index: 1;
}
&.toggle-book {
border-top-left-radius: 6px;
border-bottom-left-radius: 6px;
border-right: none;
}
&.toggle-doc {
border-top-right-radius: 6px;
border-bottom-right-radius: 6px;
}
}
}
.embed-pdf-warning {
position: absolute;
bottom: 80px;
left: 24px;
z-index: 1001;
background-color: var(--surface-card);
color: var(--text-color-secondary);
border: 1px solid var(--surface-border);
padding: 8px 16px;
border-radius: 20px;
display: flex;
align-items: center;
gap: 8px;
font-weight: 500;
font-size: 0.85rem;
box-shadow: 0 4px 6px rgb(0 0 0 / 10%);
pointer-events: none;
i {
font-size: 1rem;
color: var(--primary-color);
}
}
.embed-close-btn {
position: fixed;
top: 4px;
right: 12px;
z-index: 1010;
color: $text-primary;
padding: 7px;
}
#embedpdf-viewer {
width: 100%;
height: 100%;
flex: 1;
display: flex;
iframe {
width: 100%;
height: 100%;
border: none;
}
}
.goto-page {
display: flex;
align-items: center;
gap: 4px;
background: rgb(51 51 51 / 90%);
border-radius: 4px;
padding: 2px;
border: 1px solid #555;
.page-input {
width: 55px;
padding: 4px 6px;
border: none;
border-radius: 3px;
background: #404040;
color: $text-primary;
font-size: 12px;
text-align: center;
&:focus {
outline: none;
background: #4a4a4a;
}
&::placeholder {
color: rgb(255 255 255 / 30%);
}
}
.go-btn {
padding: 4px 8px;
border: none;
border-radius: 3px;
background: $active-color;
color: #fff;
font-size: 11px;
font-weight: 600;
cursor: pointer;
text-transform: uppercase;
transition: background $transition-fast;
&:hover:not(:disabled) {
background: color.adjust($active-color, $lightness: -10%);
}
&:disabled {
opacity: 0.4;
cursor: not-allowed;
}
}
}
// --- Override pdf.js viewer inner styles ---
::ng-deep {
// Make pdf viewer fill container
ngx-extended-pdf-viewer {
flex: 1;
display: block;
overflow: hidden;
#mainContainer {
background: #1a1a1a !important;
}
// 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;
}
}
// 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;
}
}
}
// --- Responsive ---
@media (width <= 768px) {
.pdf-footer {
height: auto;
padding: 8px 12px;
flex-wrap: wrap;
gap: 8px;
}
.page-controls {
order: -1;
width: 100%;
}
.goto-page {
display: none;
}
.zoom-controls {
display: none;
}
.header-right {
::ng-deep pdf-zoom-toolbar {
display: none !important;
}
}
.book-title {
display: none;
}
}
@@ -1,34 +1,40 @@
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {NgxExtendedPdfViewerModule, NgxExtendedPdfViewerService, pdfDefaultOptions, ZoomType} from 'ngx-extended-pdf-viewer';
import {PageTitleService} from "../../../shared/service/page-title.service";
import {BookService} from '../../book/service/book.service';
import {forkJoin, from, Subject, Subscription} from 'rxjs';
import {debounceTime, 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 { 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 { PageTitleService } from "../../../shared/service/page-title.service";
import { BookService } from '../../book/service/book.service';
import { forkJoin, from, Subject, Subscription } from 'rxjs';
import { debounceTime, 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 {ProgressSpinner} from 'primeng/progressspinner';
import {MessageService} from 'primeng/api';
import {TranslocoService, TranslocoPipe} from '@jsverse/transloco';
import {ReadingSessionService} from '../../../shared/service/reading-session.service';
import {Location} from '@angular/common';
import { ProgressSpinner } from 'primeng/progressspinner';
import { MessageService } from 'primeng/api';
import { TranslocoService, TranslocoPipe } from '@jsverse/transloco';
import { ReadingSessionService } from '../../../shared/service/reading-session.service';
import { WakeLockService } from '../../../shared/service/wake-lock.service';
import { Location } from '@angular/common';
import { FormsModule } from '@angular/forms';
interface SerializedPdfAnnotation extends Record<string, unknown> {
id?: unknown;
}
type EmbedPdfMessage =
| { type: 'ready' }
| { type: 'documentOpened'; pageCount?: number }
| { type: 'documentError'; error: string }
| { type: 'saved'; buffer?: ArrayBuffer }
| { type: 'saveError'; error: string };
@Component({
selector: 'app-pdf-reader',
standalone: true,
imports: [NgxExtendedPdfViewerModule, ProgressSpinner, TranslocoPipe],
imports: [NgxExtendedPdfViewerModule, ProgressSpinner, TranslocoPipe, ReaderIconComponent, FormsModule],
templateUrl: './pdf-reader.component.html',
styleUrl: './pdf-reader.component.scss',
})
export class PdfReaderComponent implements OnInit, OnDestroy {
export class PdfReaderComponent implements OnInit, OnDestroy, AfterViewInit {
constructor() {
pdfDefaultOptions.rangeChunkSize = 512 * 1024;
pdfDefaultOptions.disableAutoFetch = true;
@@ -49,6 +55,32 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
bookData!: string;
bookId!: number;
bookFileId?: number;
bookTitle = '';
isFullscreen = false;
viewerMode: 'book' | 'document' = 'book';
private embedPdfIframe: HTMLIFrameElement | null = null;
private embedPdfMessageHandler?: (e: MessageEvent) => void;
private embedPdfSaveResolve?: (buffer: ArrayBuffer | null) => void;
private embedPdfSaveTimer?: ReturnType<typeof setTimeout>;
private embedPdfInitTime = 0;
// Auto-hide chrome
headerVisible = true;
footerVisible = true;
private chromeAutoHideTimer?: ReturnType<typeof setTimeout>;
private readonly CHROME_HIDE_DELAY = 3000;
// Footer page navigation
goToPageInput: number | null = null;
get sliderTicks(): number[] {
if (this.totalPages <= 1) return [];
const step = Math.max(1, Math.floor(this.totalPages / 10));
const ticks: number[] = [];
for (let i = 1; i <= this.totalPages; i += step) ticks.push(i);
if (ticks[ticks.length - 1] !== this.totalPages) ticks.push(this.totalPages);
return ticks;
}
private altBookType?: string;
private appSettingsSubscription!: Subscription;
private annotationSaveSubject = new Subject<void>();
@@ -66,8 +98,14 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
private pdfViewerService = inject(NgxExtendedPdfViewerService);
private pdfAnnotationService = inject(PdfAnnotationService);
private readonly t = inject(TranslocoService);
private wakeLockService = inject(WakeLockService);
private annotationToolbarObserver?: MutationObserver;
ngOnInit(): void {
setTimeout(() => this.wakeLockService.enable(), 1000);
this.startChromeAutoHide();
document.addEventListener('fullscreenchange', this.onFullscreenChange);
this.annotationSaveSubscription = this.annotationSaveSubject
.pipe(debounceTime(1500))
.subscribe(() => this.persistAnnotations());
@@ -90,39 +128,266 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
return forkJoin([
this.bookService.getBookSetting(this.bookId, this.bookFileId!),
this.userService.getMyself()
]).pipe(map(([bookSetting, myself]) => ({book, bookSetting, myself})));
]).pipe(map(([bookSetting, myself]) => ({ book, bookSetting, myself })));
})
);
})
).subscribe({
next: ({book, bookSetting, myself}) => {
const pdfMeta = book;
const pdfPrefs = bookSetting;
next: ({ book, bookSetting, myself }) => {
const pdfMeta = book;
const pdfPrefs = bookSetting;
this.pageTitle.setBookPageTitle(pdfMeta);
this.pageTitle.setBookPageTitle(pdfMeta);
this.bookTitle = pdfMeta.metadata?.title || '';
const globalOrIndividual = myself.userSettings.perBookSetting.pdf;
if (globalOrIndividual === 'Global') {
this.zoom = myself.userSettings.pdfReaderSetting.pageZoom || 'page-fit';
this.spread = myself.userSettings.pdfReaderSetting.pageSpread || 'odd';
} else {
this.zoom = pdfPrefs.pdfSettings?.zoom || myself.userSettings.pdfReaderSetting.pageZoom || 'page-fit';
this.spread = pdfPrefs.pdfSettings?.spread || myself.userSettings.pdfReaderSetting.pageSpread || 'odd';
}
this.canPrint = myself.permissions.canDownload || myself.permissions.admin;
this.page = pdfMeta.pdfProgress?.page || 1;
this.bookData = this.altBookType
? `${API_CONFIG.BASE_URL}/api/v1/books/${this.bookId}/content?bookType=${this.altBookType}`
: `${API_CONFIG.BASE_URL}/api/v1/books/${this.bookId}/content`;
const token = this.authService.getInternalAccessToken();
this.authorization = token ? `Bearer ${token}` : '';
this.isLoading = false;
},
error: () => {
this.messageService.add({severity: 'error', summary: this.t.translate('common.error'), detail: this.t.translate('readerPdf.toast.failedToLoadBook')});
this.isLoading = false;
const globalOrIndividual = myself.userSettings.perBookSetting.pdf;
if (globalOrIndividual === 'Global') {
this.zoom = myself.userSettings.pdfReaderSetting.pageZoom || 'page-fit';
this.spread = myself.userSettings.pdfReaderSetting.pageSpread || 'off';
} else {
this.zoom = pdfPrefs.pdfSettings?.zoom || myself.userSettings.pdfReaderSetting.pageZoom || 'page-fit';
this.spread = pdfPrefs.pdfSettings?.spread || myself.userSettings.pdfReaderSetting.pageSpread || 'off';
this.isDarkTheme = pdfPrefs.pdfSettings?.isDarkTheme ?? true;
}
this.canPrint = myself.permissions.canDownload || myself.permissions.admin;
this.page = pdfMeta.pdfProgress?.page || 1;
this.bookData = this.altBookType
? `${API_CONFIG.BASE_URL}/api/v1/books/${this.bookId}/content?bookType=${this.altBookType}`
: `${API_CONFIG.BASE_URL}/api/v1/books/${this.bookId}/content`;
const token = this.authService.getInternalAccessToken();
this.authorization = token ? `Bearer ${token}` : '';
this.isLoading = false;
},
error: () => {
this.messageService.add({ severity: 'error', summary: this.t.translate('common.error'), detail: this.t.translate('readerPdf.toast.failedToLoadBook') });
this.isLoading = false;
}
});
}
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 = `<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>`;
// 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);
}
async setViewerMode(mode: 'book' | 'document') {
if (mode !== 'document' && this.embedPdfIframe) {
await this.saveEmbedPdfDocument();
await this.destroyEmbedPdf();
}
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();
}
}
private async initEmbedPdf() {
if (this.embedPdfIframe) return;
const t0 = performance.now();
this.embedPdfInitTime = t0;
try {
const headers: Record<string, string> = {};
if (this.authorization) {
headers['Authorization'] = this.authorization;
}
const response = await fetch(this.bookData, { headers, credentials: 'include' });
if (!response.ok) throw new Error(`PDF fetch failed: ${response.status}`);
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;
this.handleEmbedPdfMessage(e.data);
};
window.addEventListener('message', this.embedPdfMessageHandler);
// Wait for iframe to load before sending PDF data
await new Promise<void>((resolve) => {
iframe.onload = () => resolve();
targetEl.appendChild(iframe);
});
this.embedPdfIframe = iframe;
// Transfer the PDF buffer to the iframe (zero-copy via Transferable)
iframe.contentWindow!.postMessage({
type: 'init',
buffer: pdfBuffer,
wasmUrl: '/assets/pdfium/pdfium.wasm',
theme: this.isDarkTheme ? 'dark' : 'light'
}, location.origin, [pdfBuffer]);
} catch (err) {
console.error('[EmbedPDF] FATAL:', err);
this.messageService.add({
severity: 'error',
summary: this.t.translate('common.error'),
detail: 'Failed to load Document Viewer. Check browser console for details.'
});
}
}
/** Handle postMessage events from the EmbedPDF iframe */
private handleEmbedPdfMessage(msg: EmbedPdfMessage): void {
switch (msg.type) {
case 'ready':
break;
case 'documentOpened':
break;
case 'documentError':
console.error('[EmbedPDF] Document error:', msg.error);
break;
case 'saved':
this.embedPdfSaveResolve?.(msg.buffer ?? null);
this.embedPdfSaveResolve = undefined;
break;
case 'saveError':
console.error('[EmbedPDF] Save error:', msg.error);
this.embedPdfSaveResolve?.(null);
this.embedPdfSaveResolve = undefined;
break;
}
}
private async saveEmbedPdfDocument(): Promise<void> {
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
this.embedPdfSaveTimer = timer;
});
if (this.embedPdfSaveTimer) {
clearTimeout(this.embedPdfSaveTimer);
this.embedPdfSaveTimer = undefined;
}
if (!buffer) {
return;
}
const headers: Record<string, string> = { 'Content-Type': 'application/pdf' };
if (this.authorization) {
headers['Authorization'] = this.authorization;
}
const url = this.altBookType
? `${API_CONFIG.BASE_URL}/api/v1/books/${this.bookId}/content?bookType=${this.altBookType}`
: `${API_CONFIG.BASE_URL}/api/v1/books/${this.bookId}/content`;
const uploadResponse = await fetch(url, {
method: 'PUT',
headers,
credentials: 'include',
body: buffer
});
if (!uploadResponse.ok) {
console.error('[EmbedPDF] Upload failed:', uploadResponse.status);
}
} catch (err) {
console.error('[EmbedPDF] Failed to save document:', err);
}
}
onPageChange(page: number): void {
@@ -148,11 +413,24 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
}
}
toggleDarkTheme(): void {
this.isDarkTheme = !this.isDarkTheme;
this.updateViewerSetting();
// Sync EmbedPDF theme if active
if (this.embedPdfIframe?.contentWindow) {
this.embedPdfIframe.contentWindow.postMessage(
{ type: 'setTheme', theme: this.isDarkTheme ? 'dark' : 'light' },
location.origin
);
}
}
private updateViewerSetting(): void {
const bookSetting: BookSetting = {
pdfSettings: {
spread: this.spread,
zoom: this.zoom,
isDarkTheme: this.isDarkTheme,
}
}
this.bookService.updateViewerSetting(bookSetting, this.bookId).subscribe();
@@ -168,7 +446,8 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0;
this.readingSessionService.startSession(this.bookId, "PDF", this.page.toString(), percentage);
this.readingSessionService.updateProgress(this.page.toString(), percentage);
this.loadAnnotations();
// Delay annotation loading to ensure annotation editor layers are initialized
setTimeout(() => this.loadAnnotations(), 800);
}
onAnnotationEditorEvent(): void {
@@ -178,6 +457,9 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
}
ngOnDestroy(): void {
this.wakeLockService.disable();
if (this.chromeAutoHideTimer) clearTimeout(this.chromeAutoHideTimer);
if (this.annotationToolbarObserver) this.annotationToolbarObserver.disconnect();
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);
@@ -185,14 +467,117 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
this.annotationSaveSubscription?.unsubscribe();
this.persistAnnotations();
this.destroyEmbedPdf();
if (this.appSettingsSubscription) {
this.appSettingsSubscription.unsubscribe();
}
this.updateProgress();
document.removeEventListener('fullscreenchange', this.onFullscreenChange);
}
closeReader = (): void => {
// --- Chrome auto-hide ---
@HostListener('document:mousemove')
onMouseMove(): void {
this.showChrome();
this.startChromeAutoHide();
}
showChrome(): void {
this.headerVisible = true;
this.footerVisible = true;
}
hideChrome(): void {
this.headerVisible = false;
this.footerVisible = false;
}
private startChromeAutoHide(): void {
if (this.chromeAutoHideTimer) clearTimeout(this.chromeAutoHideTimer);
this.chromeAutoHideTimer = setTimeout(() => this.hideChrome(), this.CHROME_HIDE_DELAY);
}
onHeaderTriggerZoneEnter(): void {
this.headerVisible = true;
this.startChromeAutoHide();
}
onFooterTriggerZoneEnter(): void {
this.footerVisible = true;
this.startChromeAutoHide();
}
// --- Fullscreen ---
toggleFullscreen(): void {
if (!document.fullscreenElement) {
document.documentElement.requestFullscreen?.();
} else {
document.exitFullscreen?.();
}
}
private onFullscreenChange = (): void => {
this.isFullscreen = !!document.fullscreenElement;
};
// --- Footer page navigation ---
goToFirstPage(): void {
this.page = 1;
this.onPageChange(1);
}
goToPreviousPage(): void {
if (this.page > 1) {
const p = this.page - 1;
this.page = p;
this.onPageChange(p);
}
}
goToNextPage(): void {
if (this.page < this.totalPages) {
const p = this.page + 1;
this.page = p;
this.onPageChange(p);
}
}
goToLastPage(): void {
this.page = this.totalPages;
this.onPageChange(this.totalPages);
}
onSliderChange(event: Event): void {
const value = +(event.target as HTMLInputElement).value;
this.page = value;
this.onPageChange(value);
}
onGoToPage(): void {
if (this.goToPageInput && this.goToPageInput >= 1 && this.goToPageInput <= this.totalPages) {
this.page = this.goToPageInput;
this.onPageChange(this.goToPageInput);
this.goToPageInput = null;
}
}
// --- Rotation ---
rotateClockwise(): void {
this.rotation = ((this.rotation + 90) % 360) as 0 | 90 | 180 | 270;
}
closeReader = async (): Promise<void> => {
if (this.embedPdfIframe) {
await this.saveEmbedPdfDocument();
await this.destroyEmbedPdf();
} else {
this.persistAnnotations();
}
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);
@@ -202,11 +587,17 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
private loadAnnotations(): void {
this.pdfAnnotationService.getAnnotations(this.bookId).subscribe({
next: (response) => {
next: async (response) => {
if (response?.data) {
const annotations = JSON.parse(response.data);
for (const annotation of annotations) {
this.pdfViewerService.addEditorAnnotation(annotation);
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;
@@ -217,19 +608,45 @@ export class PdfReaderComponent implements OnInit, OnDestroy {
});
}
private async destroyEmbedPdf(): Promise<void> {
// 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) {
if (!this.annotationsLoaded || !this.bookId || this.viewerMode === 'document') {
return;
}
const serialized = this.pdfViewerService.getSerializedAnnotations();
if (serialized && serialized.length > 0) {
const cleaned = serialized.map((annotation: SerializedPdfAnnotation) => {
const {id, ...rest} = annotation;
void id;
return rest;
});
const data = JSON.stringify(cleaned);
this.pdfAnnotationService.saveAnnotations(this.bookId, data).subscribe();
try {
const serialized = this.pdfViewerService.getSerializedAnnotations();
if (serialized && serialized.length > 0) {
const data = JSON.stringify(serialized);
this.pdfAnnotationService.saveAnnotations(this.bookId, data).subscribe();
}
} catch (e) {
console.error('[PDF Annotations] Failed to save annotations:', e);
}
}
}