Improve Angular project structure and code organization (#1328)

This commit is contained in:
Aditya Chandel
2025-10-12 02:01:59 -06:00
committed by GitHub
parent 54a8bacccd
commit 7c9bd56f63
405 changed files with 463 additions and 727 deletions
@@ -0,0 +1,177 @@
<div class="comic-reader-container" tabindex="0">
<div class="navigation">
<div class="goto-page-controls">
<div class="input-group">
<input
type="number"
[(ngModel)]="goToPageInput"
[min]="1"
[max]="pages.length"
placeholder="Page"
class="page-input"
/>
<button
class="go-button"
(click)="goToPageInput !== null && goToPage(goToPageInput)"
[disabled]="goToPageInput === null || goToPageInput < 1 || goToPageInput > pages.length">
Go
</button>
</div>
</div>
<div class="page-controls">
<button class="nav-button first-page" (click)="goToPage(1)" [disabled]="currentPage === 0" title="First Page">
<span>⟨⟨</span>
</button>
<button class="nav-button prev-page" (click)="previousPage()" [disabled]="currentPage === 0" title="Previous Page">
<span>⟨</span>
</button>
<div class="page-info">
<span class="current-page">{{ currentPage + 1 }}</span>
<span class="page-separator">{{ isTwoPageView && imageUrls.length > 1 ? '-' + (currentPage + 2) : '' }}</span>
<span class="total-pages"> of {{ pages.length }}</span>
</div>
<button class="nav-button next-page" (click)="nextPage()" [disabled]="currentPage >= pages.length - 1" title="Next Page">
<span>⟩</span>
</button>
<button class="nav-button last-page" (click)="goToPage(pages.length)" [disabled]="currentPage >= pages.length - 1" title="Last Page">
<span>⟩⟩</span>
</button>
</div>
<div class="spread-controls">
<div class="desktop-controls">
<div class="fit-mode-dropdown">
<button class="view-button fit-mode-toggle"
(click)="toggleFitModeDropdown()"
title="Fit Mode">
<span>{{ displayLabel }}</span>
</button>
@if (showFitModeDropdown) {
<div class="fit-mode-menu">
@for (mode of fitModeOptions; track mode.value) {
<button
class="fit-mode-option"
[class.active]="fitMode === mode.value"
(click)="selectFitMode(mode.value)">
<span class="fit-mode-icon">{{ mode.icon }}</span>
<span class="fit-mode-label">{{ mode.label }}</span>
</button>
}
</div>
}
</div>
<button class="view-button scroll-toggle" (click)="toggleScrollMode()" title="Toggle Scroll Mode">
<span>{{ scrollModeIcon }}</span>
</button>
@if (isTwoPageView && scrollMode === CbxScrollMode.PAGINATED) {
<button class="view-button spread-toggle" (click)="toggleSpreadDirection()" title="Toggle Spread Direction">
<span>{{ pageSpread === CbxPageSpread.ODD ? '⬅️' : '➡️' }}</span>
</button>
}
@if (scrollMode === CbxScrollMode.PAGINATED) {
<button class="view-button layout-toggle" (click)="toggleView()" title="Toggle View">
<span>{{ isTwoPageView ? '📄' : '📖' }}</span>
</button>
}
<button class="view-button background-toggle" (click)="toggleBackground()" title="Toggle Background Color">
<span>{{ backgroundColorIcon }}</span>
</button>
</div>
<div class="mobile-controls">
<button class="view-button more-options-toggle"
(click)="toggleMobileOptionsDropdown()"
title="More Options">
<span>⋮</span>
</button>
@if (showMobileOptionsDropdown) {
<div class="mobile-options-menu">
<button class="mobile-option" (click)="selectMobileOption('fitMode')">
<span class="option-icon">{{ displayLabel }}</span>
<span class="option-label">Fit Mode</span>
</button>
@if (showFitModeSubmenu) {
<div class="submenu">
@for (mode of fitModeOptions; track mode.value) {
<button
class="submenu-option"
[class.active]="fitMode === mode.value"
(click)="selectFitModeFromMobile(mode.value)">
<span class="fit-mode-icon">{{ mode.icon }}</span>
<span class="fit-mode-label">{{ mode.label }}</span>
</button>
}
</div>
}
<button class="mobile-option" (click)="toggleScrollModeFromMobile()">
<span class="option-icon">{{ scrollModeIcon }}</span>
<span class="option-label">Scroll Mode</span>
</button>
@if (isTwoPageView && scrollMode === CbxScrollMode.PAGINATED) {
<button class="mobile-option" (click)="toggleSpreadDirectionFromMobile()">
<span class="option-icon">{{ pageSpread === CbxPageSpread.ODD ? '⬅️' : '➡️' }}</span>
<span class="option-label">Spread Direction</span>
</button>
}
@if (scrollMode === CbxScrollMode.PAGINATED) {
<button class="mobile-option" (click)="toggleViewFromMobile()">
<span class="option-icon">{{ isTwoPageView ? '📄' : '📖' }}</span>
<span class="option-label">Layout</span>
</button>
}
<button class="mobile-option" (click)="toggleBackgroundFromMobile()">
<span class="option-icon">{{ backgroundColorIcon }}</span>
<span class="option-label">Background</span>
</button>
</div>
}
</div>
</div>
</div>
<div class="image-container"
[class.two-page-view]="isTwoPageView && scrollMode === CbxScrollMode.PAGINATED"
[class.infinite-scroll]="scrollMode === CbxScrollMode.INFINITE"
[class.fit-actual-size]="fitMode === CbxFitMode.ACTUAL_SIZE"
[class.fit-page]="fitMode === CbxFitMode.FIT_PAGE"
[class.fit-width]="fitMode === CbxFitMode.FIT_WIDTH"
[class.fit-height]="fitMode === CbxFitMode.FIT_HEIGHT"
[class.fit-auto]="fitMode === CbxFitMode.AUTO"
[class.bg-black]="backgroundColor === CbxBackgroundColor.BLACK"
[class.bg-gray]="backgroundColor === CbxBackgroundColor.GRAY"
[class.bg-white]="backgroundColor === CbxBackgroundColor.WHITE"
(scroll)="onScroll($event)">
@if (!isLoading) {
@if (pages.length > 0) {
@if (scrollMode === CbxScrollMode.PAGINATED) {
<div class="pages-wrapper">
@for (url of imageUrls; track url) {
<img [src]="url" alt="Page Image" class="page-image"/>
}
</div>
} @else {
<div class="infinite-scroll-wrapper">
@for (url of infiniteScrollImageUrls; track url; let i = $index) {
<img [src]="url" alt="Page {{ infiniteScrollPages[i] + 1 }}" class="page-image"/>
}
@if (isLoadingMore) {
<div class="loading-more">
<p-progressSpinner class="small-spinner"></p-progressSpinner>
</div>
}
</div>
}
} @else {
<div class="no-pages">
<p>No pages available.</p>
</div>
}
} @else {
<div class="loading-container">
<p-progressSpinner class="custom-spinner"></p-progressSpinner>
<p class="loading-text">Processing pages... This may take a few seconds on first load. Future loads will be significantly faster.</p>
</div>
}
</div>
</div>
@@ -0,0 +1,651 @@
.comic-reader-container {
display: flex;
flex-direction: column;
height: 100dvh;
width: 100vw;
overflow: hidden;
box-sizing: border-box;
background: #1a1a1a;
color: #ffffff;
&:focus {
outline: none;
}
.navigation {
flex-shrink: 0;
width: 100%;
background: linear-gradient(135deg, #2d2d2d 0%, #1f1f1f 100%);
border-bottom: 1px solid #404040;
padding: 0.25rem 0.5rem;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
display: flex;
align-items: center;
justify-content: space-between;
z-index: 1000;
min-width: 0;
.goto-page-controls {
flex: 1;
order: 1;
min-width: fit-content;
display: flex;
justify-content: flex-start;
.input-group {
display: flex;
align-items: center;
gap: 0.125rem;
background: rgba(51, 51, 51, 0.9);
border-radius: 4px;
padding: 1px;
border: 1px solid #555;
.page-input {
width: 55px;
padding: 4px 6px;
border: none;
border-radius: 3px;
background: #404040;
color: #ffffff;
font-size: 12px;
text-align: center;
transition: all 0.2s ease;
&:focus {
outline: none;
background: #4a4a4a;
box-shadow: 0 0 0 1px rgba(74, 144, 226, 0.5);
}
&::placeholder {
color: #999;
}
}
.go-button {
padding: 4px 8px;
background: #4a90e2;
color: white;
border: none;
border-radius: 3px;
font-size: 12px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
&:hover:not(:disabled) {
background: #357abd;
}
&:disabled {
background: #666;
cursor: not-allowed;
opacity: 0.6;
}
}
}
}
.page-controls {
flex: 0 0 auto;
display: flex;
align-items: center;
justify-content: center;
gap: 0.25rem;
order: 2;
min-width: 0;
.nav-button {
width: 24px;
height: 28px;
border: 1px solid #555;
background: rgba(51, 51, 51, 0.9);
color: #ffffff;
border-radius: 4px;
cursor: pointer;
transition: all 0.2s ease;
display: flex;
align-items: center;
justify-content: center;
span {
font-size: 11px;
font-weight: bold;
}
&:hover:not(:disabled) {
background: #4a4a4a;
border-color: #666;
}
&:disabled {
background: #2a2a2a;
color: #666;
cursor: not-allowed;
border-color: #333;
}
}
.page-info {
margin: 0 0.5rem;
padding: 2px 8px;
background: rgba(255, 255, 255, 0.1);
border-radius: 4px;
font-weight: 500;
font-size: 12px;
min-width: 80px;
text-align: center;
.current-page {
color: #4a90e2;
font-weight: 600;
}
.page-separator {
color: #4a90e2;
font-weight: 600;
}
.total-pages {
color: #ccc;
}
}
}
.spread-controls {
flex: 1;
display: flex;
gap: 0.25rem;
order: 3;
min-width: fit-content;
align-items: center;
justify-content: flex-end;
.mobile-controls {
display: none;
}
.desktop-controls {
display: flex;
gap: 0.25rem;
align-items: center;
}
@media (max-width: 768px) {
.desktop-controls {
display: none;
}
.mobile-controls {
display: block;
position: relative;
.more-options-toggle {
width: 32px;
height: 28px;
span {
font-size: 18px;
font-weight: bold;
}
}
.mobile-options-menu {
position: absolute;
top: calc(100% + 4px);
right: 0;
background: #2d2d2d;
border: 1px solid #555;
border-radius: 4px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
z-index: 1001;
min-width: 180px;
overflow: hidden;
.mobile-option {
width: 100%;
padding: 10px 12px;
background: transparent;
border: none;
color: #ffffff;
text-align: left;
cursor: pointer;
transition: background 0.2s ease;
display: flex;
align-items: center;
gap: 10px;
font-size: 13px;
border-bottom: 1px solid #404040;
.option-icon {
width: 24px;
text-align: center;
font-size: 14px;
}
.option-label {
flex: 1;
}
&:last-child {
border-bottom: none;
}
&:hover {
background: #3a3a3a;
}
}
.submenu {
background: #252525;
border-top: 1px solid #404040;
.submenu-option {
width: 100%;
padding: 8px 12px 8px 36px;
background: transparent;
border: none;
color: #ffffff;
text-align: left;
cursor: pointer;
transition: background 0.2s ease;
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
.fit-mode-icon {
width: 20px;
text-align: center;
font-size: 13px;
}
.fit-mode-label {
flex: 1;
}
&:hover {
background: #3a3a3a;
}
&.active {
background: #4a90e2;
color: #ffffff;
}
}
}
}
}
}
.view-button {
width: 28px;
height: 28px;
border: 1px solid #555;
background: rgba(51, 51, 51, 0.9);
color: #ffffff;
border-radius: 4px;
cursor: pointer;
transition: all 0.2s ease;
display: flex;
align-items: center;
justify-content: center;
span {
font-size: 13px;
}
&:hover {
background: #4a4a4a;
border-color: #666;
}
}
.fit-mode-dropdown {
position: relative;
.fit-mode-toggle {
width: auto;
min-width: 28px;
padding: 0 6px;
span {
font-size: 11px;
white-space: nowrap;
}
}
.fit-mode-menu {
position: absolute;
top: calc(100% + 4px);
right: 0;
background: #2d2d2d;
border: 1px solid #555;
border-radius: 4px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
z-index: 1001;
min-width: 160px;
overflow: hidden;
.fit-mode-option {
width: 100%;
padding: 8px 12px;
background: transparent;
border: none;
color: #ffffff;
text-align: left;
cursor: pointer;
transition: background 0.2s ease;
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
.fit-mode-icon {
width: 20px;
text-align: center;
font-size: 13px;
}
.fit-mode-label {
flex: 1;
}
&:hover {
background: #3a3a3a;
}
&.active {
background: #4a90e2;
color: #ffffff;
}
}
}
}
}
}
.image-container {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
padding: 0.5rem;
background: #0f0f0f;
min-height: 0;
position: relative;
&.bg-black {
background: #000000;
}
&.bg-gray {
background: #0f0f0f;
}
&.bg-white {
background: #ffffff;
}
&:not(.infinite-scroll) {
.pages-wrapper {
display: flex;
gap: 1rem;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
position: relative;
}
.page-image {
object-fit: contain;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.6);
border-radius: 4px;
transition: transform 0.2s ease;
&:hover {
transform: scale(1.02);
}
}
&.fit-width {
.pages-wrapper {
height: auto;
max-height: 100%;
}
.page-image {
width: 100%;
height: auto;
&:hover {
transform: scale(1.02);
}
}
&.two-page-view {
.pages-wrapper {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
}
.page-image {
width: 100%;
height: auto;
}
}
}
&.fit-height {
.pages-wrapper {
width: auto;
max-width: 100%;
}
.page-image {
width: auto;
height: 100%;
&:hover {
transform: scale(1.02);
}
}
&.two-page-view {
.page-image {
width: auto;
height: 100%;
max-width: calc(50% - 0.5rem);
}
}
}
&.fit-actual-size {
overflow: auto;
.pages-wrapper {
width: max-content;
height: max-content;
min-width: 0;
min-height: 0;
}
.page-image {
width: auto;
height: auto;
max-width: none;
max-height: none;
&:hover {
transform: none;
}
}
}
&.fit-page {
.page-image {
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
&:hover {
transform: scale(1.02);
}
}
&.two-page-view {
.page-image {
max-width: calc(50% - 0.5rem);
max-height: 100%;
width: auto;
height: auto;
}
}
}
&.fit-auto {
.page-image {
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
&:hover {
transform: scale(1.02);
}
}
&.two-page-view {
.page-image {
max-width: calc(50% - 0.5rem);
max-height: 100%;
width: auto;
height: auto;
}
}
}
}
&.infinite-scroll {
overflow-y: auto;
overflow-x: hidden;
align-items: flex-start;
.infinite-scroll-wrapper {
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
width: 100%;
padding: 1rem 0;
}
.page-image {
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.6);
border-radius: 4px;
transition: none;
&:hover {
transform: none;
}
}
&.fit-width .page-image {
width: 100%;
height: auto;
}
&.fit-height {
.infinite-scroll-wrapper {
min-height: 100%;
}
.page-image {
width: auto;
height: calc(100vh - 60px - 2rem);
max-width: 100%;
}
}
&.fit-actual-size {
overflow-x: auto;
.infinite-scroll-wrapper {
align-items: center;
width: max-content;
min-width: 100%;
}
.page-image {
width: auto;
height: auto;
}
}
&.fit-page {
.infinite-scroll-wrapper {
min-height: 100%;
}
.page-image {
max-width: 100%;
max-height: calc(100vh - 60px - 2rem);
width: auto;
height: auto;
}
}
&.fit-auto {
.infinite-scroll-wrapper {
min-height: 100%;
}
.page-image {
max-width: 100%;
max-height: calc(100vh - 60px - 2rem);
width: auto;
height: auto;
}
}
.loading-more {
padding: 2rem;
display: flex;
justify-content: center;
}
}
.no-pages {
text-align: center;
color: #999;
font-size: 18px;
}
.loading-container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 1.5rem;
text-align: center;
.loading-text {
color: #ccc;
font-size: 16px;
max-width: 400px;
line-height: 1.5;
margin: 0;
}
}
}
::ng-deep .small-spinner {
width: 40px;
height: 40px;
}
}
@@ -0,0 +1,561 @@
import {Component, HostListener, inject, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {CbxReaderService} from '../../book/service/cbx-reader.service';
import {BookService} from '../../book/service/book.service';
import {
CbxFitMode,
CbxPageSpread,
CbxPageViewMode,
CbxScrollMode,
PdfPageSpread,
PdfPageViewMode,
UserService,
CbxBackgroundColor
} from '../../settings/user-management/user.service';
import {MessageService} from 'primeng/api';
import {forkJoin} from 'rxjs';
import {BookSetting, BookType} from '../../book/model/book.model';
import {ProgressSpinner} from 'primeng/progressspinner';
import {FormsModule} from "@angular/forms";
import {NewPdfReaderService} from '../../book/service/new-pdf-reader.service';
@Component({
selector: 'app-cbx-reader',
standalone: true,
imports: [ProgressSpinner, FormsModule],
templateUrl: './cbx-reader.component.html',
styleUrl: './cbx-reader.component.scss'
})
export class CbxReaderComponent implements OnInit {
bookType!: BookType;
goToPageInput: number | null = null;
bookId!: number;
pages: number[] = [];
currentPage = 0;
isLoading = true;
pageSpread: CbxPageSpread | PdfPageSpread = CbxPageSpread.ODD;
pageViewMode: CbxPageViewMode | PdfPageViewMode = CbxPageViewMode.SINGLE_PAGE;
backgroundColor: CbxBackgroundColor = CbxBackgroundColor.GRAY;
fitMode: CbxFitMode = CbxFitMode.FIT_PAGE;
private touchStartX = 0;
private touchEndX = 0;
private route = inject(ActivatedRoute);
private cbxReaderService = inject(CbxReaderService);
private pdfReaderService = inject(NewPdfReaderService);
private bookService = inject(BookService);
private userService = inject(UserService);
private messageService = inject(MessageService);
showFitModeDropdown: boolean = false;
showMobileOptionsDropdown: boolean = false;
showFitModeSubmenu: boolean = false;
fitModeOptions = [
{value: CbxFitMode.FIT_PAGE, label: 'Fit Page', icon: '⬜'},
{value: CbxFitMode.FIT_WIDTH, label: 'Fit Width', icon: '↔️'},
{value: CbxFitMode.FIT_HEIGHT, label: 'Fit Height', icon: '↕️'},
{value: CbxFitMode.ACTUAL_SIZE, label: 'Actual Size', icon: '1:1'},
{value: CbxFitMode.AUTO, label: 'Automatic', icon: '🔄'}
];
scrollMode: CbxScrollMode = CbxScrollMode.PAGINATED;
infiniteScrollPages: number[] = [];
preloadCount: number = 3;
isLoadingMore: boolean = false;
protected readonly CbxScrollMode = CbxScrollMode;
protected readonly CbxFitMode = CbxFitMode;
protected readonly CbxBackgroundColor = CbxBackgroundColor;
protected readonly CbxPageViewMode = CbxPageViewMode;
protected readonly CbxPageSpread = CbxPageSpread;
private static readonly TYPE_PDF = 'PDF';
private static readonly TYPE_CBX = 'CBX';
private static readonly SETTING_GLOBAL = 'Global';
ngOnInit() {
this.route.paramMap.subscribe((params) => {
this.isLoading = true;
this.bookId = +params.get('bookId')!;
forkJoin([
this.bookService.getBookByIdFromAPI(this.bookId, false),
this.bookService.getBookSetting(this.bookId),
this.userService.getMyself()
]).subscribe({
next: ([book, bookSettings, myself]) => {
const userSettings = myself.userSettings;
this.bookType = book.bookType;
const pagesObservable = this.bookType === CbxReaderComponent.TYPE_PDF
? this.pdfReaderService.getAvailablePages(this.bookId)
: this.cbxReaderService.getAvailablePages(this.bookId);
pagesObservable.subscribe({
next: (pages) => {
this.pages = pages;
if (this.bookType === CbxReaderComponent.TYPE_CBX) {
const global = userSettings.perBookSetting.cbx === CbxReaderComponent.SETTING_GLOBAL;
this.pageViewMode = global
? this.CbxPageViewMode[userSettings.cbxReaderSetting.pageViewMode as keyof typeof CbxPageViewMode] || this.CbxPageViewMode.SINGLE_PAGE
: this.CbxPageViewMode[bookSettings.cbxSettings?.pageViewMode as keyof typeof CbxPageViewMode] || this.CbxPageViewMode[userSettings.cbxReaderSetting.pageViewMode as keyof typeof CbxPageViewMode] || this.CbxPageViewMode.SINGLE_PAGE;
this.pageSpread = global
? this.CbxPageSpread[userSettings.cbxReaderSetting.pageSpread as keyof typeof CbxPageSpread] || this.CbxPageSpread.ODD
: this.CbxPageSpread[bookSettings.cbxSettings?.pageSpread as keyof typeof CbxPageSpread] || this.CbxPageSpread[userSettings.cbxReaderSetting.pageSpread as keyof typeof CbxPageSpread] || this.CbxPageSpread.ODD;
this.fitMode = global
? this.CbxFitMode[userSettings.cbxReaderSetting.fitMode as keyof typeof CbxFitMode] || this.CbxFitMode.FIT_PAGE
: this.CbxFitMode[bookSettings.cbxSettings?.fitMode as keyof typeof CbxFitMode] || this.CbxFitMode[userSettings.cbxReaderSetting.fitMode as keyof typeof CbxFitMode] || this.CbxFitMode.FIT_PAGE;
this.scrollMode = global
? this.CbxScrollMode[userSettings.cbxReaderSetting.scrollMode as keyof typeof CbxScrollMode] || CbxScrollMode.PAGINATED
: this.CbxScrollMode[bookSettings.cbxSettings?.scrollMode as keyof typeof CbxScrollMode] || this.CbxScrollMode[userSettings.cbxReaderSetting.scrollMode as keyof typeof CbxScrollMode] || CbxScrollMode.PAGINATED;
this.backgroundColor = global
? this.CbxBackgroundColor[userSettings.cbxReaderSetting.backgroundColor as keyof typeof CbxBackgroundColor] || CbxBackgroundColor.GRAY
: this.CbxBackgroundColor[bookSettings.cbxSettings?.backgroundColor as keyof typeof CbxBackgroundColor] || this.CbxBackgroundColor[userSettings.cbxReaderSetting.backgroundColor as keyof typeof CbxBackgroundColor] || CbxBackgroundColor.GRAY;
this.currentPage = (book.cbxProgress?.page || 1) - 1;
if (this.scrollMode === CbxScrollMode.INFINITE) {
this.initializeInfiniteScroll();
}
}
if (this.bookType === CbxReaderComponent.TYPE_PDF) {
const global = userSettings.perBookSetting.pdf === CbxReaderComponent.SETTING_GLOBAL;
this.pageViewMode = global
? PdfPageViewMode[userSettings.newPdfReaderSetting.pageViewMode as keyof typeof PdfPageViewMode] || PdfPageViewMode.SINGLE_PAGE
: PdfPageViewMode[bookSettings.newPdfSettings?.pageViewMode as keyof typeof PdfPageViewMode] || PdfPageViewMode[userSettings.newPdfReaderSetting.pageViewMode as keyof typeof PdfPageViewMode] || PdfPageViewMode.SINGLE_PAGE;
this.pageSpread = global
? PdfPageSpread[userSettings.newPdfReaderSetting.pageSpread as keyof typeof PdfPageSpread] || PdfPageSpread.ODD
: PdfPageSpread[bookSettings.newPdfSettings?.pageSpread as keyof typeof PdfPageSpread] || PdfPageSpread[userSettings.newPdfReaderSetting.pageSpread as keyof typeof PdfPageSpread] || PdfPageSpread.ODD;
this.currentPage = (book.pdfProgress?.page || 1) - 1;
}
this.alignCurrentPageToParity();
this.isLoading = false;
},
error: (err) => {
const errorMessage = err?.error?.message || 'Failed to load pages';
this.messageService.add({severity: 'error', summary: 'Error', detail: errorMessage});
this.isLoading = false;
}
});
},
error: (err) => {
const errorMessage = err?.error?.message || 'Failed to load the book';
this.messageService.add({severity: 'error', summary: 'Error', detail: errorMessage});
this.isLoading = false;
}
});
});
}
get isTwoPageView(): boolean {
return this.pageViewMode === this.CbxPageViewMode.TWO_PAGE || this.pageViewMode === PdfPageViewMode.TWO_PAGE;
}
get backgroundColorIcon(): string {
switch (this.backgroundColor) {
case CbxBackgroundColor.BLACK:
return '⚫';
case CbxBackgroundColor.GRAY:
return '🔘';
case CbxBackgroundColor.WHITE:
return '⚪';
default:
return '🔘';
}
}
toggleBackground(): void {
switch (this.backgroundColor) {
case CbxBackgroundColor.BLACK:
this.backgroundColor = CbxBackgroundColor.GRAY;
break;
case CbxBackgroundColor.GRAY:
this.backgroundColor = CbxBackgroundColor.WHITE;
break;
case CbxBackgroundColor.WHITE:
this.backgroundColor = CbxBackgroundColor.BLACK;
break;
}
this.updateViewerSetting();
}
toggleView() {
if (!this.isTwoPageView && this.isPhonePortrait()) return;
this.pageViewMode = this.isTwoPageView
? (this.bookType === CbxReaderComponent.TYPE_CBX ? this.CbxPageViewMode.SINGLE_PAGE : PdfPageViewMode.SINGLE_PAGE)
: (this.bookType === CbxReaderComponent.TYPE_CBX ? this.CbxPageViewMode.TWO_PAGE : PdfPageViewMode.TWO_PAGE);
this.alignCurrentPageToParity();
this.updateViewerSetting();
}
toggleSpreadDirection() {
if (this.pageSpread === this.CbxPageSpread.ODD || this.pageSpread === PdfPageSpread.ODD) {
this.pageSpread = this.bookType === CbxReaderComponent.TYPE_CBX ? this.CbxPageSpread.EVEN : PdfPageSpread.EVEN;
} else {
this.pageSpread = this.bookType === CbxReaderComponent.TYPE_CBX ? this.CbxPageSpread.ODD : PdfPageSpread.ODD;
}
this.alignCurrentPageToParity();
this.updateViewerSetting();
}
toggleScrollMode(): void {
this.scrollMode = this.scrollMode === CbxScrollMode.PAGINATED
? CbxScrollMode.INFINITE
: CbxScrollMode.PAGINATED;
this.updateViewerSetting();
if (this.scrollMode === CbxScrollMode.INFINITE) {
this.initializeInfiniteScroll();
setTimeout(() => this.scrollToPage(this.currentPage), 100);
}
}
nextPage() {
const previousPage = this.currentPage;
if (this.scrollMode === CbxScrollMode.INFINITE) {
if (this.currentPage < this.pages.length - 1) {
this.currentPage++;
this.scrollToPage(this.currentPage);
this.updateProgress();
}
return;
}
if (this.isTwoPageView) {
if (this.currentPage + 2 < this.pages.length) {
this.currentPage += 2;
} else if (this.currentPage + 1 < this.pages.length) {
this.currentPage += 1;
}
} else if (this.currentPage < this.pages.length - 1) {
this.currentPage++;
}
if (this.currentPage !== previousPage) {
this.updateProgress();
}
}
previousPage() {
if (this.scrollMode === CbxScrollMode.INFINITE) {
if (this.currentPage > 0) {
this.currentPage--;
this.scrollToPage(this.currentPage);
this.updateProgress();
}
return;
}
if (this.isTwoPageView) {
this.currentPage = Math.max(0, this.currentPage - 2);
} else {
this.currentPage = Math.max(0, this.currentPage - 1);
}
this.updateProgress();
}
private alignCurrentPageToParity() {
if (!this.pages.length || !this.isTwoPageView) return;
const desiredOdd = this.pageSpread === CbxPageSpread.ODD || this.pageSpread === PdfPageSpread.ODD;
for (let i = this.currentPage; i >= 0; i--) {
if ((this.pages[i] % 2 === 1) === desiredOdd) {
this.currentPage = i;
this.updateProgress();
return;
}
}
for (let i = 0; i < this.pages.length; i++) {
if ((this.pages[i] % 2 === 1) === desiredOdd) {
this.currentPage = i;
this.updateProgress();
return;
}
}
}
toggleFitModeDropdown(): void {
this.showFitModeDropdown = !this.showFitModeDropdown;
}
selectFitMode(mode: CbxFitMode): void {
this.fitMode = mode;
this.showFitModeDropdown = false;
this.updateViewerSetting();
}
toggleMobileOptionsDropdown(): void {
this.showMobileOptionsDropdown = !this.showMobileOptionsDropdown;
this.showFitModeSubmenu = false;
}
selectMobileOption(option: string): void {
if (option === 'fitMode') {
this.showFitModeSubmenu = !this.showFitModeSubmenu;
}
}
selectFitModeFromMobile(mode: CbxFitMode): void {
this.fitMode = mode;
this.showFitModeSubmenu = false;
this.showMobileOptionsDropdown = false;
this.updateViewerSetting();
}
toggleScrollModeFromMobile(): void {
this.toggleScrollMode();
this.showMobileOptionsDropdown = false;
}
toggleSpreadDirectionFromMobile(): void {
this.toggleSpreadDirection();
this.showMobileOptionsDropdown = false;
}
toggleViewFromMobile(): void {
this.toggleView();
this.showMobileOptionsDropdown = false;
}
toggleBackgroundFromMobile(): void {
this.toggleBackground();
this.showMobileOptionsDropdown = false;
}
get displayLabel(): string {
const option = this.fitModeOptions.find(opt => opt.value === this.fitMode);
return option ? option.icon : '↔️';
}
get scrollModeIcon(): string {
return this.scrollMode === CbxScrollMode.PAGINATED ? '📄' : '📜';
}
private initializeInfiniteScroll(): void {
this.infiniteScrollPages = [];
const endIndex = Math.min(this.currentPage + this.preloadCount, this.pages.length);
for (let i = this.currentPage; i < endIndex; i++) {
this.infiniteScrollPages.push(i);
}
}
onScroll(event: Event): void {
if (this.scrollMode !== CbxScrollMode.INFINITE || this.isLoadingMore) return;
const container = event.target as HTMLElement;
const scrollPosition = container.scrollTop + container.clientHeight;
const scrollHeight = container.scrollHeight;
if (scrollPosition >= scrollHeight * 0.8) {
this.loadMorePages();
}
this.updateCurrentPageFromScroll(container);
}
private loadMorePages(): void {
if (this.isLoadingMore) return;
const lastLoadedIndex = this.infiniteScrollPages[this.infiniteScrollPages.length - 1];
if (lastLoadedIndex >= this.pages.length - 1) return;
this.isLoadingMore = true;
const endIndex = Math.min(lastLoadedIndex + this.preloadCount + 1, this.pages.length);
setTimeout(() => {
for (let i = lastLoadedIndex + 1; i < endIndex; i++) {
this.infiniteScrollPages.push(i);
}
this.isLoadingMore = false;
}, 100);
}
private updateCurrentPageFromScroll(container: HTMLElement): void {
const images = container.querySelectorAll('.page-image');
const containerRect = container.getBoundingClientRect();
for (let i = 0; i < images.length; i++) {
const img = images[i] as HTMLElement;
const rect = img.getBoundingClientRect();
if (rect.top <= containerRect.top + containerRect.height / 2 &&
rect.bottom >= containerRect.top + containerRect.height / 2) {
const newPage = this.infiniteScrollPages[i];
if (newPage !== this.currentPage) {
this.currentPage = newPage;
this.updateProgress();
}
break;
}
}
}
private getPageImageUrl(pageIndex: number): string {
return this.bookType === CbxReaderComponent.TYPE_PDF
? this.pdfReaderService.getPageImageUrl(this.bookId, this.pages[pageIndex])
: this.cbxReaderService.getPageImageUrl(this.bookId, this.pages[pageIndex]);
}
get imageUrls(): string[] {
if (!this.pages.length) return [];
const urls: string[] = [];
urls.push(this.getPageImageUrl(this.currentPage));
if (this.isTwoPageView && this.currentPage + 1 < this.pages.length) {
urls.push(this.getPageImageUrl(this.currentPage + 1));
}
return urls;
}
get infiniteScrollImageUrls(): string[] {
return this.infiniteScrollPages.map(pageIndex => this.getPageImageUrl(pageIndex));
}
private updateViewerSetting(): void {
const bookSetting: BookSetting = this.bookType === CbxReaderComponent.TYPE_CBX
? {
cbxSettings: {
pageSpread: this.pageSpread as CbxPageSpread,
pageViewMode: this.pageViewMode as CbxPageViewMode,
fitMode: this.fitMode as CbxFitMode,
scrollMode: this.scrollMode as CbxScrollMode,
backgroundColor: this.backgroundColor as CbxBackgroundColor,
}
}
: {
newPdfSettings: {
pageSpread: this.pageSpread as PdfPageSpread,
pageViewMode: this.pageViewMode as PdfPageViewMode,
}
};
this.bookService.updateViewerSetting(bookSetting, this.bookId).subscribe();
}
updateProgress(): void {
const percentage = this.pages.length > 0
? Math.round(((this.currentPage + 1) / this.pages.length) * 1000) / 10
: 0;
if (this.bookType === CbxReaderComponent.TYPE_CBX) {
this.bookService.saveCbxProgress(this.bookId, this.currentPage + 1, percentage).subscribe();
}
if (this.bookType === CbxReaderComponent.TYPE_PDF) {
this.bookService.savePdfProgress(this.bookId, this.currentPage + 1, percentage).subscribe();
}
}
goToPage(page: number): void {
if (page < 1 || page > this.pages.length) return;
const targetIndex = page - 1;
if (targetIndex === this.currentPage) return;
this.currentPage = targetIndex;
if (this.scrollMode === CbxScrollMode.INFINITE) {
this.ensurePageLoaded(targetIndex);
this.scrollToPage(targetIndex);
this.updateProgress();
} else {
this.alignCurrentPageToParity();
this.updateProgress();
}
}
private scrollToPage(pageIndex: number): void {
this.ensurePageLoaded(pageIndex);
setTimeout(() => {
const container = document.querySelector('.image-container.infinite-scroll') as HTMLElement;
if (!container) return;
const images = container.querySelectorAll('.page-image');
const indexInScroll = this.infiniteScrollPages.indexOf(pageIndex);
if (indexInScroll >= 0 && indexInScroll < images.length) {
const targetImage = images[indexInScroll] as HTMLElement;
targetImage.scrollIntoView({behavior: 'smooth', block: 'start'});
}
}, 100);
}
private ensurePageLoaded(pageIndex: number): void {
if (this.infiniteScrollPages.includes(pageIndex)) return;
this.infiniteScrollPages = [];
const startIndex = Math.max(0, pageIndex - 1);
const endIndex = Math.min(pageIndex + this.preloadCount, this.pages.length);
for (let i = startIndex; i < endIndex; i++) {
this.infiniteScrollPages.push(i);
}
}
@HostListener('window:keydown', ['$event'])
handleKeyDown(event: KeyboardEvent) {
if (event.key === 'ArrowRight') this.nextPage();
else if (event.key === 'ArrowLeft') this.previousPage();
}
@HostListener('touchstart', ['$event'])
onTouchStart(event: TouchEvent) {
this.touchStartX = event.changedTouches[0].screenX;
}
@HostListener('touchend', ['$event'])
onTouchEnd(event: TouchEvent) {
this.touchEndX = event.changedTouches[0].screenX;
this.handleSwipeGesture();
}
@HostListener('window:resize')
onResize() {
this.enforcePortraitSinglePageView();
}
private handleSwipeGesture() {
const delta = this.touchEndX - this.touchStartX;
if (Math.abs(delta) >= 50) delta < 0 ? this.nextPage() : this.previousPage();
}
private enforcePortraitSinglePageView() {
if (this.isPhonePortrait() && this.isTwoPageView) {
this.pageViewMode = this.bookType === CbxReaderComponent.TYPE_CBX ? CbxPageViewMode.SINGLE_PAGE : PdfPageViewMode.SINGLE_PAGE;
this.updateViewerSetting();
}
}
private isPhonePortrait(): boolean {
return window.innerWidth < 768 && window.innerHeight > window.innerWidth;
}
@HostListener('document:click', ['$event'])
onDocumentClick(event: MouseEvent): void {
const target = event.target as HTMLElement;
if (!target.closest('.fit-mode-dropdown')) {
this.showFitModeDropdown = false;
}
if (!target.closest('.mobile-controls')) {
this.showMobileOptionsDropdown = false;
this.showFitModeSubmenu = false;
}
}
}
@@ -0,0 +1,185 @@
<div #epubContainer class="epub-viewer-container">
@if (isLoading) {
<div class="spinner-wrapper">
<p-progressSpinner></p-progressSpinner>
</div>
}
@if (!isLoading) {
<div>
<div class="epub-header">
<div class="header-left">
<p-button size="small" class="menu-toggle-button" (click)="toggleDrawer()" icon="pi pi-bars" severity="secondary"></p-button>
<div class="progress-info">
<span class="progress-percentage"><span class="progress-label">Progress: </span>{{ progressPercentage }}%</span>
</div>
<p-drawer [(visible)]="isDrawerVisible" [modal]="true" [position]="'left'" header="Chapters">
<ul class="chapter-list">
@for (chapter of chapters; track chapter) {
<li (click)="navigateToChapter(chapter); $event.stopPropagation()" class="chapter-item">
{{ chapter.label }}
</li>
}
</ul>
</p-drawer>
</div>
<div class="header-center">
<p class="text-sm font-medium">{{ currentChapter }}</p>
</div>
<div class="header-right">
<div class="flex gap-4">
@if (!locationsReady) {
<div class="location-indicator" pTooltip="Saving progress not ready yet">
<span class="dot"></span>
</div>
}
<div>
<p-button size="small" class="settings-toggle-button" (click)="toggleSettingsDrawer()" icon="pi pi-cog" severity="secondary"></p-button>
<p-drawer [(visible)]="isSettingsDrawerVisible" [modal]="true" [position]="'right'" header="Settings">
<div class="flex flex-col gap-4 max-w-md mx-auto">
<div class="flex items-center gap-4">
<span class="font-semibold text-gray-200">Font Size:</span>
<div class="flex items-center gap-2">
<p-button size="small" icon="pi pi-minus" (click)="decreaseFontSize()" severity="info"></p-button>
<span class="text-gray-100">{{ fontSize }}%</span>
<p-button size="small" icon="pi pi-plus" (click)="increaseFontSize()" severity="info"></p-button>
</div>
</div>
<p-divider></p-divider>
<div class="flex items-center gap-2">
<label for="font-type" class="block font-semibold text-gray-200">Font:</label>
<p-select
id="font-type"
[options]="fontTypes"
[(ngModel)]="selectedFontType"
(onChange)="changeFontType()"
class="w-full"
placeholder="Select font type">
</p-select>
</div>
<p-divider></p-divider>
<div class="flex gap-2 items-center">
<label class="block font-semibold text-gray-200">Theme:</label>
<div class="flex gap-3 mt-1" role="radiogroup" aria-label="Theme selection">
@for (theme of themes; track theme) {
<button
type="button"
class="w-8 h-8 rounded-full border-2 transition-all"
[class.border-blue-600]="selectedTheme === theme.value"
[style.background-color]="getThemeColor(theme.value)"
(click)="selectTheme(theme.value)"
[attr.aria-pressed]="selectedTheme === theme.value"
[attr.aria-label]="theme.label">
</button>
}
</div>
</div>
<p-divider></p-divider>
<div class="flex items-center gap-2">
<label id="flow-label" class="block font-semibold text-gray-200">Flow:</label>
<div class="flex gap-4" role="radiogroup" aria-labelledby="flow-label">
<div class="flex items-center gap-1.5">
<p-radioButton
name="flow"
[value]="'paginated'"
[(ngModel)]="selectedFlow"
(onClick)="changeScrollMode()"
inputId="flow-paginated">
</p-radioButton>
<label for="flow-paginated" class="cursor-pointer select-none text-gray-200">Paginated</label>
</div>
<div class="flex items-center gap-1.5">
<p-radioButton
name="flow"
[value]="'scrolled'"
[(ngModel)]="selectedFlow"
(onClick)="changeScrollMode()"
inputId="flow-scrolled">
</p-radioButton>
<label for="flow-scrolled" class="cursor-pointer select-none text-gray-200">Scrolled</label>
</div>
</div>
</div>
@if (selectedFlow === 'paginated' && !isMobileDevice()) {
<p-divider></p-divider>
<div class="flex items-center gap-2">
<label id="spread-label" class="block font-semibold text-gray-200">Page Spread:</label>
<div class="flex gap-4" role="radiogroup" aria-labelledby="spread-label">
<div class="flex items-center gap-1.5">
<p-radioButton
name="spread"
[value]="'single'"
[(ngModel)]="selectedSpread"
(onClick)="changeSpreadMode()"
inputId="spread-single">
</p-radioButton>
<label for="spread-single" class="cursor-pointer select-none text-gray-200">Single</label>
</div>
<div class="flex items-center gap-1.5">
<p-radioButton
name="spread"
[value]="'double'"
[(ngModel)]="selectedSpread"
(onClick)="changeSpreadMode()"
inputId="spread-auto">
</p-radioButton>
<label for="spread-auto" class="cursor-pointer select-none text-gray-200">Double</label>
</div>
</div>
</div>
}
<p-divider></p-divider>
<div>
<label class="block mb-1 font-semibold text-gray-200 pb-2">Line Height: {{ lineHeight }}</label>
<p-slider
[(ngModel)]="lineHeight"
[min]="1"
[max]="2.5"
[step]="0.1"
(onSlideEnd)="updateThemeStyle()"
class="w-full"
aria-label="Line Height">
</p-slider>
</div>
<div>
<label class="block mb-1 font-semibold text-gray-200 pb-2 pt-2">Letter Spacing: {{ letterSpacing }}em</label>
<p-slider
[(ngModel)]="letterSpacing"
[min]="0"
[max]="0.2"
[step]="0.01"
(onSlideEnd)="updateThemeStyle()"
class="w-full"
aria-label="Letter Spacing">
</p-slider>
</div>
</div>
</p-drawer>
</div>
</div>
</div>
</div>
<div id="epubContainer" #epubContainer></div>
@if (selectedFlow !== 'scrolled') {
<button class="epub-controls-left" [class.visible]="showControls" (click)="prevPage(); onBookTouch()">←</button>
}
@if (selectedFlow !== 'scrolled') {
<button class="epub-controls-right" [class.visible]="showControls" (click)="nextPage(); onBookTouch()">→</button>
}
</div>
}
</div>
@@ -0,0 +1,176 @@
.epub-header {
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
padding-left: 1rem;
padding-right: 1rem;
position: relative;
}
.header-left {
display: flex;
align-items: center;
gap: 1rem;
flex: 0 0 auto;
}
.header-center {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
pointer-events: none;
}
.header-right {
display: flex;
align-items: center;
flex: 0 0 auto;
margin-left: auto;
}
.progress-info {
display: flex;
align-items: center;
justify-content: center;
}
.progress-percentage {
font-size: 0.85rem;
color: var(--text-color);
font-weight: 500;
display: flex;
align-items: center;
}
.progress-label {
@media (max-width: 768px) {
display: none;
}
}
.epub-viewer-container {
display: flex;
flex-direction: column;
height: 100dvh;
overflow: hidden;
}
#epubContainer {
height: 100%;
width: 100%;
overflow: hidden;
}
.menu-toggle-button,
.settings-toggle-button {
top: 10px;
z-index: 1000;
margin: 0;
}
.menu-toggle-button {
left: 10px;
}
.settings-toggle-button {
right: 10px;
}
.epub-controls-left,
.epub-controls-right {
position: absolute;
top: 50%;
transform: translateY(-50%);
z-index: 10;
font-size: 30px;
color: rgba(0, 0, 0, 0.5);
cursor: pointer;
background: none;
border: none;
padding: 10px;
transition: color 0.3s ease, transform 0.2s ease, opacity 0.3s ease;
@media (max-width: 768px) {
opacity: 0;
pointer-events: none;
&.visible {
opacity: 1;
pointer-events: auto;
}
}
}
.epub-controls-left {
left: 10px;
}
.epub-controls-right {
right: 10px;
}
.epub-controls-left:hover,
.epub-controls-right:hover {
color: rgba(0, 0, 0, 0.8);
transform: scale(1.1) translateY(-50%);
}
.epub-controls-left:focus,
.epub-controls-right:focus {
outline: none;
}
.chapter-list {
list-style: none;
padding: 0;
margin: 0;
display: flex;
flex-direction: column;
gap: 10px;
}
.chapter-item {
padding: 0.5px 0.5px;
font-size: 14px;
color: var(--text-color);
cursor: pointer;
transition: background-color 0.3s ease, color 0.3s ease;
border-radius: 5px;
}
.chapter-item:hover {
color: var(--primary-color);
}
.location-indicator {
display: flex;
align-items: center;
margin-left: 0.5rem;
.dot {
height: 10px;
width: 10px;
background-color: red;
border-radius: 50%;
display: inline-block;
box-shadow: 0 0 4px #bbb;
}
}
.spinner-wrapper {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
width: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 999;
}
::ng-deep .p-divider.p-divider-horizontal {
margin: 0.25rem 0 0.5rem 0 !important;
}
@@ -0,0 +1,443 @@
import {Component, ElementRef, inject, OnDestroy, OnInit, ViewChild, AfterViewInit, NgZone} from '@angular/core';
import ePub from 'epubjs';
import {Drawer} from 'primeng/drawer';
import {Button} from 'primeng/button';
import {FormsModule} from '@angular/forms';
import {ActivatedRoute} from '@angular/router';
import {Book, BookSetting} from '../../../book/model/book.model';
import {BookService} from '../../../book/service/book.service';
import {forkJoin} from 'rxjs';
import {Select} from 'primeng/select';
import {UserService} from '../../../settings/user-management/user.service';
import {ProgressSpinner} from 'primeng/progressspinner';
import {MessageService} from 'primeng/api';
import {Tooltip} from 'primeng/tooltip';
import {Slider} from 'primeng/slider';
import {FALLBACK_EPUB_SETTINGS, getChapter} from '../epub-reader-helper';
import {EpubThemeUtil} from '../epub-theme-util';
import {RadioButton} from 'primeng/radiobutton';
import {Divider} from 'primeng/divider';
@Component({
selector: 'app-epub-reader',
templateUrl: './epub-reader.component.html',
styleUrls: ['./epub-reader.component.scss'],
imports: [Drawer, Button, FormsModule, Select, ProgressSpinner, Tooltip, Slider, RadioButton, Divider],
standalone: true
})
export class EpubReaderComponent implements OnInit, OnDestroy {
@ViewChild('epubContainer', {static: false}) epubContainer!: ElementRef;
isLoading = true;
chapters: { label: string; href: string }[] = [];
currentChapter = '';
isDrawerVisible = false;
isSettingsDrawerVisible = false;
public locationsReady = false;
public approxProgress = 0;
public exactProgress = 0;
public progressPercentage = 0;
showControls = !this.isMobileDevice();
private hideControlsTimeout?: number;
private book: any;
private rendition: any;
private keyListener: (e: KeyboardEvent) => void = () => {
};
fontSize?: number = 100;
selectedFlow?: string = 'paginated';
selectedTheme?: string = 'white';
selectedFontType?: string | null = null;
selectedSpread?: string = 'double';
lineHeight?: number;
letterSpacing?: number;
fontTypes: any[] = [
{label: "Book's Internal", value: null},
{label: 'Serif', value: 'serif'},
{label: 'Sans Serif', value: 'sans-serif'},
{label: 'Roboto', value: 'roboto'},
{label: 'Cursive', value: 'cursive'},
{label: 'Monospace', value: 'monospace'},
];
themes: any[] = [
{label: 'White', value: 'white'},
{label: 'Black', value: 'black'},
{label: 'Grey', value: 'grey'},
{label: 'Sepia', value: 'sepia'},
];
private route = inject(ActivatedRoute);
private userService = inject(UserService);
private bookService = inject(BookService);
private messageService = inject(MessageService);
private ngZone = inject(NgZone);
epub!: Book;
ngOnInit(): void {
this.route.paramMap.subscribe((params) => {
this.isLoading = true;
const bookId = +params.get('bookId')!;
const myself$ = this.userService.getMyself();
const epub$ = this.bookService.getBookByIdFromAPI(bookId, false);
const epubData$ = this.bookService.getFileContent(bookId);
const bookSetting$ = this.bookService.getBookSetting(bookId);
forkJoin([myself$, epub$, epubData$, bookSetting$]).subscribe({
next: ([myself, epub, epubData, bookSetting]) => {
this.epub = epub;
const individualSetting = bookSetting?.epubSettings;
const fileReader = new FileReader();
fileReader.onload = () => {
this.book = ePub(fileReader.result as ArrayBuffer);
this.book.loaded.navigation.then((nav: any) => {
this.chapters = nav.toc.map((chapter: any) => ({
label: chapter.label,
href: chapter.href,
}));
});
const settingScope = myself.userSettings.perBookSetting.epub;
const globalSettings = myself.userSettings.epubReaderSetting;
const resolvedFlow = settingScope === 'Global' ? globalSettings.flow : individualSetting?.flow;
const resolvedFontSize = settingScope === 'Global' ? globalSettings.fontSize : individualSetting?.fontSize;
const resolvedFontFamily = settingScope === 'Global' ? globalSettings.font : individualSetting?.font;
const resolvedTheme = settingScope === 'Global' ? globalSettings.theme : individualSetting?.theme;
const resolvedLineHeight = settingScope === 'Global' ? globalSettings.lineHeight : individualSetting?.lineHeight;
const resolvedLetterSpacing = settingScope === 'Global' ? globalSettings.letterSpacing : individualSetting?.letterSpacing;
const resolvedSpread = settingScope === 'Global' ? globalSettings.spread || 'double' : individualSetting?.spread || 'double';
if (resolvedTheme != null) this.selectedTheme = resolvedTheme;
if (resolvedFontFamily != null) this.selectedFontType = resolvedFontFamily;
if (resolvedFontSize != null) this.fontSize = resolvedFontSize;
if (resolvedLineHeight != null) this.lineHeight = resolvedLineHeight;
if (resolvedLetterSpacing != null) this.letterSpacing = resolvedLetterSpacing;
if (resolvedFlow != null) this.selectedFlow = resolvedFlow;
if (resolvedSpread != null) this.selectedSpread = resolvedSpread;
this.rendition = this.book.renderTo(this.epubContainer.nativeElement, {
flow: this.selectedFlow ?? 'paginated',
manager: this.selectedFlow === 'scrolled' ? 'continuous' : 'default',
width: '100%',
height: '100%',
spread: this.selectedFlow === 'paginated' && !this.isMobileDevice() ? (this.selectedSpread === 'single' ? 'none' : this.selectedSpread) : 'none',
allowScriptedContent: true,
});
const baseTheme = EpubThemeUtil.themesMap.get(this.selectedTheme ?? 'black') || {};
const combinedTheme = {
...baseTheme,
body: {
...baseTheme.body,
...(this.selectedFontType ? {'font-family': this.selectedFontType} : {}),
...(this.lineHeight != null ? {'line-height': this.lineHeight} : {}),
...(this.letterSpacing != null ? {'letter-spacing': `${this.letterSpacing}em`} : {}),
},
'*': {
...baseTheme['*'],
...(this.lineHeight != null ? {'line-height': this.lineHeight} : {}),
...(this.letterSpacing != null ? {'letter-spacing': `${this.letterSpacing}em`} : {}),
},
};
this.rendition.themes.override('font-size', `${this.fontSize}%`);
this.rendition.themes.register('custom', combinedTheme);
this.rendition.themes.select('custom');
const displayPromise = this.epub?.epubProgress?.cfi
? this.rendition.display(this.epub.epubProgress.cfi)
: this.rendition.display();
displayPromise.then(() => {
this.setupKeyListener();
this.trackProgress();
this.setupTouchListener();
this.isLoading = false;
});
};
fileReader.readAsArrayBuffer(epubData);
},
error: () => {
this.messageService.add({
severity: 'error',
summary: 'Error',
detail: 'Failed to load the book',
});
this.isLoading = false;
},
});
});
}
updateThemeStyle(): void {
this.applyCombinedTheme();
this.updateViewerSetting();
}
changeScrollMode(): void {
if (!this.rendition || !this.book) return;
const cfi = this.rendition.currentLocation()?.start?.cfi;
this.rendition.destroy();
this.rendition = this.book.renderTo(this.epubContainer.nativeElement, {
flow: this.selectedFlow,
manager: this.selectedFlow === 'scrolled' ? 'continuous' : 'default',
width: '100%',
height: '100%',
spread: this.selectedFlow === 'paginated' && !this.isMobileDevice() ? (this.selectedSpread === 'single' ? 'none' : this.selectedSpread) : 'none',
allowScriptedContent: true,
});
this.rendition.themes.override('font-size', `${this.fontSize}%`);
this.applyCombinedTheme();
this.setupKeyListener();
this.rendition.display(cfi || undefined);
this.updateViewerSetting();
}
changeSpreadMode(): void {
if (!this.rendition || !this.book || this.selectedFlow === 'scrolled' || this.isMobileDevice()) return;
const cfi = this.rendition.currentLocation()?.start?.cfi;
this.rendition.destroy();
this.rendition = this.book.renderTo(this.epubContainer.nativeElement, {
flow: this.selectedFlow,
manager: 'default',
width: '100%',
height: '100%',
spread: this.selectedSpread === 'single' ? 'none' : this.selectedSpread,
allowScriptedContent: true,
});
this.rendition.themes.override('font-size', `${this.fontSize}%`);
this.applyCombinedTheme();
this.setupKeyListener();
this.rendition.display(cfi || undefined);
this.updateViewerSetting();
}
changeThemes(): void {
this.applyCombinedTheme();
this.updateViewerSetting();
}
private applyCombinedTheme(): void {
EpubThemeUtil.applyTheme(
this.rendition,
this.selectedTheme ?? 'white',
this.selectedFontType ?? undefined,
this.fontSize,
this.lineHeight,
this.letterSpacing
);
}
updateFontSize(): void {
if (this.rendition) {
this.rendition.themes.override('font-size', `${this.fontSize}%`);
this.updateViewerSetting();
}
}
changeFontType(): void {
if (this.rendition) {
if (this.selectedFontType) {
this.rendition.themes.font(this.selectedFontType);
} else {
this.rendition.themes.font('');
}
this.updateViewerSetting();
}
}
increaseFontSize(): void {
this.fontSize = Math.min(Number(this.fontSize) + 10, FALLBACK_EPUB_SETTINGS.maxFontSize);
this.updateFontSize();
}
decreaseFontSize(): void {
this.fontSize = Math.max(Number(this.fontSize) - 10, FALLBACK_EPUB_SETTINGS.minFontSize);
this.updateFontSize();
}
private updateViewerSetting(): void {
const epubSettings: any = {};
if (this.selectedTheme) epubSettings.theme = this.selectedTheme;
if (this.selectedFontType) epubSettings.font = this.selectedFontType;
if (this.fontSize) epubSettings.fontSize = this.fontSize;
if (this.selectedFlow) epubSettings.flow = this.selectedFlow;
if (this.selectedSpread === 'single' || this.selectedSpread === 'double') epubSettings.spread = this.selectedSpread;
if (this.lineHeight) epubSettings.lineHeight = this.lineHeight;
if (this.letterSpacing) epubSettings.letterSpacing = this.letterSpacing;
const bookSetting: BookSetting = {
epubSettings: epubSettings
};
this.bookService.updateViewerSetting(bookSetting, this.epub.id).subscribe();
}
private setupKeyListener(): void {
this.keyListener = (e: KeyboardEvent) => {
switch (e.key) {
case 'ArrowLeft':
this.prevPage();
break;
case 'ArrowRight':
this.nextPage();
break;
default:
break;
}
};
if (this.rendition) {
this.rendition.on('keyup', this.keyListener);
}
document.addEventListener('keyup', this.keyListener);
}
private setupTouchListener(): void {
if (!this.isMobileDevice() || !this.rendition) return;
this.rendition.on('rendered', () => {
const iframe = this.epubContainer.nativeElement.querySelector('iframe');
if (iframe && iframe.contentDocument) {
iframe.contentDocument.addEventListener('touchstart', () => {
this.ngZone.run(() => {
this.onBookTouch();
});
});
}
});
}
public isMobileDevice(): boolean {
return window.innerWidth <= 768;
}
prevPage(): void {
if (this.rendition) {
this.rendition.prev();
}
}
nextPage(): void {
if (this.rendition) {
this.rendition.next();
}
}
navigateToChapter(chapter: { label: string; href: string }): void {
if (this.book && chapter.href) {
this.book.rendition.display(chapter.href);
}
}
toggleDrawer(): void {
this.isDrawerVisible = !this.isDrawerVisible;
}
toggleSettingsDrawer(): void {
this.isSettingsDrawerVisible = !this.isSettingsDrawerVisible;
}
private trackProgress(): void {
if (!this.book || !this.rendition) return;
this.rendition.on('relocated', (location: any) => {
const cfi = location.end.cfi;
const currentIndex = location.start.index;
const totalSpineItems = this.book.spine.items.length;
let percentage: number;
if (this.locationsReady && this.book.locations.total > 0) {
percentage = this.book.locations.percentageFromCfi(cfi);
this.exactProgress = Math.round(percentage * 1000) / 10;
this.progressPercentage = Math.round(percentage * 1000) / 10;
} else {
if (totalSpineItems > 0) {
percentage = (currentIndex + 1) / totalSpineItems;
} else {
percentage = 0;
}
this.approxProgress = Math.round(percentage * 1000) / 10;
this.progressPercentage = Math.round(percentage * 1000) / 10;
}
this.currentChapter = getChapter(this.book, location)?.label;
this.bookService.saveEpubProgress(this.epub.id, cfi, Math.round(percentage * 1000) / 10).subscribe();
});
this.book.ready.then(() => {
return this.book.locations.generate(1600);
}).then(() => {
this.locationsReady = true;
if (this.rendition.currentLocation()) {
const location = this.rendition.currentLocation();
const cfi = location.end.cfi;
const percentage = this.book.locations.percentageFromCfi(cfi);
this.progressPercentage = Math.round(percentage * 1000) / 10;
}
}).catch(() => {
this.locationsReady = false;
});
}
ngOnDestroy(): void {
if (this.rendition) {
this.rendition.off('keyup', this.keyListener);
}
document.removeEventListener('keyup', this.keyListener);
if (this.hideControlsTimeout) {
window.clearTimeout(this.hideControlsTimeout);
}
}
getThemeColor(themeKey: string | undefined): string {
switch (themeKey) {
case 'white':
return '#ffffff';
case 'black':
return '#000000';
case 'grey':
return '#808080';
case 'sepia':
return '#704214';
default:
return '#ffffff';
}
}
selectTheme(themeKey: string): void {
this.selectedTheme = themeKey;
this.changeThemes();
}
onBookTouch(): void {
if (this.isMobileDevice()) {
this.showControls = true;
if (this.hideControlsTimeout) {
window.clearTimeout(this.hideControlsTimeout);
}
this.hideControlsTimeout = window.setTimeout(() => {
this.ngZone.run(() => {
this.showControls = false;
});
}, 3000);
}
}
}
@@ -0,0 +1,44 @@
import {EpubCFI} from 'epubjs';
export const FALLBACK_EPUB_SETTINGS = {
maxFontSize: 300,
minFontSize: 50
};
export function flatten(chapters: any) {
return [].concat.apply([], chapters.map((chapter: any) => [].concat.apply([chapter], flatten(chapter.subitems))));
}
export function getCfiFromHref(book: any, href: string): string | null {
const [_, id] = href.split('#');
const section = book.spine.get(href);
if (!section || !section.document) {
console.warn('Section or section.document is undefined for href:', href);
return null;
}
const el = id ? section.document.getElementById(id) : section.document.body;
if (!el) {
console.warn('Element not found in section.document for href:', href);
return null;
}
return section.cfiFromElement(el);
}
export function getChapter(book: any, location: any) {
const locationHref = location.start.href;
return flatten(book.navigation.toc)
.filter((chapter: any) => {
return book.canonical(chapter.href).includes(book.canonical(locationHref));
})
.reduce((result: any | null, chapter: any) => {
const chapterCfi = getCfiFromHref(book, chapter.href);
if (!chapterCfi) {
return result;
}
const locationAfterChapter = EpubCFI.prototype.compare(location.start.cfi, chapterCfi) > 0;
return locationAfterChapter ? chapter : result;
}, null);
}
@@ -0,0 +1,60 @@
export class EpubThemeUtil {
static readonly themesMap = new Map<string, any>([
['black', {
"body": {"background-color": "#000000", "color": "#f9f9f9"},
"p": {"color": "#f9f9f9"},
"h1, h2, h3, h4, h5, h6": {"color": "#f9f9f9"},
"a": {"color": "#f9f9f9"},
"img": {"-webkit-filter": "invert(1) hue-rotate(180deg)", "filter": "invert(1) hue-rotate(180deg)"},
"code": {"color": "#00ff00", "background-color": "black"}
}],
['sepia', {
"body": {"background-color": "#f4ecd8", "color": "#6e4b3a"},
"p": {"color": "#6e4b3a"},
"h1, h2, h3, h4, h5, h6": {"color": "#6e4b3a"},
"a": {"color": "#8b4513"},
"img": {"-webkit-filter": "sepia(1) contrast(1.5)", "filter": "sepia(1) contrast(1.5)"},
"code": {"color": "#8b0000", "background-color": "#f4ecd8"}
}],
['white', {
"body": {"background-color": "#ffffff", "color": "#000000"},
"p": {"color": "#000000"},
"h1, h2, h3, h4, h5, h6": {"color": "#000000"},
"a": {"color": "#000000"},
"img": {"-webkit-filter": "none", "filter": "none"},
"code": {"color": "#d14", "background-color": "#f5f5f5"}
}],
['grey', {
"body": {"background-color": "#404040", "color": "#d3d3d3"},
"p": {"color": "#d3d3d3"},
"h1, h2, h3, h4, h5, h6": {"color": "#d3d3d3"},
"a": {"color": "#1e90ff"},
"img": {"filter": "none"},
"code": {"color": "#d14", "background-color": "#585858"}
}]
]);
static applyTheme(rendition: any, themeKey: string, fontFamily?: string, fontSize?: number, lineHeight?: number, letterSpacing?: number): void {
if (!rendition) return;
const baseTheme = this.themesMap.get(themeKey ?? 'black') ?? {};
const combined = {
...baseTheme,
body: {
...baseTheme.body,
'font-family': fontFamily,
'font-size': `${fontSize ?? 100}%`,
'line-height': lineHeight,
'letter-spacing': `${letterSpacing}em`
},
'*': {
...baseTheme['*'],
'line-height': lineHeight,
'letter-spacing': `${letterSpacing}em`
}
};
rendition.themes.register('custom', combined);
rendition.themes.select('custom');
}
}
@@ -0,0 +1,27 @@
@if (isLoading) {
<div class="flex justify-center items-center h-screen relative">
<p-progressSpinner></p-progressSpinner>
</div>
}
@if (!isLoading) {
<ngx-extended-pdf-viewer
[src]="bookData"
[textLayer]="true"
[showHandToolButton]="true"
[handTool]="false"
[height]="'auto'"
[page]="page"
[rotation]="rotation"
[sidebarVisible]="false"
[zoom]="zoom"
[spread]="spread"
[showBookModeButton]="false"
[showDownloadButton]="showDownloadButton"
[showPrintButton]="showPrintButton"
(pagesLoaded)="onPdfPagesLoaded($event)"
(pageChange)="onPageChange($event)"
(zoomChange)="onZoomChange($event)"
(spreadChange)="onSpreadChange($event)">
</ngx-extended-pdf-viewer>
}
@@ -0,0 +1,129 @@
import {Component, inject, OnDestroy, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {NgxExtendedPdfViewerModule} from 'ngx-extended-pdf-viewer';
import {BookService} from '../../book/service/book.service';
import {forkJoin, Subscription} from 'rxjs';
import {BookSetting} from '../../book/model/book.model';
import {UserService} from '../../settings/user-management/user.service';
import {ProgressSpinner} from 'primeng/progressspinner';
import {MessageService} from 'primeng/api';
@Component({
selector: 'app-pdf-reader',
standalone: true,
imports: [NgxExtendedPdfViewerModule, ProgressSpinner],
templateUrl: './pdf-reader.component.html',
})
export class PdfReaderComponent implements OnInit, OnDestroy {
isLoading = true;
totalPages: number = 0;
rotation: 0 | 90 | 180 | 270 = 0;
page!: number;
spread!: 'off' | 'even' | 'odd';
zoom!: number | string;
showDownloadButton = false;
showPrintButton = false;
bookData!: string | Blob;
bookId!: number;
private appSettingsSubscription!: Subscription;
private bookService = inject(BookService);
private userService = inject(UserService);
private messageService = inject(MessageService);
private route = inject(ActivatedRoute);
ngOnInit(): void {
this.route.paramMap.subscribe((params) => {
this.isLoading = true;
this.bookId = +params.get('bookId')!;
const myself$ = this.userService.getMyself();
const book$ = this.bookService.getBookByIdFromAPI(this.bookId, false);
const bookSetting$ = this.bookService.getBookSetting(this.bookId);
const pdfData$ = this.bookService.getFileContent(this.bookId);
forkJoin([book$, bookSetting$, pdfData$, myself$]).subscribe({
next: (results) => {
const pdfMeta = results[0];
const pdfPrefs = results[1];
const pdfData = results[2];
const myself = results[3];
this.showDownloadButton = myself.permissions.canDownload || myself.permissions.admin;
this.showPrintButton = myself.permissions.canDownload || myself.permissions.admin;
let 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.page = pdfMeta.pdfProgress?.page || 1;
this.bookData = pdfData;
this.isLoading = false;
},
error: () => {
this.messageService.add({severity: 'error', summary: 'Error', detail: 'Failed to load the book'});
this.isLoading = false;
}
});
});
}
onPageChange(page: number): void {
if (page !== this.page) {
this.page = page;
this.updateProgress();
}
}
onZoomChange(zoom: string | number): 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();
}
}
private updateViewerSetting(): void {
const bookSetting: BookSetting = {
pdfSettings: {
spread: this.spread,
zoom: this.zoom,
}
}
this.bookService.updateViewerSetting(bookSetting, this.bookId).subscribe();
}
updateProgress(): void {
const percentage = this.totalPages > 0
? Math.round((this.page / this.totalPages) * 1000) / 10
: 0;
this.bookService.savePdfProgress(this.bookId, this.page, percentage).subscribe();
}
onPdfPagesLoaded(event: any): void {
this.totalPages = event.pagesCount;
}
ngOnDestroy(): void {
if (this.appSettingsSubscription) {
this.appSettingsSubscription.unsubscribe();
}
this.updateProgress();
}
}