refactor(frontend): rename booklore-ui to frontend

- Frontend path:
  - rename the tracked Angular app tree from `booklore-ui/` to `frontend/`
  - preserve file contents during the move so this commit stays focused on the path change itself
- Frontend docs:
  - update the moved frontend README and contribution guide where they refer to the renamed folder
  - keep those edits limited to path references introduced by the directory rename
This commit is contained in:
James Cox
2026-04-22 17:26:39 -04:00
committed by Zach Yale
parent c99aa87877
commit 874b013f75
1493 changed files with 3 additions and 3 deletions
@@ -0,0 +1,403 @@
<ng-container *transloco="let t; prefix: 'readerAudiobook'">
@if (isLoading) {
<div class="loading-container">
<p-progressSpinner strokeWidth="3" />
<span class="loading-text">{{ t('loading') }}</span>
</div>
} @else if (audiobookInfo) {
<div class="audiobook-player">
<!-- Hidden audio element -->
<audio
#audioElement
(loadedmetadata)="onAudioLoaded()"
(timeupdate)="onTimeUpdate()"
(progress)="onProgress()"
(ended)="onAudioEnded()"
(error)="onAudioError()"
></audio>
<!-- Header -->
<header class="reader-header">
<p-button
icon="pi pi-arrow-left"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="closeReader()"
[pTooltip]="t('header.backTooltip')"
tooltipPosition="bottom"
/>
<div class="header-info">
<h1 class="book-title">{{ audiobookInfo.title || t('untitled') }}</h1>
<span class="book-author">{{ audiobookInfo.author || t('unknownAuthor') }}</span>
</div>
<div class="header-actions">
<p-button
icon="pi pi-bookmark"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="toggleBookmarkList()"
[pTooltip]="t('header.bookmarksTooltip')"
tooltipPosition="bottom"
/>
<p-button
icon="pi pi-list"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="toggleTrackList()"
[pTooltip]="t('header.chaptersTracksTooltip')"
tooltipPosition="bottom"
/>
</div>
</header>
<!-- Main content -->
<main class="reader-main">
<!-- Cover art -->
<div class="cover-container">
<div class="cover-wrapper">
@if (coverUrl) {
<img
[src]="coverUrl"
(error)="onCoverError()"
[alt]="t('coverAlt')"
class="cover-image"
/>
} @else {
<div class="cover-placeholder">
<i class="pi pi-headphones"></i>
</div>
}
@if (audioLoading) {
<div class="cover-loading">
<p-progressSpinner strokeWidth="3" />
</div>
}
</div>
</div>
<!-- Track/Chapter info -->
<div class="track-info">
@if (audiobookInfo.folderBased && currentTrack) {
<span class="track-title">{{ currentTrack.title }}</span>
<span class="track-number">{{ t('trackInfo.trackOf', { current: currentTrackIndex + 1, total: audiobookInfo.tracks?.length }) }}</span>
} @else if (getCurrentChapter()) {
<span class="track-title">{{ getCurrentChapter()?.title }}</span>
@if (hasMultipleChapters()) {
<span class="track-number">{{ t('trackInfo.chapterOf', { current: getCurrentChapterIndex() + 1, total: audiobookInfo.chapters?.length }) }}</span>
}
}
</div>
<!-- Progress bar -->
<div class="progress-container">
<div class="time-display">
<span class="current-time">{{ formatTime(currentTime) }}</span>
<span class="duration">{{ formatTime(duration) }}</span>
</div>
<div class="progress-bar-wrapper">
<div class="buffered-bar" [style.width.%]="getBufferedPercent()"></div>
<p-slider
[(ngModel)]="currentTime"
[min]="0"
[max]="duration || 100"
[step]="1"
(onChange)="seek($event)"
class="progress-slider"
/>
</div>
</div>
<!-- Playback controls -->
<div class="playback-controls">
@if (audiobookInfo.folderBased) {
<p-button
icon="pi pi-step-backward"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="previousTrack()"
[disabled]="currentTrackIndex === 0"
[pTooltip]="t('controls.previousTrackTooltip')"
tooltipPosition="top"
size="large"
/>
} @else if (hasMultipleChapters()) {
<p-button
icon="pi pi-step-backward"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="previousChapter()"
[disabled]="!canGoPreviousChapter()"
[pTooltip]="t('controls.previousChapterTooltip')"
tooltipPosition="top"
size="large"
/>
}
<p-button
icon="pi pi-replay"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="seekRelative(-30)"
[pTooltip]="t('controls.rewindTooltip')"
tooltipPosition="top"
size="large"
/>
<p-button
[icon]="isPlaying ? 'pi pi-pause' : 'pi pi-play'"
[rounded]="true"
severity="contrast"
(onClick)="togglePlay()"
[disabled]="audioLoading"
class="play-button"
size="large"
/>
<p-button
icon="pi pi-forward"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="seekRelative(30)"
[pTooltip]="t('controls.forwardTooltip')"
tooltipPosition="top"
size="large"
/>
@if (audiobookInfo.folderBased) {
<p-button
icon="pi pi-step-forward"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="nextTrack()"
[disabled]="!audiobookInfo.tracks || currentTrackIndex >= audiobookInfo.tracks.length - 1"
[pTooltip]="t('controls.nextTrackTooltip')"
tooltipPosition="top"
size="large"
/>
} @else if (hasMultipleChapters()) {
<p-button
icon="pi pi-step-forward"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="nextChapter()"
[disabled]="!canGoNextChapter()"
[pTooltip]="t('controls.nextChapterTooltip')"
tooltipPosition="top"
size="large"
/>
}
</div>
<!-- Secondary controls -->
<div class="secondary-controls">
<!-- Volume -->
<div class="volume-control">
<p-button
[icon]="getVolumeIcon()"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="toggleMute()"
size="small"
/>
<p-slider
[(ngModel)]="volume"
[min]="0"
[max]="1"
[step]="0.01"
(onChange)="setVolume($event)"
class="volume-slider"
/>
</div>
<!-- Playback speed -->
<div class="speed-control">
<p-selectButton
[options]="playbackRates"
[ngModel]="playbackRate"
(ngModelChange)="setPlaybackRate($event)"
optionLabel="label"
optionValue="value"
size="small"
/>
</div>
</div>
<!-- Extra controls row -->
<div class="extra-controls">
<!-- Add bookmark button -->
<p-button
icon="pi pi-bookmark-fill"
[label]="t('extra.addBookmark')"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="addBookmark()"
size="small"
/>
<!-- Sleep timer -->
<p-button
#sleepTimerBtn
icon="pi pi-moon"
[label]="sleepTimerActive ? formatSleepTimerRemaining() : t('extra.sleepTimer')"
[rounded]="true"
[text]="true"
severity="secondary"
[class]="sleepTimerActive ? 'sleep-timer-active' : ''"
(onClick)="sleepTimerMenu.toggle($event)"
size="small"
/>
<p-menu
#sleepTimerMenu
[model]="sleepTimerOptions"
[popup]="true"
appendTo="body"
/>
</div>
<!-- Audio details -->
<div class="audio-details">
@if (audiobookInfo.narrator) {
<span class="detail-item">
<i class="pi pi-user"></i>
{{ t('details.narratedBy', { narrator: audiobookInfo.narrator }) }}
</span>
}
@if (audiobookInfo.bitrate) {
<span class="detail-item">
<i class="pi pi-sliders-h"></i>
{{ t('details.kbps', { bitrate: audiobookInfo.bitrate }) }}
</span>
}
@if (audiobookInfo.durationMs) {
<span class="detail-item">
<i class="pi pi-clock"></i>
{{ t('details.totalDuration', { duration: formatDuration(audiobookInfo.durationMs) }) }}
</span>
}
</div>
</main>
<!-- Track/Chapter list sidebar -->
@if (showTrackList) {
<aside class="track-list-sidebar">
<div class="sidebar-header">
<h2>{{ audiobookInfo.folderBased ? t('sidebar.tracks') : t('sidebar.chapters') }}</h2>
<p-button
icon="pi pi-times"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="toggleTrackList()"
/>
</div>
<div class="sidebar-content">
@if (audiobookInfo.folderBased && audiobookInfo.tracks) {
<ul class="track-list">
@for (track of audiobookInfo.tracks; track track.index) {
<li
class="track-item"
[class.active]="track.index === currentTrackIndex"
(click)="selectTrack(track)"
>
<span class="track-index">{{ track.index + 1 }}</span>
<div class="track-details">
<span class="track-name">{{ track.title }}</span>
<span class="track-duration">{{ formatDuration(track.durationMs) }}</span>
</div>
@if (track.index === currentTrackIndex && isPlaying) {
<i class="pi pi-volume-up playing-indicator"></i>
}
</li>
}
</ul>
} @else if (audiobookInfo.chapters) {
<ul class="track-list">
@for (chapter of audiobookInfo.chapters; track chapter.index) {
<li
class="track-item"
[class.active]="getCurrentChapter()?.index === chapter.index"
(click)="selectChapter(chapter)"
>
<span class="track-index">{{ chapter.index + 1 }}</span>
<div class="track-details">
<span class="track-name">{{ chapter.title }}</span>
<span class="track-duration">{{ formatDuration(chapter.durationMs) }}</span>
</div>
@if (getCurrentChapter()?.index === chapter.index && isPlaying) {
<i class="pi pi-volume-up playing-indicator"></i>
}
</li>
}
</ul>
}
</div>
</aside>
}
<!-- Bookmark list sidebar -->
@if (showBookmarkList) {
<aside class="track-list-sidebar bookmark-sidebar">
<div class="sidebar-header">
<h2>{{ t('bookmarks.title') }}</h2>
<p-button
icon="pi pi-times"
[rounded]="true"
[text]="true"
severity="secondary"
(onClick)="toggleBookmarkList()"
/>
</div>
<div class="sidebar-content">
@if (bookmarks.length === 0) {
<div class="empty-bookmarks">
<i class="pi pi-bookmark"></i>
<p>{{ t('bookmarks.empty') }}</p>
<span>{{ t('bookmarks.emptyHint') }}</span>
</div>
} @else {
<ul class="track-list">
@for (bookmark of bookmarks; track bookmark.id) {
<li
class="track-item bookmark-item"
(click)="goToBookmark(bookmark)"
>
<i class="pi pi-bookmark-fill bookmark-icon"></i>
<div class="track-details">
<span class="track-name">{{ bookmark.title }}</span>
<span class="track-duration">{{ formatBookmarkPosition(bookmark) }}</span>
</div>
<p-button
icon="pi pi-trash"
[rounded]="true"
[text]="true"
severity="danger"
size="small"
(onClick)="deleteBookmark($event, bookmark.id)"
[pTooltip]="t('bookmarks.deleteTooltip')"
tooltipPosition="left"
/>
</li>
}
</ul>
}
</div>
</aside>
}
</div>
} @else {
<div class="loading-container">
<span class="loading-text">{{ t('toast.loadFailed') }}</span>
</div>
}
</ng-container>
@@ -0,0 +1,803 @@
@use 'sass:color';
// Variables - More vibrant color palette
$bg-primary: #0f0f1a;
$bg-secondary: #1a1a2e;
$bg-tertiary: #252542;
$bg-darker: #0a0a12;
$text-primary: #ffffff;
$text-secondary: rgba(255, 255, 255, 0.8);
$text-tertiary: rgba(255, 255, 255, 0.5);
$accent-secondary: #ec4899;
$accent-tertiary: #06b6d4;
$border-color: rgba(255, 255, 255, 0.1);
// CSS variable for primary color from theme
:host {
--accent-color: var(--primary-color, #8b5cf6);
--accent-hover: var(--primary-hover-color, #a78bfa);
}
// Gradient mixins
@mixin gradient-bg {
background: linear-gradient(135deg, $bg-secondary 0%, $bg-primary 50%, $bg-darker 100%);
}
@mixin accent-gradient {
background: linear-gradient(135deg, var(--accent-color) 0%, $accent-secondary 100%);
}
@mixin glow-effect($color, $intensity: 0.4) {
box-shadow: 0 0 40px rgba($color, $intensity),
0 0 80px rgba($color, $intensity * 0.5);
}
// Loading container
.loading-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
@include gradient-bg;
gap: 1rem;
.loading-text {
color: $text-secondary;
font-size: 0.9rem;
}
::ng-deep .p-progress-spinner-circle {
stroke: var(--accent-color) !important;
}
}
// Main container
.audiobook-player {
display: flex;
flex-direction: column;
height: 100vh;
@include gradient-bg;
color: $text-primary;
overflow: hidden;
position: relative;
// Subtle animated gradient overlay
&::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: radial-gradient(ellipse at 20% 0%, color-mix(in srgb, var(--accent-color) 15%, transparent) 0%, transparent 50%),
radial-gradient(ellipse at 80% 100%, rgba($accent-secondary, 0.1) 0%, transparent 50%);
pointer-events: none;
z-index: 0;
}
}
// Header
.reader-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1rem 1.5rem;
background: rgba(0, 0, 0, 0.4);
backdrop-filter: blur(20px);
border-bottom: 1px solid $border-color;
z-index: 10;
position: relative;
.header-info {
flex: 1;
text-align: center;
padding: 0 1rem;
overflow: hidden;
.book-title {
font-size: 1.1rem;
font-weight: 600;
margin: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
background: linear-gradient(90deg, $text-primary, var(--accent-color));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.book-author {
font-size: 0.85rem;
color: $text-secondary;
}
}
.header-actions {
display: flex;
gap: 0.25rem;
}
::ng-deep .p-button {
&.p-button-text {
color: $text-secondary;
&:hover {
color: $text-primary;
background: color-mix(in srgb, var(--accent-color) 20%, transparent);
}
}
}
}
// Main content
.reader-main {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
padding: 2rem 1.5rem;
overflow-y: auto;
gap: 1.5rem;
position: relative;
z-index: 1;
}
// Cover art
.cover-container {
flex-shrink: 0;
width: 100%;
max-width: min(480px, 40vh);
aspect-ratio: 1;
.cover-wrapper {
position: relative;
width: 100%;
height: 100%;
border-radius: 16px;
overflow: hidden;
box-shadow:
0 25px 60px -12px rgba(0, 0, 0, 0.6),
0 0 0 1px rgba(255, 255, 255, 0.1),
0 0 60px color-mix(in srgb, var(--accent-color) 20%, transparent),
0 0 100px rgba($accent-secondary, 0.1);
transition: transform 0.3s ease, box-shadow 0.3s ease;
&:hover {
transform: scale(1.02);
box-shadow:
0 30px 70px -12px rgba(0, 0, 0, 0.7),
0 0 0 1px rgba(255, 255, 255, 0.15),
0 0 80px color-mix(in srgb, var(--accent-color) 30%, transparent),
0 0 120px rgba($accent-secondary, 0.15);
}
.cover-image {
width: 100%;
height: 100%;
object-fit: cover;
}
.cover-loading {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, 0.7);
backdrop-filter: blur(4px);
}
.cover-placeholder {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
@include accent-gradient;
opacity: 0.8;
i {
font-size: 5rem;
color: rgba(255, 255, 255, 0.9);
text-shadow: 0 0 30px rgba(255, 255, 255, 0.5);
}
}
}
}
// Track info
.track-info {
text-align: center;
min-height: 3rem;
.track-title {
display: block;
font-size: 1.1rem;
font-weight: 600;
color: $text-primary;
margin-bottom: 0.25rem;
}
.track-number {
font-size: 0.85rem;
color: var(--accent-color);
font-weight: 500;
}
}
// Progress bar
.progress-container {
width: 100%;
max-width: 500px;
.time-display {
display: flex;
justify-content: space-between;
margin-bottom: 0.75rem;
font-size: 0.85rem;
color: $text-secondary;
font-variant-numeric: tabular-nums;
font-weight: 500;
}
.progress-bar-wrapper {
position: relative;
height: 8px;
background: rgba(255, 255, 255, 0.1);
border-radius: 4px;
overflow: visible;
.buffered-bar {
position: absolute;
top: 0;
left: 0;
height: 100%;
background: rgba(255, 255, 255, 0.15);
border-radius: 4px;
transition: width 0.3s ease;
}
::ng-deep .progress-slider {
position: absolute;
top: 50%;
left: 0;
right: 0;
transform: translateY(-50%);
.p-slider {
background: transparent;
height: 8px;
.p-slider-range {
@include accent-gradient;
border-radius: 4px;
box-shadow: 0 0 10px color-mix(in srgb, var(--accent-color) 50%, transparent);
}
.p-slider-handle {
width: 18px;
height: 18px;
background: $text-primary;
border: 3px solid var(--accent-color);
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.4),
0 0 15px color-mix(in srgb, var(--accent-color) 40%, transparent);
transition: transform 0.15s ease, box-shadow 0.15s ease;
&:hover {
transform: scale(1.2);
box-shadow: 0 2px 15px rgba(0, 0, 0, 0.5),
0 0 25px color-mix(in srgb, var(--accent-color) 60%, transparent);
}
}
}
}
}
}
// Playback controls
.playback-controls {
display: flex;
align-items: center;
justify-content: center;
gap: 1rem;
::ng-deep .play-button {
.p-button {
width: 72px;
height: 72px;
font-size: 1.75rem;
@include accent-gradient;
border: none;
box-shadow: 0 8px 30px color-mix(in srgb, var(--accent-color) 40%, transparent),
0 0 50px color-mix(in srgb, var(--accent-color) 20%, transparent);
transition: transform 0.2s ease, box-shadow 0.2s ease;
&:hover {
transform: scale(1.05);
box-shadow: 0 10px 40px color-mix(in srgb, var(--accent-color) 50%, transparent),
0 0 70px color-mix(in srgb, var(--accent-color) 30%, transparent);
}
&:active {
transform: scale(0.98);
}
.p-button-icon {
font-size: 1.75rem;
}
}
}
::ng-deep .p-button {
&.p-button-text {
color: $text-secondary;
transition: all 0.2s ease;
&:hover {
color: $text-primary;
background: color-mix(in srgb, var(--accent-color) 20%, transparent);
transform: scale(1.1);
}
&:disabled {
color: $text-tertiary;
opacity: 0.4;
transform: none;
}
}
&.p-button-lg {
width: 48px;
height: 48px;
}
}
}
// Secondary controls
.secondary-controls {
display: flex;
align-items: center;
justify-content: center;
gap: 2rem;
width: 100%;
max-width: 500px;
padding: 1rem 0;
}
.volume-control {
display: flex;
align-items: center;
gap: 0.75rem;
::ng-deep .p-button.p-button-text {
color: $text-secondary;
&:hover {
color: var(--accent-color);
background: color-mix(in srgb, var(--accent-color) 15%, transparent);
}
}
::ng-deep .volume-slider {
width: 100px;
.p-slider {
background: rgba(255, 255, 255, 0.15);
height: 5px;
border-radius: 3px;
.p-slider-range {
background: $accent-tertiary;
border-radius: 3px;
}
.p-slider-handle {
width: 14px;
height: 14px;
background: $text-primary;
border: 2px solid $accent-tertiary;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
}
}
}
}
.speed-control {
::ng-deep .p-selectbutton {
.p-button {
padding: 0.5rem 0.75rem;
font-size: 0.8rem;
font-weight: 600;
background: rgba(255, 255, 255, 0.08);
border: 1px solid rgba(255, 255, 255, 0.1);
color: $text-secondary;
transition: all 0.2s ease;
&:hover {
background: rgba(255, 255, 255, 0.12);
color: $text-primary;
border-color: rgba(255, 255, 255, 0.2);
}
&.p-highlight {
@include accent-gradient;
color: $text-primary;
border-color: transparent;
box-shadow: 0 4px 15px color-mix(in srgb, var(--accent-color) 30%, transparent);
}
}
}
}
// Audio details
.audio-details {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 1.25rem;
padding: 1rem;
color: $text-tertiary;
font-size: 0.8rem;
background: rgba(255, 255, 255, 0.03);
border-radius: 12px;
margin-top: 0.5rem;
.detail-item {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem 0.75rem;
background: rgba(255, 255, 255, 0.05);
border-radius: 8px;
white-space: nowrap;
i {
font-size: 0.9rem;
color: $accent-tertiary;
}
}
}
// Extra controls (bookmark, sleep timer)
.extra-controls {
display: flex;
align-items: center;
justify-content: center;
gap: 1rem;
padding-top: 0.5rem;
::ng-deep .p-button {
&.p-button-text {
color: $text-secondary;
font-size: 0.85rem;
&:hover {
color: $text-primary;
background: color-mix(in srgb, var(--accent-color) 15%, transparent);
}
.p-button-icon {
font-size: 1rem;
}
}
&.sleep-timer-active {
color: #fbbf24 !important;
&:hover {
background: rgba(251, 191, 36, 0.15) !important;
}
}
}
}
// Empty bookmarks
.empty-bookmarks {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 3rem 1.5rem;
text-align: center;
color: $text-tertiary;
i {
font-size: 3rem;
margin-bottom: 1rem;
opacity: 0.5;
}
p {
margin: 0 0 0.5rem;
font-size: 1rem;
font-weight: 500;
color: $text-secondary;
}
span {
font-size: 0.85rem;
}
}
// Bookmark item
.bookmark-item {
.bookmark-icon {
color: var(--accent-color);
font-size: 1.1rem;
flex-shrink: 0;
}
::ng-deep .p-button {
opacity: 0;
transition: opacity 0.2s ease;
}
&:hover {
::ng-deep .p-button {
opacity: 1;
}
}
}
// Track list sidebar
.track-list-sidebar {
position: fixed;
top: 0;
right: 0;
width: 100%;
max-width: 400px;
height: 100vh;
background: linear-gradient(180deg, $bg-tertiary 0%, $bg-secondary 100%);
border-left: 1px solid color-mix(in srgb, var(--accent-color) 20%, transparent);
z-index: 100;
display: flex;
flex-direction: column;
animation: slideIn 0.25s ease-out;
box-shadow: -10px 0 40px rgba(0, 0, 0, 0.5);
@keyframes slideIn {
from {
transform: translateX(100%);
opacity: 0.5;
}
to {
transform: translateX(0);
opacity: 1;
}
}
.sidebar-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.25rem 1.5rem;
border-bottom: 1px solid $border-color;
background: rgba(0, 0, 0, 0.2);
h2 {
margin: 0;
font-size: 1.2rem;
font-weight: 600;
background: linear-gradient(90deg, $text-primary, var(--accent-color));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
::ng-deep .p-button.p-button-text {
color: $text-secondary;
&:hover {
color: $text-primary;
background: color-mix(in srgb, var(--accent-color) 20%, transparent);
}
}
}
.sidebar-content {
flex: 1;
overflow-y: auto;
padding: 0.5rem 0;
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: color-mix(in srgb, var(--accent-color) 30%, transparent);
border-radius: 3px;
&:hover {
background: color-mix(in srgb, var(--accent-color) 50%, transparent);
}
}
}
}
.track-list {
list-style: none;
margin: 0;
padding: 0;
.track-item {
display: flex;
align-items: center;
padding: 1rem 1.5rem;
cursor: pointer;
transition: all 0.2s ease;
gap: 1rem;
border-left: 3px solid transparent;
&:hover {
background: color-mix(in srgb, var(--accent-color) 10%, transparent);
border-left-color: color-mix(in srgb, var(--accent-color) 50%, transparent);
}
&.active {
background: linear-gradient(90deg, color-mix(in srgb, var(--accent-color) 20%, transparent) 0%, transparent 100%);
border-left-color: var(--accent-color);
.track-index {
color: var(--accent-color);
font-weight: 700;
}
.track-name {
color: var(--accent-color);
}
}
.track-index {
width: 2rem;
text-align: center;
font-size: 0.9rem;
color: $text-tertiary;
flex-shrink: 0;
font-weight: 600;
}
.track-details {
flex: 1;
min-width: 0;
.track-name {
display: block;
font-size: 0.95rem;
color: $text-primary;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
font-weight: 500;
}
.track-duration {
font-size: 0.8rem;
color: $text-tertiary;
margin-top: 0.2rem;
}
}
.playing-indicator {
color: var(--accent-color);
animation: pulse 1.5s ease-in-out infinite;
font-size: 1.1rem;
}
@keyframes pulse {
0%, 100% {
opacity: 1;
transform: scale(1);
}
50% {
opacity: 0.6;
transform: scale(0.95);
}
}
}
}
// Responsive adjustments
@media (max-width: 768px) {
.reader-main {
padding: 1rem;
gap: 1rem;
}
.cover-container {
max-width: min(360px, 35vh);
}
.secondary-controls {
flex-direction: column;
gap: 1rem;
}
.volume-control {
::ng-deep .volume-slider {
width: 150px;
}
}
.track-list-sidebar {
max-width: 75%;
}
.audio-details {
gap: 0.75rem;
padding: 0.75rem;
.detail-item {
padding: 0.4rem 0.6rem;
font-size: 0.75rem;
i {
font-size: 0.8rem;
}
}
}
}
@media (max-width: 480px) {
.cover-container {
max-width: min(300px, 30vh);
}
.playback-controls {
gap: 0.5rem;
::ng-deep .play-button {
.p-button {
width: 64px;
height: 64px;
}
}
::ng-deep .p-button.p-button-lg {
width: 40px;
height: 40px;
}
}
.audio-details {
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
gap: 0.5rem;
.detail-item {
flex: 0 1 auto;
}
}
}
// Landscape mode optimization
@media (max-height: 600px) and (orientation: landscape) {
.reader-main {
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
gap: 1rem;
}
.cover-container {
max-width: 180px;
}
.track-info,
.progress-container,
.playback-controls,
.secondary-controls {
width: auto;
}
.audio-details {
flex-direction: row;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,39 @@
export interface AudiobookInfo {
bookId: number;
bookFileId: number;
title?: string;
author?: string;
narrator?: string;
durationMs: number;
bitrate?: number;
codec?: string;
sampleRate?: number;
channels?: number;
folderBased: boolean;
chapters?: AudiobookChapter[];
tracks?: AudiobookTrack[];
}
export interface AudiobookChapter {
index: number;
title: string;
startTimeMs: number;
endTimeMs: number;
durationMs: number;
}
export interface AudiobookTrack {
index: number;
fileName: string;
title: string;
durationMs: number;
fileSizeBytes: number;
cumulativeStartMs: number;
}
export interface AudiobookProgress {
positionMs: number;
trackIndex?: number;
trackPositionMs?: number;
percentage: number;
}
@@ -0,0 +1,64 @@
import { inject, Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { API_CONFIG } from '../../../core/config/api-config';
import { AudiobookInfo, AudiobookProgress } from './audiobook.model';
import { AuthService } from '../../../shared/service/auth.service';
import { BookFileProgress } from '../../book/model/book.model';
@Injectable({
providedIn: 'root'
})
export class AudiobookService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/audiobooks`;
private readonly booksUrl = `${API_CONFIG.BASE_URL}/api/v1/books`;
private http = inject(HttpClient);
private authService = inject(AuthService);
getAudiobookInfo(bookId: number, bookType?: string): Observable<AudiobookInfo> {
const params: Record<string, string> = {};
if (bookType) {
params['bookType'] = bookType;
}
return this.http.get<AudiobookInfo>(`${this.baseUrl}/${bookId}/info`, { params });
}
getStreamUrl(bookId: number, trackIndex?: number): string {
const token = this.authService.getInternalAccessToken();
let url = `${this.baseUrl}/${bookId}/stream?ngsw-bypass=true&token=${encodeURIComponent(token || '')}`;
if (trackIndex !== undefined && trackIndex !== null) {
url += `&trackIndex=${trackIndex}`;
}
return url;
}
getTrackStreamUrl(bookId: number, trackIndex: number): string {
const token = this.authService.getInternalAccessToken();
return `${this.baseUrl}/${bookId}/track/${trackIndex}/stream?ngsw-bypass=true&token=${encodeURIComponent(token || '')}`;
}
getEmbeddedCoverUrl(bookId: number): string {
const token = this.authService.getInternalAccessToken();
return `${this.baseUrl}/${bookId}/cover?ngsw-bypass=true&token=${encodeURIComponent(token || '')}`;
}
saveProgress(bookId: number, progress: AudiobookProgress, bookFileId?: number): Observable<void> {
if (bookFileId) {
const fileProgress: BookFileProgress = {
bookFileId: bookFileId,
positionData: progress.positionMs.toString(),
positionHref: progress.trackIndex?.toString(),
progressPercent: progress.percentage
};
return this.http.post<void>(`${this.booksUrl}/progress`, {
bookId,
fileProgress
});
}
return this.http.post<void>(`${this.booksUrl}/progress`, {
bookId,
audiobookProgress: progress
});
}
}
@@ -0,0 +1,3 @@
export * from './audiobook-player.component';
export * from './audiobook.service';
export * from './audiobook.model';
@@ -0,0 +1,118 @@
<div class="comic-reader-container" tabindex="0"
[class.rtl-reading]="readingDirection === CbxReadingDirection.RTL"
[class.fullscreen-mode]="isFullscreen"
[class.slideshow-active]="isSlideshowActive">
<app-cbx-header [isCurrentPageBookmarked]="isCurrentPageBookmarked" [currentPageHasNotes]="currentPageHasNotes"></app-cbx-header>
<app-cbx-sidebar></app-cbx-sidebar>
@if (showQuickSettings) {
<app-cbx-quick-settings></app-cbx-quick-settings>
}
@if (isCurrentPageBookmarked) {
<div class="bookmark-indicator">
<svg width="48" height="64" viewBox="0 0 48 64">
<polygon points="0,0 48,0 48,64 24,48 0,64" fill="red"/>
</svg>
</div>
}
@if (showNoteDialog) {
<app-cbx-note-dialog
[data]="noteDialogData"
(save)="onNoteSave($event)"
(cancel)="onNoteCancel()"
></app-cbx-note-dialog>
}
@if (showShortcutsHelp) {
<app-cbx-shortcuts-help
(close)="onShortcutsHelpClose()"
></app-cbx-shortcuts-help>
}
@if (isSlideshowActive) {
<div class="slideshow-progress" [class.above-footer]="isFooterVisible" [style.animation-duration.ms]="slideshowInterval"></div>
}
<div #magnifierLens class="magnifier-lens"></div>
<div class="image-container"
[class.magnifier-active]="isMagnifierActive"
[class.two-page-view]="isTwoPageView && scrollMode === CbxScrollMode.PAGINATED"
[class.infinite-scroll]="scrollMode === CbxScrollMode.INFINITE"
[class.long-strip]="scrollMode === CbxScrollMode.LONG_STRIP"
[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" (click)="onImageClick()" (dblclick)="onImageDoubleClick()">
@if (isPageTransitioning && previousImageUrls.length > 0) {
<div class="previous-page-layer">
@for (url of previousImageUrls; track url) {
<img [src]="url" alt="Previous Page" class="page-image previous-image"/>
}
</div>
}
<div class="current-page-layer" [class.fade-in]="isPageTransitioning && imagesLoaded">
@for (url of currentImageUrls; track url; let i = $index) {
<img [src]="url" alt="Page Image" class="page-image" (load)="onPageImageLoad($event, currentPage + i)"/>
}
</div>
</div>
@if (isAtLastPage && nextBookInSeries) {
<div class="end-of-comic-action">
<button class="next-book-action-button" (click)="navigateToNextBook()">
<span class="action-icon">📖</span>
<span class="action-text">{{ 'readerCbx.reader.continueToNextBook' | transloco }}</span>
<span class="book-title">{{ getBookDisplayTitle(nextBookInSeries) }}</span>
</button>
</div>
}
} @else {
<div class="infinite-scroll-wrapper" [class.long-strip-wrapper]="scrollMode === CbxScrollMode.LONG_STRIP">
@for (pageIdx of infiniteScrollPages; track pageIdx; let i = $index) {
<img [src]="getPageImageUrl(pageIdx)" alt="Page {{ pageIdx + 1 }}" class="page-image" (click)="onImageClick()" (dblclick)="onImageDoubleClick()" (load)="onPageImageLoad($event, pageIdx)"/>
}
@if (isLoadingMore) {
<div class="loading-more">
<p-progressSpinner class="small-spinner"></p-progressSpinner>
</div>
}
@if (infiniteScrollPages.length > 0 && infiniteScrollPages[infiniteScrollPages.length - 1] >= pages.length - 1 && nextBookInSeries) {
<div class="end-of-comic-action">
<button class="next-book-action-button" (click)="navigateToNextBook()">
<span class="action-icon">📖</span>
<span class="action-text">{{ 'readerCbx.reader.continueToNextBook' | transloco }}</span>
<span class="book-title">{{ getBookDisplayTitle(nextBookInSeries) }}</span>
</button>
</div>
}
</div>
}
} @else {
<div class="no-pages">
<p>{{ 'readerCbx.reader.noPagesAvailable' | transloco }}</p>
</div>
}
} @else {
<div class="loader-overlay">
<div class="loader-content">
<div class="spinner"></div>
<p class="loader-text">{{ 'readerCbx.reader.loadingBook' | transloco }}</p>
</div>
</div>
}
</div>
<app-cbx-footer></app-cbx-footer>
</div>
@@ -0,0 +1,630 @@
.comic-reader-container {
display: flex;
flex-direction: column;
height: 100dvh;
width: 100vw;
overflow: hidden;
box-sizing: border-box;
background: #1a1a1a;
color: #ffffff;
position: relative;
touch-action: none;
overscroll-behavior: none;
-webkit-user-select: none;
user-select: none;
&:focus {
outline: none;
}
// RTL reading mode - reverse page order in two-page view
&.rtl-reading {
.two-page-view {
.pages-wrapper,
.previous-page-layer,
.current-page-layer {
flex-direction: row-reverse;
}
}
}
// Slideshow progress bar
.slideshow-progress {
position: absolute;
bottom: 0;
left: 0;
height: 3px;
background: #4a90e2;
z-index: 1001;
pointer-events: none;
animation: slideshow-fill linear infinite;
transition: bottom 0.3s ease;
&.above-footer {
bottom: 52px;
}
}
@keyframes slideshow-fill {
from { width: 0; }
to { width: 100%; }
}
.magnifier-lens {
position: fixed;
top: 0;
left: 0;
display: none;
border-radius: 50%;
border: 3px solid rgba(255, 255, 255, 0.8);
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.3), 0 8px 32px rgba(0, 0, 0, 0.5);
pointer-events: none;
z-index: 1000;
background-repeat: no-repeat;
}
.bookmark-indicator {
position: absolute;
top: 0;
right: 24px;
z-index: 10;
pointer-events: none;
filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3));
svg {
display: block;
}
}
.image-container {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
padding: 0.5rem;
background: #0f0f0f;
min-height: 0;
&:not(.two-page-view):not(.infinite-scroll) {
flex-direction: column;
align-items: stretch;
.pages-wrapper {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
min-height: 0;
}
.end-of-comic-action {
flex: 0 0 auto;
margin-top: 1rem;
}
}
&.magnifier-active {
cursor: none;
}
&.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;
}
.previous-page-layer,
.current-page-layer {
display: flex;
gap: 1rem;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
}
.previous-page-layer {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1;
}
.current-page-layer {
position: relative;
z-index: 2;
&.fade-in {
animation: fadeIn 0.15s ease-out forwards;
}
}
@keyframes fadeIn {
from {
opacity: 0.7;
}
to {
opacity: 1;
}
}
.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);
}
&.previous-image {
&:hover {
transform: none;
}
}
}
&.fit-width {
.pages-wrapper,
.previous-page-layer,
.current-page-layer {
height: auto;
max-height: 100%;
}
.page-image {
width: 100%;
height: auto;
&:hover {
transform: scale(1.02);
}
}
&.two-page-view {
.pages-wrapper,
.previous-page-layer,
.current-page-layer {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
}
.page-image {
width: 100%;
height: auto;
}
}
}
&.fit-height {
.pages-wrapper,
.previous-page-layer,
.current-page-layer {
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,
.previous-page-layer,
.current-page-layer {
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;
touch-action: pan-y;
overscroll-behavior: contain;
.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 - 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 - 2rem);
width: auto;
height: auto;
}
}
&.fit-auto {
.infinite-scroll-wrapper {
min-height: 100%;
}
.page-image {
max-width: 100%;
max-height: calc(100vh - 2rem);
width: auto;
height: auto;
}
}
.loading-more {
padding: 2rem;
display: flex;
justify-content: center;
}
}
// Long Strip / Webtoon mode - no gaps between pages
&.long-strip {
overflow-y: auto;
overflow-x: hidden;
align-items: flex-start;
touch-action: pan-y;
-webkit-overflow-scrolling: touch;
overscroll-behavior: contain;
.long-strip-wrapper {
display: flex;
flex-direction: column;
align-items: center;
gap: 0;
width: 100%;
padding: 0;
}
.page-image {
box-shadow: none;
border-radius: 0;
transition: none;
display: block;
&:hover {
transform: none;
}
}
&.fit-width .page-image {
width: 100%;
height: auto;
}
&.fit-height .page-image {
width: auto;
height: auto;
max-width: 100%;
}
&.fit-actual-size {
overflow-x: auto;
.long-strip-wrapper {
width: max-content;
min-width: 100%;
}
.page-image {
width: auto;
height: auto;
}
}
&.fit-page .page-image,
&.fit-auto .page-image {
max-width: 100%;
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;
}
.end-of-comic-action {
display: flex;
justify-content: center;
align-items: center;
padding: 2rem 1rem;
.next-book-action-button {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.75rem;
padding: 2rem 3rem;
background: linear-gradient(135deg, #4a90e2 0%, #357abd 100%);
border: none;
border-radius: 12px;
font-weight: 600;
color: #ffffff;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 4px 20px rgba(74, 144, 226, 0.3);
min-width: 280px;
&:hover {
transform: translateY(-2px);
box-shadow: 0 8px 30px rgba(74, 144, 226, 0.5);
background: linear-gradient(135deg, #357abd 0%, #2a6399 100%);
}
&:active {
transform: translateY(0);
}
.action-icon {
font-size: 2.5rem;
}
.action-text {
font-size: 1.1rem;
}
.book-title {
font-size: 0.95rem;
font-weight: 400;
opacity: 0.9;
max-width: 350px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
}
}
@media (max-width: 768px) {
.comic-reader-container {
.slideshow-progress.above-footer {
bottom: 48px;
}
.image-container {
top: 0;
bottom: 0;
}
.end-of-comic-action {
padding: 1.5rem 1rem;
.next-book-action-button {
min-width: 240px;
padding: 1.5rem 2rem;
.action-icon { font-size: 2rem; }
.action-text { font-size: 1rem; }
.book-title {
font-size: 0.85rem;
max-width: 250px;
}
}
}
}
}
.loader-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.8);
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
}
.loader-content {
display: flex;
flex-direction: column;
align-items: center;
gap: 1.5rem;
}
.spinner {
width: 48px;
height: 48px;
border: 4px solid rgba(255, 255, 255, 0.2);
border-top-color: #fff;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
.loader-text {
color: #fff;
font-size: 1.1rem;
margin: 0;
font-weight: 500;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,49 @@
<div class="dialog-overlay" (click)="onOverlayClick($event)">
<div class="dialog">
<div class="dialog-header">
<h2>{{ isEditing ? ('readerCbx.noteDialog.editNote' | transloco) : ('readerCbx.noteDialog.addNote' | transloco) }}</h2>
<button class="close-btn" (click)="onCancel()">
<app-reader-icon name="close" [size]="18"></app-reader-icon>
</button>
</div>
<div class="dialog-body">
<div class="page-info-section">
<span class="section-label">{{ 'readerCbx.noteDialog.pageLabel' | transloco }}</span>
<p class="page-info">{{ 'readerCbx.noteDialog.pageInfo' | transloco: { pageNumber: data?.pageNumber } }}</p>
</div>
<div class="note-section">
<label class="section-label" for="noteContent">{{ 'readerCbx.noteDialog.yourNote' | transloco }}</label>
<textarea
id="noteContent"
class="note-input"
[(ngModel)]="noteContent"
[placeholder]="'readerCbx.noteDialog.placeholder' | transloco"
rows="6"
autofocus
></textarea>
</div>
<div class="color-section">
<span class="section-label">{{ 'readerCbx.noteDialog.noteColor' | transloco }}</span>
<div class="color-buttons">
@for (color of noteColors; track color.value) {
<button
class="color-btn"
[style.--color]="color.value"
[class.selected]="selectedColor === color.value"
[title]="color.label"
(click)="selectColor(color.value)">
</button>
}
</div>
</div>
</div>
<div class="dialog-footer">
<button class="btn btn-secondary" (click)="onCancel()">{{ 'common.cancel' | transloco }}</button>
<button class="btn btn-primary" (click)="onSave()" [disabled]="!noteContent.trim()">{{ isEditing ? ('readerCbx.noteDialog.updateNote' | transloco) : ('readerCbx.noteDialog.saveNote' | transloco) }}</button>
</div>
</div>
</div>
@@ -0,0 +1,258 @@
// Variables matching reader styling
$dialog-bg: #1a1a1a;
$text-primary: rgba(255, 255, 255, 0.95);
$text-secondary: rgba(255, 255, 255, 0.6);
$text-muted: rgba(255, 255, 255, 0.4);
$border-color: rgba(255, 255, 255, 0.08);
$hover-bg: rgba(255, 255, 255, 0.08);
$active-color: #4a90e2;
$active-bg: rgba(74, 144, 226, 0.15);
$transition-fast: 150ms ease;
$transition-normal: 200ms ease;
.dialog-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(4px);
z-index: 13000;
display: flex;
align-items: center;
justify-content: center;
animation: fadeIn $transition-normal;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.dialog {
background: $dialog-bg;
border: 1px solid $border-color;
border-radius: 12px;
width: 90%;
max-width: 500px;
max-height: 85vh;
display: flex;
flex-direction: column;
overflow: hidden;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
animation: slideUp 250ms cubic-bezier(0.4, 0, 0.2, 1);
}
@keyframes slideUp {
from {
transform: translateY(20px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.dialog-header {
padding: 16px 20px;
border-bottom: 1px solid $border-color;
display: flex;
align-items: center;
justify-content: space-between;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.02) 0%, transparent 100%);
h2 {
margin: 0;
font-size: 16px;
font-weight: 600;
color: $text-primary;
letter-spacing: -0.3px;
}
}
.close-btn {
background: none;
border: none;
color: $text-muted;
cursor: pointer;
padding: 6px;
border-radius: 6px;
transition: background $transition-fast, color $transition-fast;
line-height: 1;
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
&:hover {
background: $hover-bg;
color: $text-primary;
}
}
.dialog-body {
padding: 20px;
overflow-y: auto;
flex: 1;
display: flex;
flex-direction: column;
gap: 20px;
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.15);
border-radius: 3px;
&:hover {
background: rgba(255, 255, 255, 0.25);
}
}
}
.section-label {
display: block;
color: $text-muted;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 1px;
margin-bottom: 8px;
}
.page-info-section {
.page-info {
margin: 0;
padding: 12px 16px;
background: rgba(255, 255, 255, 0.03);
border-left: 3px solid $active-color;
border-radius: 0 8px 8px 0;
color: $text-secondary;
font-size: 13px;
line-height: 1.6;
}
}
.note-section {
flex: 1;
display: flex;
flex-direction: column;
}
.note-input {
flex: 1;
min-height: 120px;
padding: 12px 16px;
background: rgba(255, 255, 255, 0.03);
border: 1px solid $border-color;
border-radius: 8px;
color: $text-primary;
font-size: 14px;
line-height: 1.6;
resize: vertical;
font-family: inherit;
transition: border-color $transition-fast, box-shadow $transition-fast;
&::placeholder {
color: $text-muted;
}
&:focus {
outline: none;
border-color: $active-color;
box-shadow: 0 0 0 3px rgba(74, 144, 226, 0.15);
}
}
.color-section {
.color-buttons {
display: flex;
gap: 10px;
}
}
.color-btn {
width: 32px;
height: 32px;
border-radius: 50%;
border: 2px solid transparent;
background: var(--color);
cursor: pointer;
transition: transform $transition-fast, border-color $transition-fast, box-shadow $transition-fast;
position: relative;
&:hover {
transform: scale(1.1);
}
&.selected {
border-color: $text-primary;
box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.2);
&::after {
content: '\2713';
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 14px;
font-weight: bold;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}
}
}
.dialog-footer {
padding: 16px 20px;
border-top: 1px solid $border-color;
display: flex;
justify-content: flex-end;
gap: 12px;
background: linear-gradient(0deg, rgba(255, 255, 255, 0.02) 0%, transparent 100%);
}
.btn {
padding: 10px 20px;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background $transition-fast, transform $transition-fast, opacity $transition-fast;
border: none;
&:active {
transform: scale(0.98);
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
transform: none;
}
}
.btn-secondary {
background: $hover-bg;
color: $text-primary;
&:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.12);
}
}
.btn-primary {
background: $active-color;
color: white;
&:hover:not(:disabled) {
background: #5a9ee6;
}
}
@@ -0,0 +1,80 @@
import {Component, EventEmitter, inject, Input, Output, OnChanges, SimpleChanges} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {TranslocoService, TranslocoPipe} from '@jsverse/transloco';
import {ReaderIconComponent} from '../../ebook-reader/shared/icon.component';
export interface CbxNoteDialogData {
pageNumber: number;
noteId?: number;
noteContent?: string;
color?: string;
}
export interface CbxNoteDialogResult {
noteContent: string;
color: string;
}
@Component({
selector: 'app-cbx-note-dialog',
standalone: true,
imports: [CommonModule, FormsModule, TranslocoPipe, ReaderIconComponent],
templateUrl: './cbx-note-dialog.component.html',
styleUrls: ['./cbx-note-dialog.component.scss']
})
export class CbxNoteDialogComponent implements OnChanges {
private readonly t = inject(TranslocoService);
@Input() data: CbxNoteDialogData | null = null;
@Output() save = new EventEmitter<CbxNoteDialogResult>();
@Output() cancel = new EventEmitter<void>();
noteContent = '';
selectedColor = '#FFC107';
get isEditing(): boolean {
return !!this.data?.noteId;
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['data'] && this.data) {
this.noteContent = this.data.noteContent || '';
this.selectedColor = this.data.color || '#FFC107';
}
}
get noteColors() {
return [
{value: '#FFC107', label: this.t.translate('readerCbx.noteDialog.colorAmber')},
{value: '#4CAF50', label: this.t.translate('readerCbx.noteDialog.colorGreen')},
{value: '#2196F3', label: this.t.translate('readerCbx.noteDialog.colorBlue')},
{value: '#E91E63', label: this.t.translate('readerCbx.noteDialog.colorPink')},
{value: '#9C27B0', label: this.t.translate('readerCbx.noteDialog.colorPurple')},
{value: '#FF5722', label: this.t.translate('readerCbx.noteDialog.colorDeepOrange')}
];
}
onSave(): void {
if (this.noteContent.trim()) {
this.save.emit({
noteContent: this.noteContent.trim(),
color: this.selectedColor
});
}
}
onCancel(): void {
this.cancel.emit();
}
selectColor(color: string): void {
this.selectedColor = color;
}
onOverlayClick(event: MouseEvent): void {
if ((event.target as HTMLElement).classList.contains('dialog-overlay')) {
this.onCancel();
}
}
}
@@ -0,0 +1,42 @@
<div class="dialog-overlay" (click)="onOverlayClick($event)">
<div class="dialog">
<div class="dialog-header">
<h2>{{ 'readerCbx.shortcutsHelp.title' | transloco }}</h2>
<button class="close-btn" (click)="onClose()">
<app-reader-icon name="close" [size]="18"></app-reader-icon>
</button>
</div>
<div class="dialog-body">
@for (group of shortcutGroups; track group.title) {
<div class="shortcut-group">
<h3 class="group-title">{{ group.title }}</h3>
<div class="shortcuts-list">
@for (shortcut of group.shortcuts; track shortcut.description) {
<div class="shortcut-item">
<div class="shortcut-keys">
@for (key of shortcut.keys; track key; let last = $last) {
<kbd class="key">{{ key }}</kbd>
@if (!last) {
<span class="key-separator">+</span>
}
}
</div>
<div class="shortcut-info">
<span class="shortcut-description">{{ shortcut.description }}</span>
@if (isMobile && shortcut.mobileGesture) {
<span class="mobile-gesture">{{ shortcut.mobileGesture }}</span>
}
</div>
</div>
}
</div>
</div>
}
</div>
<div class="dialog-footer">
<button class="btn btn-primary" (click)="onClose()">{{ 'readerCbx.shortcutsHelp.gotIt' | transloco }}</button>
</div>
</div>
</div>
@@ -0,0 +1,245 @@
$dialog-bg: #1a1a1a;
$text-primary: rgba(255, 255, 255, 0.95);
$text-secondary: rgba(255, 255, 255, 0.6);
$text-muted: rgba(255, 255, 255, 0.4);
$border-color: rgba(255, 255, 255, 0.08);
$hover-bg: rgba(255, 255, 255, 0.08);
$active-color: #4a90e2;
$transition-fast: 150ms ease;
$transition-normal: 200ms ease;
.dialog-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(4px);
z-index: 13000;
display: flex;
align-items: center;
justify-content: center;
animation: fadeIn $transition-normal;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.dialog {
background: $dialog-bg;
border: 1px solid $border-color;
border-radius: 12px;
width: 90%;
max-width: 480px;
max-height: 85vh;
display: flex;
flex-direction: column;
overflow: hidden;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
animation: slideUp 250ms cubic-bezier(0.4, 0, 0.2, 1);
}
@keyframes slideUp {
from {
transform: translateY(20px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.dialog-header {
padding: 16px 20px;
border-bottom: 1px solid $border-color;
display: flex;
align-items: center;
justify-content: space-between;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.02) 0%, transparent 100%);
h2 {
margin: 0;
font-size: 16px;
font-weight: 600;
color: $text-primary;
letter-spacing: -0.3px;
}
}
.close-btn {
background: none;
border: none;
color: $text-muted;
cursor: pointer;
padding: 6px;
border-radius: 6px;
transition: background $transition-fast, color $transition-fast;
line-height: 1;
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
&:hover {
background: $hover-bg;
color: $text-primary;
}
}
.dialog-body {
padding: 20px;
overflow-y: auto;
flex: 1;
display: flex;
flex-direction: column;
gap: 24px;
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.15);
border-radius: 3px;
&:hover {
background: rgba(255, 255, 255, 0.25);
}
}
}
.shortcut-group {
.group-title {
margin: 0 0 12px 0;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 1px;
color: $text-muted;
}
}
.shortcuts-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.shortcut-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 8px 12px;
background: rgba(255, 255, 255, 0.03);
border-radius: 8px;
transition: background $transition-fast;
&:hover {
background: rgba(255, 255, 255, 0.05);
}
}
.shortcut-keys {
display: flex;
align-items: center;
gap: 4px;
flex-shrink: 0;
}
.key {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 28px;
height: 26px;
padding: 0 8px;
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 5px;
font-family: inherit;
font-size: 12px;
font-weight: 500;
color: $text-primary;
box-shadow: 0 2px 0 rgba(0, 0, 0, 0.2);
}
.key-separator {
color: $text-muted;
font-size: 12px;
margin: 0 2px;
}
.shortcut-info {
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 2px;
text-align: right;
}
.shortcut-description {
font-size: 13px;
color: $text-secondary;
}
.mobile-gesture {
font-size: 11px;
color: $active-color;
font-style: italic;
}
.dialog-footer {
padding: 16px 20px;
border-top: 1px solid $border-color;
display: flex;
justify-content: flex-end;
background: linear-gradient(0deg, rgba(255, 255, 255, 0.02) 0%, transparent 100%);
}
.btn {
padding: 10px 24px;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background $transition-fast, transform $transition-fast;
border: none;
&:active {
transform: scale(0.98);
}
}
.btn-primary {
background: $active-color;
color: white;
&:hover {
background: #5a9ee6;
}
}
@media (max-width: 480px) {
.dialog {
width: 95%;
max-height: 90vh;
}
.shortcut-item {
flex-direction: column;
align-items: flex-start;
gap: 8px;
}
.shortcut-info {
align-items: flex-start;
text-align: left;
}
}
@@ -0,0 +1,81 @@
import {Component, EventEmitter, inject, Output} from '@angular/core';
import {CommonModule} from '@angular/common';
import {TranslocoService, TranslocoPipe} from '@jsverse/transloco';
import {ReaderIconComponent} from '../../ebook-reader/shared/icon.component';
interface ShortcutItem {
keys: string[];
description: string;
mobileGesture?: string;
}
interface ShortcutGroup {
title: string;
shortcuts: ShortcutItem[];
}
@Component({
selector: 'app-cbx-shortcuts-help',
standalone: true,
imports: [CommonModule, TranslocoPipe, ReaderIconComponent],
templateUrl: './cbx-shortcuts-help.component.html',
styleUrls: ['./cbx-shortcuts-help.component.scss']
})
export class CbxShortcutsHelpComponent {
private readonly t = inject(TranslocoService);
@Output() close = new EventEmitter<void>();
get shortcutGroups(): ShortcutGroup[] {
return [
{
title: this.t.translate('readerCbx.shortcutsHelp.groupNavigation'),
shortcuts: [
{keys: ['←', '→'], description: this.t.translate('readerCbx.shortcutsHelp.previousNextPage'), mobileGesture: this.t.translate('readerCbx.shortcutsHelp.swipeLeftRight')},
{keys: ['Space'], description: this.t.translate('readerCbx.shortcutsHelp.nextPage')},
{keys: ['Shift', 'Space'], description: this.t.translate('readerCbx.shortcutsHelp.previousPage')},
{keys: ['Home'], description: this.t.translate('readerCbx.shortcutsHelp.firstPage')},
{keys: ['End'], description: this.t.translate('readerCbx.shortcutsHelp.lastPage')},
{keys: ['Page Up'], description: this.t.translate('readerCbx.shortcutsHelp.previousPage')},
{keys: ['Page Down'], description: this.t.translate('readerCbx.shortcutsHelp.nextPage')}
]
},
{
title: this.t.translate('readerCbx.shortcutsHelp.groupDisplay'),
shortcuts: [
{keys: ['F'], description: this.t.translate('readerCbx.shortcutsHelp.toggleFullscreen')},
{keys: ['D'], description: this.t.translate('readerCbx.shortcutsHelp.toggleReadingDirection')},
{keys: ['Escape'], description: this.t.translate('readerCbx.shortcutsHelp.exitFullscreenCloseDialogs')},
{keys: ['Double-click'], description: this.t.translate('readerCbx.shortcutsHelp.toggleZoom'), mobileGesture: this.t.translate('readerCbx.shortcutsHelp.doubleTap')},
{keys: ['M'], description: this.t.translate('readerCbx.shortcutsHelp.toggleMagnifier')},
{keys: ['+', '−'], description: this.t.translate('readerCbx.shortcutsHelp.magnifierZoom')},
{keys: ['[', ']'], description: this.t.translate('readerCbx.shortcutsHelp.magnifierLensSize')}
]
},
{
title: this.t.translate('readerCbx.shortcutsHelp.groupPlayback'),
shortcuts: [
{keys: ['P'], description: this.t.translate('readerCbx.shortcutsHelp.toggleSlideshow')}
]
},
{
title: this.t.translate('readerCbx.shortcutsHelp.groupOther'),
shortcuts: [
{keys: ['?'], description: this.t.translate('readerCbx.shortcutsHelp.showHelpDialog')}
]
}
];
}
isMobile = window.innerWidth < 768;
onClose(): void {
this.close.emit();
}
onOverlayClick(event: MouseEvent): void {
if ((event.target as HTMLElement).classList.contains('dialog-overlay')) {
this.onClose();
}
}
}
@@ -0,0 +1,90 @@
<div class="cbx-footer" [class.visible]="forceVisible()">
@if (state().hasSeries) {
<button
class="nav-btn series-btn"
(click)="onPreviousBook()"
[disabled]="!state().previousBookInSeries"
[title]="getPreviousBookTooltip()">
<app-reader-icon name="chevron-double-left" [size]="14" />
<span class="label hide-on-mobile">{{ 'readerCbx.footer.prevBook' | transloco }}</span>
</button>
}
<div class="page-nav-left">
<button class="nav-btn" (click)="onFirstPage()" [disabled]="!canGoPrevious" [title]="'readerCbx.footer.firstPage' | transloco">
<app-reader-icon name="chevron-first" [size]="16" />
</button>
<button class="nav-btn" (click)="onPreviousPage()" [disabled]="!canGoPrevious" [title]="'readerCbx.footer.previousPage' | transloco">
<app-reader-icon name="chevron-left" [size]="16" />
</button>
<div class="page-info">
<span class="current">{{ displayPage }}</span>
@if (displaySecondPage) {
<span class="separator">-{{ displaySecondPage }}</span>
}
<span class="total"> {{ 'readerCbx.footer.of' | transloco }} {{ state().totalPages }}</span>
</div>
<button class="nav-btn" (click)="onNextPage()" [disabled]="!canGoNext" [title]="'readerCbx.footer.nextPage' | transloco">
<app-reader-icon name="chevron-right" [size]="16" />
</button>
<button class="nav-btn" (click)="onLastPage()" [disabled]="!canGoNext" [title]="'readerCbx.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]="state().totalPages"
[value]="sliderValue"
(input)="onSliderChange($event)"
list="page-ticks"
[title]="'readerCbx.footer.pageSlider' | transloco"/>
<datalist id="page-ticks">
@for (tick of sliderTicks; track tick) {
<option [value]="tick"></option>
}
</datalist>
</div>
<div class="goto-page-wrapper">
<div class="goto-page">
<input
type="number"
[(ngModel)]="goToPageInput"
[min]="1"
[max]="state().totalPages"
[placeholder]="'readerCbx.footer.pagePlaceholder' | transloco"
class="page-input"
(keyup.enter)="onGoToPage()"
/>
<button
class="go-btn"
(click)="onGoToPage()"
[disabled]="goToPageInput === null || goToPageInput < 1 || goToPageInput > state().totalPages">
{{ 'readerCbx.footer.go' | transloco }}
</button>
</div>
</div>
</div>
<div class="page-nav-right">
</div>
@if (state().hasSeries) {
<button
class="nav-btn series-btn"
(click)="onNextBook()"
[disabled]="!state().nextBookInSeries"
[title]="getNextBookTooltip()">
<span class="label hide-on-mobile">{{ 'readerCbx.footer.nextBook' | transloco }}</span>
<app-reader-icon name="chevron-double-right" [size]="14" />
</button>
}
</div>
@@ -0,0 +1,347 @@
@use 'sass:color';
// Variables
$footer-bg: #1a1a1a;
$text-primary: rgba(255, 255, 255, 0.95);
$text-secondary: rgba(255, 255, 255, 0.6);
$text-muted: rgba(255, 255, 255, 0.4);
$border-color: rgba(255, 255, 255, 0.08);
$hover-bg: rgba(255, 255, 255, 0.08);
$active-color: #4a90e2;
$transition-fast: 150ms ease;
.cbx-footer {
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 52px;
padding: 0 16px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
z-index: 1000;
background: linear-gradient(135deg, #2d2d2d 0%, #1f1f1f 100%);
border-top: 1px solid #404040;
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.3);
color: $text-primary;
transform: translateY(100%);
opacity: 0;
transition: transform 0.3s ease, opacity 0.3s ease;
pointer-events: none;
&.visible {
transform: translateY(0);
opacity: 1;
pointer-events: auto;
}
}
.page-nav-left,
.page-nav-right {
display: flex;
align-items: center;
gap: 8px;
flex: 0 0 auto;
}
.series-nav {
flex: 0 0 auto;
min-width: 110px;
}
.page-nav {
display: flex;
align-items: center;
gap: 8px;
flex: 0 0 auto;
}
.nav-btn {
background: rgba(51, 51, 51, 0.9);
border: 1px solid #555;
color: $text-primary;
padding: 6px 10px;
border-radius: 4px;
cursor: pointer;
transition: all $transition-fast;
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
font-size: 14px;
font-weight: bold;
&:hover:not(:disabled) {
background: #4a4a4a;
border-color: #666;
}
&:disabled {
background: #2a2a2a;
color: #666;
cursor: not-allowed;
border-color: #333;
}
&.series-btn {
gap: 6px;
padding: 6px 12px;
background: $active-color;
border-color: $active-color;
.label {
font-size: 12px;
font-weight: 500;
}
&:hover:not(:disabled) {
background: color.adjust($active-color, $lightness: -10%);
}
&:disabled {
background: #555;
border-color: #555;
opacity: 0.5;
}
}
}
.page-info {
padding: 4px 12px;
background: rgba(255, 255, 255, 0.1);
border-radius: 4px;
font-size: 13px;
font-weight: 500;
min-width: 90px;
text-align: center;
.current {
color: $active-color;
font-weight: 600;
}
.separator {
color: $active-color;
font-weight: 600;
}
.total {
color: $text-secondary;
}
}
.page-controls {
display: flex;
align-items: center;
gap: 12px;
flex: 1;
justify-content: center;
max-width: none;
}
.slider-wrapper {
flex: 1;
display: flex;
align-items: center;
position: relative;
.page-slider {
width: 100%;
border-radius: 3px;
outline: none;
-webkit-appearance: none;
appearance: none;
background: none;
cursor: pointer;
/* ===== Track ===== */
&::-webkit-slider-runnable-track {
width: 100%;
height: 6px;
background: rgba(255, 255, 255, 0.12);
border-radius: 3px;
cursor: pointer;
}
&::-moz-range-track {
width: 100%;
height: 6px;
background: rgba(255, 255, 255, 0.12);
border-radius: 3px;
cursor: pointer;
}
&::-ms-fill-lower,
&::-ms-fill-upper {
background: rgba(255, 255, 255, 0.12);
border-radius: 3px;
}
/* ===== Thumb ===== */
&::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 18px;
height: 18px;
border-radius: 50%;
background: $active-color;
cursor: pointer;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
transition: transform $transition-fast, box-shadow $transition-fast;
margin-top: calc((6px - 18px) / 2); /* center thumb on track */
}
&::-moz-range-thumb {
width: 18px;
height: 18px;
border-radius: 50%;
background: $active-color;
cursor: pointer;
border: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
transition: transform $transition-fast, box-shadow $transition-fast;
margin-top: calc((6px - 18px) / 2);
}
&::-ms-thumb {
width: 18px;
height: 18px;
border-radius: 50%;
background: $active-color;
cursor: pointer;
border: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
}
/* ===== Tick marks ===== */
datalist {
display: flex;
justify-content: space-between;
position: absolute;
width: 100%;
left: 0;
top: 50%;
transform: translateY(-50%);
pointer-events: none;
height: 10px;
box-sizing: border-box;
option {
width: 0;
position: relative;
padding: 0;
&::before {
content: '';
position: absolute;
left: 50%;
transform: translateX(-50%);
width: 2px;
height: 10px;
background: rgba(255, 255, 255, 0.5);
top: 0;
}
}
}
}
.goto-page {
display: flex;
align-items: center;
gap: 4px;
background: rgba(51, 51, 51, 0.9);
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;
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-btn {
padding: 4px 10px;
background: $active-color;
color: white;
border: none;
border-radius: 3px;
font-size: 12px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
&:hover:not(:disabled) {
background: color.adjust($active-color, $lightness: -10%);
}
&:disabled {
background: #666;
cursor: not-allowed;
opacity: 0.6;
}
}
}
@media (max-width: 768px) {
.cbx-footer {
height: 48px;
padding: 0 8px;
gap: 8px;
justify-content: center;
}
.page-nav-left .series-btn,
.page-nav-right .series-btn {
display: none;
}
.page-nav-left {
gap: 4px;
}
.page-nav-right {
display: none;
}
.page-nav-left {
margin: 0 auto;
justify-content: center;
flex: 1;
}
.page-controls {
display: none;
}
.slider-wrapper {
display: none;
}
.goto-page-wrapper {
display: none;
}
.hide-on-mobile {
display: none !important;
}
}
@@ -0,0 +1,148 @@
import {Component, inject} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {TranslocoService, TranslocoPipe} from '@jsverse/transloco';
import {Book} from '../../../../book/model/book.model';
import {ReaderIconComponent} from '../../../ebook-reader/shared/icon.component';
import {CbxFooterService} from './cbx-footer.service';
@Component({
selector: 'app-cbx-footer',
standalone: true,
imports: [CommonModule, FormsModule, TranslocoPipe, ReaderIconComponent],
templateUrl: './cbx-footer.component.html',
styleUrls: ['./cbx-footer.component.scss']
})
export class CbxFooterComponent {
private readonly footerService = inject(CbxFooterService);
private readonly t = inject(TranslocoService);
readonly forceVisible = this.footerService.forceVisible;
readonly state = this.footerService.state;
goToPageInput: number | null = null;
get displayPage(): number {
return this.state().currentPage + 1;
}
get displaySecondPage(): number | null {
const state = this.state();
if (state.isTwoPageView && state.currentPage + 1 < state.totalPages) {
return state.currentPage + 2;
}
return null;
}
get sliderValue(): number {
return this.displayPage;
}
get canGoPrevious(): boolean {
return this.state().currentPage > 0;
}
get canGoNext(): boolean {
const state = this.state();
return state.currentPage < state.totalPages - 1;
}
get sliderTicks(): number[] {
const totalPages = this.state().totalPages;
if (totalPages <= 10) {
return Array.from({length: totalPages}, (_, i) => i + 1);
} else if (totalPages <= 20) {
return Array.from({length: totalPages}, (_, i) => i + 1);
} else if (totalPages <= 50) {
const ticks: number[] = [];
for (let i = 1; i <= totalPages; i += 2) {
ticks.push(i);
}
if (!ticks.includes(totalPages)) {
ticks.push(totalPages);
}
return ticks;
} else if (totalPages <= 100) {
const ticks: number[] = [];
const step = 5;
for (let i = 1; i <= totalPages; i += step) {
ticks.push(i);
}
if (!ticks.includes(totalPages)) {
ticks.push(totalPages);
}
return ticks;
} else {
const ticks: number[] = [];
const step = Math.ceil(totalPages / 20);
for (let i = 1; i <= totalPages; i += step) {
ticks.push(i);
}
if (!ticks.includes(totalPages)) {
ticks.push(totalPages);
}
return ticks;
}
}
onPreviousPage(): void {
this.footerService.emitPreviousPage();
}
onNextPage(): void {
this.footerService.emitNextPage();
}
onFirstPage(): void {
this.footerService.emitFirstPage();
}
onLastPage(): void {
this.footerService.emitLastPage();
}
onGoToPage(): void {
if (this.goToPageInput !== null && this.goToPageInput >= 1 && this.goToPageInput <= this.state().totalPages) {
this.footerService.emitGoToPage(this.goToPageInput);
this.goToPageInput = null;
}
}
onSliderChange(event: Event): void {
const target = event.target as HTMLInputElement;
const page = parseInt(target.value, 10);
this.footerService.emitSliderChange(page);
}
onPreviousBook(): void {
this.footerService.emitPreviousBook();
}
onNextBook(): void {
this.footerService.emitNextBook();
}
getPreviousBookTooltip(): string {
const previousBookInSeries = this.state().previousBookInSeries;
if (!previousBookInSeries) return this.t.translate('readerCbx.footer.noPreviousBook');
return this.t.translate('readerCbx.footer.previousBookTooltip', {title: this.getBookDisplayTitle(previousBookInSeries)});
}
getNextBookTooltip(): string {
const nextBookInSeries = this.state().nextBookInSeries;
if (!nextBookInSeries) return this.t.translate('readerCbx.footer.noNextBook');
return this.t.translate('readerCbx.footer.nextBookTooltip', {title: this.getBookDisplayTitle(nextBookInSeries)});
}
private getBookDisplayTitle(book: Book): string {
const parts: string[] = [];
if (book.metadata?.seriesNumber) {
parts.push(`#${book.metadata.seriesNumber}`);
}
const title = book.metadata?.title || book.fileName;
if (title) {
parts.push(title);
}
return parts.join(' - ');
}
}
@@ -0,0 +1,123 @@
import {Injectable, signal} from '@angular/core';
import {Subject} from 'rxjs';
import {Book} from '../../../../book/model/book.model';
export interface CbxFooterState {
currentPage: number;
totalPages: number;
isTwoPageView: boolean;
previousBookInSeries: Book | null;
nextBookInSeries: Book | null;
hasSeries: boolean;
}
@Injectable()
export class CbxFooterService {
private readonly defaultState: CbxFooterState = {
currentPage: 0,
totalPages: 0,
isTwoPageView: false,
previousBookInSeries: null,
nextBookInSeries: null,
hasSeries: false
};
private readonly _state = signal<CbxFooterState>(this.defaultState);
readonly state = this._state.asReadonly();
private readonly _forceVisible = signal(false);
readonly forceVisible = this._forceVisible.asReadonly();
private _previousPage = new Subject<void>();
previousPage$ = this._previousPage.asObservable();
private _nextPage = new Subject<void>();
nextPage$ = this._nextPage.asObservable();
private _goToPage = new Subject<number>();
goToPage$ = this._goToPage.asObservable();
private _firstPage = new Subject<void>();
firstPage$ = this._firstPage.asObservable();
private _lastPage = new Subject<void>();
lastPage$ = this._lastPage.asObservable();
private _previousBook = new Subject<void>();
previousBook$ = this._previousBook.asObservable();
private _nextBook = new Subject<void>();
nextBook$ = this._nextBook.asObservable();
private _sliderChange = new Subject<number>();
sliderChange$ = this._sliderChange.asObservable();
setForceVisible(visible: boolean): void {
this._forceVisible.set(visible);
}
updateState(partial: Partial<CbxFooterState>): void {
this._state.update(current => ({...current, ...partial}));
}
setCurrentPage(page: number): void {
this.updateState({currentPage: page});
}
setTotalPages(total: number): void {
this.updateState({totalPages: total});
}
setTwoPageView(isTwoPage: boolean): void {
this.updateState({isTwoPageView: isTwoPage});
}
setSeriesBooks(previous: Book | null, next: Book | null): void {
this.updateState({
previousBookInSeries: previous,
nextBookInSeries: next
});
}
setHasSeries(hasSeries: boolean): void {
this.updateState({hasSeries});
}
// Navigation actions (called from footer component)
emitPreviousPage(): void {
this._previousPage.next();
}
emitNextPage(): void {
this._nextPage.next();
}
emitGoToPage(page: number): void {
this._goToPage.next(page);
}
emitFirstPage(): void {
this._firstPage.next();
}
emitLastPage(): void {
this._lastPage.next();
}
emitPreviousBook(): void {
this._previousBook.next();
}
emitNextBook(): void {
this._nextBook.next();
}
emitSliderChange(page: number): void {
this._sliderChange.next(page);
}
reset(): void {
this._state.set(this.defaultState);
this._forceVisible.set(false);
}
}
@@ -0,0 +1,59 @@
<div class="cbx-header" [class.visible]="forceVisible()">
<div class="header-left">
<button class="icon-btn" (click)="onOpenSidebar()" [title]="'readerCbx.header.contents' | transloco">
<app-reader-icon name="menu" [size]="20" />
</button>
<button class="icon-btn" (click)="onToggleBookmark()" [title]="isCurrentPageBookmarked ? ('readerCbx.header.removeBookmark' | transloco) : ('readerCbx.header.addBookmark' | transloco)" [class.active]="isCurrentPageBookmarked">
<app-reader-icon name="bookmark" [size]="20" />
</button>
<button class="icon-btn" (click)="onOpenNoteDialog()" [title]="currentPageHasNotes ? ('readerCbx.header.pageHasNotesAddAnother' | transloco) : ('readerCbx.header.addNote' | transloco)" [class.has-notes]="currentPageHasNotes">
<app-reader-icon name="note" [size]="20" />
@if (currentPageHasNotes) {
<span class="indicator-dot"></span>
}
</button>
</div>
<span class="book-title">{{ bookTitle() }}</span>
<div class="header-right">
<button class="icon-btn desktop-only" (click)="onToggleMagnifier()" [title]="state().isMagnifierActive ? ('readerCbx.header.disableMagnifier' | transloco) : ('readerCbx.header.enableMagnifier' | transloco)" [class.active]="state().isMagnifierActive">
<app-reader-icon name="magnifier" [size]="20" />
</button>
<button class="icon-btn desktop-only" (click)="onToggleSlideshow()" [title]="state().isSlideshowActive ? ('readerCbx.header.stopSlideshow' | transloco) : ('readerCbx.header.startSlideshow' | transloco)" [class.active]="state().isSlideshowActive">
<app-reader-icon [name]="state().isSlideshowActive ? 'pause' : 'play'" [size]="20" />
</button>
<button class="icon-btn desktop-only" (click)="onToggleFullscreen()" [title]="state().isFullscreen ? ('readerCbx.header.exitFullscreen' | transloco) : ('readerCbx.header.fullscreen' | transloco)">
<app-reader-icon [name]="state().isFullscreen ? 'fullscreen-exit' : 'fullscreen'" [size]="20" />
</button>
<button class="icon-btn desktop-only" (click)="onShowShortcutsHelp()" [title]="'readerCbx.header.keyboardShortcuts' | transloco">
<app-reader-icon name="help" [size]="20" />
</button>
<div class="overflow-menu mobile-only">
<button class="icon-btn" (click)="overflowOpen = !overflowOpen; $event.stopPropagation()" [title]="'readerCbx.header.more' | transloco">
<app-reader-icon name="dots-vertical" [size]="20" />
</button>
@if (overflowOpen) {
<div class="overflow-backdrop" (click)="overflowOpen = false"></div>
<div class="overflow-dropdown">
<button class="overflow-item" (click)="onToggleSlideshow(); overflowOpen = false" [class.active]="state().isSlideshowActive">
<app-reader-icon [name]="state().isSlideshowActive ? 'pause' : 'play'" [size]="18" />
<span>{{ state().isSlideshowActive ? ('readerCbx.header.stopSlideshowLabel' | transloco) : ('readerCbx.header.startSlideshowLabel' | transloco) }}</span>
</button>
<button class="overflow-item" (click)="onToggleFullscreen(); overflowOpen = false">
<app-reader-icon [name]="state().isFullscreen ? 'fullscreen-exit' : 'fullscreen'" [size]="18" />
<span>{{ state().isFullscreen ? ('readerCbx.header.exitFullscreenLabel' | transloco) : ('readerCbx.header.fullscreenLabel' | transloco) }}</span>
</button>
<button class="overflow-item" (click)="onShowShortcutsHelp(); overflowOpen = false">
<app-reader-icon name="help" [size]="18" />
<span>{{ 'readerCbx.header.keyboardShortcutsLabel' | transloco }}</span>
</button>
</div>
}
</div>
<button class="icon-btn" (click)="onOpenSettings()" [title]="'readerCbx.header.settings' | transloco">
<app-reader-icon name="settings" [size]="20" />
</button>
<button class="icon-btn close-btn" (click)="onClose(); $event.stopPropagation()" [title]="'readerCbx.header.closeReader' | transloco">
<app-reader-icon name="close" [size]="20" />
</button>
</div>
</div>
@@ -0,0 +1,187 @@
.cbx-header {
position: absolute;
top: 0;
left: 0;
right: 0;
height: 38px;
padding: 0 12px;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 14px;
z-index: 1000;
background: linear-gradient(135deg, #2d2d2d 0%, #1f1f1f 100%);
border-bottom: 1px solid #404040;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
color: #ffffff;
opacity: 1;
pointer-events: auto;
transform: translateY(0);
transition: opacity 0.25s ease-out, transform 0.25s ease-out;
&:not(.visible) {
opacity: 0;
pointer-events: none;
transform: translateY(-100%);
}
.header-left,
.header-right {
display: flex;
align-items: center;
z-index: 1;
}
.icon-btn {
background: none;
border: none;
color: inherit;
cursor: pointer;
padding: 8px;
border-radius: 6px;
transition: background 0.15s, box-shadow 0.15s;
display: flex;
align-items: center;
justify-content: center;
margin-right: 8px;
.icon {
font-size: 18px;
line-height: 1;
}
&:hover {
background: rgba(255, 255, 255, 0.12);
}
&:last-child {
margin-right: 0;
}
&.close-btn {
.icon {
font-size: 22px;
font-weight: bold;
}
&:hover {
background: rgba(239, 68, 68, 0.2);
}
}
&.active {
color: #ef4444;
background: rgba(239, 68, 68, 0.15);
}
&.has-notes {
color: #ffc107;
position: relative;
}
.indicator-dot {
position: absolute;
top: 4px;
right: 4px;
width: 8px;
height: 8px;
background: #ffc107;
border-radius: 50%;
border: 1px solid #1f1f1f;
}
}
.book-title {
flex: 1;
min-width: 0;
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;
}
.mobile-only {
display: none;
}
.overflow-menu {
position: relative;
}
.overflow-backdrop {
position: fixed;
inset: 0;
z-index: 999;
}
.overflow-dropdown {
position: absolute;
top: 100%;
right: 0;
margin-top: 4px;
background: #2d2d2d;
border: 1px solid #404040;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
z-index: 1000;
min-width: 180px;
padding: 4px;
}
.overflow-item {
display: flex;
align-items: center;
gap: 10px;
width: 100%;
padding: 8px 12px;
background: none;
border: none;
color: #ffffff;
font-size: 13px;
cursor: pointer;
border-radius: 6px;
white-space: nowrap;
&:hover {
background: rgba(255, 255, 255, 0.12);
}
&.active {
color: #ef4444;
background: rgba(239, 68, 68, 0.15);
}
}
}
@media (max-width: 600px) {
.cbx-header {
padding: 0 4px;
.icon-btn {
padding: 5px;
margin-right: 6px;
app-reader-icon {
transform: scale(0.9);
}
}
.book-title {
font-size: 12px;
}
.desktop-only {
display: none;
}
.mobile-only {
display: block;
}
}
}
@@ -0,0 +1,61 @@
import {Component, inject, Input} from '@angular/core';
import {TranslocoPipe} from '@jsverse/transloco';
import {CbxHeaderService} from './cbx-header.service';
import {ReaderIconComponent} from '../../../ebook-reader';
import {CommonModule} from '@angular/common';
@Component({
selector: 'app-cbx-header',
standalone: true,
imports: [CommonModule, TranslocoPipe, ReaderIconComponent],
templateUrl: './cbx-header.component.html',
styleUrls: ['./cbx-header.component.scss']
})
export class CbxHeaderComponent {
private readonly headerService = inject(CbxHeaderService);
@Input() isCurrentPageBookmarked = false;
@Input() currentPageHasNotes = false;
readonly forceVisible = this.headerService.forceVisible;
readonly state = this.headerService.state;
readonly bookTitle = this.headerService.bookTitle;
overflowOpen = false;
onOpenSidebar(): void {
this.headerService.openSidebar();
}
onOpenSettings(): void {
this.headerService.openQuickSettings();
}
onToggleBookmark(): void {
this.headerService.toggleBookmark();
}
onOpenNoteDialog(): void {
this.headerService.openNoteDialog();
}
onToggleFullscreen(): void {
this.headerService.toggleFullscreen();
}
onToggleSlideshow(): void {
this.headerService.toggleSlideshow();
}
onToggleMagnifier(): void {
this.headerService.toggleMagnifier();
}
onShowShortcutsHelp(): void {
this.headerService.showShortcutsHelp();
}
onClose(): void {
this.headerService.close();
}
}
@@ -0,0 +1,106 @@
import {inject, Injectable, signal} from '@angular/core';
import {Location} from '@angular/common';
import {Subject} from 'rxjs';
import {CbxSidebarService} from '../sidebar/cbx-sidebar.service';
export interface CbxHeaderState {
isFullscreen: boolean;
isSlideshowActive: boolean;
isMagnifierActive: boolean;
}
@Injectable()
export class CbxHeaderService {
private readonly defaultState: CbxHeaderState = {
isFullscreen: false,
isSlideshowActive: false,
isMagnifierActive: false
};
private sidebarService = inject(CbxSidebarService);
private location = inject(Location);
private readonly _bookTitle = signal('');
readonly bookTitle = this._bookTitle.asReadonly();
private readonly _forceVisible = signal(true);
readonly forceVisible = this._forceVisible.asReadonly();
private readonly _state = signal<CbxHeaderState>(this.defaultState);
readonly state = this._state.asReadonly();
private _showQuickSettings = new Subject<void>();
showQuickSettings$ = this._showQuickSettings.asObservable();
private _toggleBookmark = new Subject<void>();
toggleBookmark$ = this._toggleBookmark.asObservable();
private _openNoteDialog = new Subject<void>();
openNoteDialog$ = this._openNoteDialog.asObservable();
private _toggleFullscreen = new Subject<void>();
toggleFullscreen$ = this._toggleFullscreen.asObservable();
private _toggleSlideshow = new Subject<void>();
toggleSlideshow$ = this._toggleSlideshow.asObservable();
private _toggleMagnifier = new Subject<void>();
toggleMagnifier$ = this._toggleMagnifier.asObservable();
private _showShortcutsHelp = new Subject<void>();
showShortcutsHelp$ = this._showShortcutsHelp.asObservable();
initialize(title: string | undefined): void {
this._bookTitle.set(title || '');
}
setForceVisible(visible: boolean): void {
this._forceVisible.set(visible);
}
updateState(partial: Partial<CbxHeaderState>): void {
this._state.update(current => ({...current, ...partial}));
}
openSidebar(): void {
this.sidebarService.open();
}
openQuickSettings(): void {
this._showQuickSettings.next();
}
toggleBookmark(): void {
this._toggleBookmark.next();
}
openNoteDialog(): void {
this._openNoteDialog.next();
}
toggleFullscreen(): void {
this._toggleFullscreen.next();
}
toggleSlideshow(): void {
this._toggleSlideshow.next();
}
toggleMagnifier(): void {
this._toggleMagnifier.next();
}
showShortcutsHelp(): void {
this._showShortcutsHelp.next();
}
close(): void {
this.location.back();
}
reset(): void {
this._forceVisible.set(true);
this._state.set(this.defaultState);
this._bookTitle.set('');
}
}
@@ -0,0 +1,151 @@
<div class="quick-settings-overlay" (click)="onOverlayClick()">
<div class="quick-settings-panel" (click)="$event.stopPropagation()">
<div class="pointer"></div>
<div class="panel-body">
<!-- Fit Mode -->
<div class="control">
<label>{{ 'readerCbx.quickSettings.fitMode' | transloco }}</label>
<div class="control-right">
<div class="button-group">
@for (option of fitModeOptions; track option.value) {
<button
class="option-btn"
[class.active]="state().fitMode === option.value"
(click)="onFitModeSelect(option.value)"
[title]="option.label">
<app-reader-icon [name]="option.icon" [size]="16" />
</button>
}
</div>
</div>
</div>
<!-- Scroll Mode -->
<div class="control">
<label>{{ 'readerCbx.quickSettings.scrollMode' | transloco }}</label>
<div class="control-right">
<div class="button-group text-btns">
@for (option of scrollModeOptions; track option.value) {
<button
class="option-btn text-btn"
[class.active]="state().scrollMode === option.value"
(click)="onScrollModeSelect(option.value)"
[title]="option.label">
{{ option.label }}
</button>
}
</div>
</div>
</div>
<!-- Page View (only in paginated mode) -->
@if (isPaginated && !isPhonePortrait) {
<div class="control">
<label>{{ 'readerCbx.quickSettings.pageView' | transloco }}</label>
<div class="control-right">
<span class="mode-label">{{ isTwoPageView ? ('readerCbx.quickSettings.twoPage' | transloco) : ('readerCbx.quickSettings.single' | transloco) }}</span>
<button class="switch" [class.active]="isTwoPageView" (click)="onPageViewToggle()">
<span class="slider"></span>
</button>
</div>
</div>
}
<!-- Page Spread (only in two-page mode) -->
@if (isPaginated && isTwoPageView) {
<div class="control">
<label>{{ 'readerCbx.quickSettings.pageSpread' | transloco }}</label>
<div class="control-right">
<span class="mode-label">{{ state().pageSpread === CbxPageSpread.ODD ? ('readerCbx.quickSettings.oddFirst' | transloco) : ('readerCbx.quickSettings.evenFirst' | transloco) }}</span>
<button class="switch" [class.active]="state().pageSpread === CbxPageSpread.EVEN" (click)="onPageSpreadToggle()">
<span class="slider"></span>
</button>
</div>
</div>
}
<!-- Reading Direction -->
<div class="control">
<label>{{ 'readerCbx.quickSettings.readingDirection' | transloco }}</label>
<div class="control-right">
<span class="mode-label">{{ state().readingDirection === CbxReadingDirection.LTR ? ('readerCbx.quickSettings.leftToRight' | transloco) : ('readerCbx.quickSettings.rightToLeft' | transloco) }}</span>
<button class="switch" [class.active]="state().readingDirection === CbxReadingDirection.RTL" (click)="onReadingDirectionToggle()">
<span class="slider"></span>
</button>
</div>
</div>
<!-- Slideshow Interval -->
<div class="control">
<label>{{ 'readerCbx.quickSettings.slideshowInterval' | transloco }}</label>
<div class="control-right">
<div class="button-group text-btns">
@for (option of slideshowIntervalOptions; track option.value) {
<button
class="option-btn text-btn small"
[class.active]="state().slideshowInterval === option.value"
(click)="onSlideshowIntervalSelect(option.value)"
[title]="option.label">
{{ option.label }}
</button>
}
</div>
</div>
</div>
<!-- Background Color -->
<div class="control">
<label>{{ 'readerCbx.quickSettings.background' | transloco }}</label>
<div class="control-right">
<div class="button-group">
@for (option of backgroundOptions; track option.value) {
<button
class="option-btn color-btn"
[class.active]="state().backgroundColor === option.value"
(click)="onBackgroundSelect(option.value)"
[title]="option.label">
<span class="color-swatch" [style.background]="option.color"></span>
</button>
}
</div>
</div>
</div>
<!-- Magnifier Lens Size -->
<div class="control">
<label>{{ 'readerCbx.quickSettings.magnifierLensSize' | transloco }}</label>
<div class="control-right">
<div class="button-group text-btns">
@for (option of magnifierLensSizeOptions; track option.value) {
<button
class="option-btn text-btn small"
[class.active]="state().magnifierLensSize === option.value"
(click)="onMagnifierLensSizeSelect(option.value)"
[title]="option.label">
{{ option.label }}
</button>
}
</div>
</div>
</div>
<!-- Magnifier Zoom -->
<div class="control">
<label>{{ 'readerCbx.quickSettings.magnifierZoom' | transloco }}</label>
<div class="control-right">
<div class="button-group text-btns">
@for (option of magnifierZoomOptions; track option.value) {
<button
class="option-btn text-btn small"
[class.active]="state().magnifierZoom === option.value"
(click)="onMagnifierZoomSelect(option.value)"
[title]="option.label">
{{ option.label }}
</button>
}
</div>
</div>
</div>
</div>
</div>
</div>
@@ -0,0 +1,222 @@
@use 'sass:color';
// Variables
$panel-bg: #1a1a1a;
$text-primary: rgba(255, 255, 255, 0.95);
$text-secondary: rgba(255, 255, 255, 0.6);
$text-muted: rgba(255, 255, 255, 0.4);
$border-color: rgba(255, 255, 255, 0.08);
$hover-bg: rgba(255, 255, 255, 0.08);
$active-color: #4a90e2;
$active-bg: rgba(74, 144, 226, 0.15);
$transition-fast: 150ms ease;
$transition-normal: 200ms ease;
.quick-settings-overlay {
position: fixed;
inset: 0;
z-index: 12000;
background: rgba(0, 0, 0, 0.3);
animation: fadeIn $transition-normal;
cursor: pointer;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.quick-settings-panel {
position: absolute;
top: 52px;
right: 60px;
width: 340px;
background: $panel-bg;
border: 1px solid $border-color;
border-radius: 12px;
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.5);
animation: slideDown 200ms cubic-bezier(0.4, 0, 0.2, 1);
overflow: visible;
cursor: default;
}
@keyframes slideDown {
from {
transform: translateY(-8px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
// Pointer arrow
.pointer {
position: absolute;
top: -8px;
right: 18px;
width: 16px;
height: 16px;
background: $panel-bg;
border-left: 1px solid $border-color;
border-top: 1px solid $border-color;
transform: rotate(45deg);
border-radius: 3px 0 0 0;
}
.panel-body {
padding: 16px;
}
.control {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 0;
&:not(:last-child) {
border-bottom: 1px solid $border-color;
}
> label {
color: $text-primary;
font-size: 13px;
font-weight: 500;
flex-shrink: 0;
}
}
.control-right {
display: flex;
align-items: center;
gap: 10px;
}
.mode-label {
font-size: 12px;
color: $text-secondary;
min-width: 60px;
text-align: right;
}
// Toggle switch
.switch {
position: relative;
width: 40px;
height: 22px;
background: rgba(255, 255, 255, 0.15);
border: none;
border-radius: 11px;
cursor: pointer;
transition: background 300ms ease;
padding: 0;
&.active {
background: $active-color;
.slider {
transform: translateX(18px);
}
}
.slider {
position: absolute;
top: 2px;
left: 2px;
width: 18px;
height: 18px;
background: #ffffff;
border-radius: 50%;
transition: transform 300ms ease;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
&:hover {
background: rgba(255, 255, 255, 0.2);
&.active {
background: color.adjust($active-color, $lightness: 5%);
}
}
}
// Button group
.button-group {
display: flex;
gap: 4px;
background: rgba(255, 255, 255, 0.03);
padding: 3px;
border-radius: 6px;
border: 1px solid $border-color;
}
.option-btn {
width: 32px;
height: 28px;
background: transparent;
color: $text-secondary;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
display: flex;
align-items: center;
justify-content: center;
transition: all $transition-fast;
&:hover {
background: $hover-bg;
color: $text-primary;
}
&.active {
background: $active-color;
color: white;
}
&.text-btn {
width: auto;
padding: 0 10px;
font-size: 11px;
font-weight: 500;
&.small {
padding: 0 6px;
font-size: 10px;
}
}
&.color-btn {
padding: 4px;
&.active {
background: transparent;
box-shadow: 0 0 0 2px $active-color;
}
}
.color-swatch {
width: 20px;
height: 20px;
border-radius: 50%;
border: 1px solid rgba(255, 255, 255, 0.3);
}
}
.text-btns {
flex-wrap: wrap;
}
@media (max-width: 600px) {
.quick-settings-panel {
right: 16px;
left: 16px;
width: auto;
top: 56px;
}
.pointer {
right: 30px;
}
}
@@ -0,0 +1,162 @@
import {Component, inject} from '@angular/core';
import {CommonModule} from '@angular/common';
import {TranslocoService, TranslocoPipe} from '@jsverse/transloco';
import {
CbxFitMode,
CbxScrollMode,
CbxPageViewMode,
CbxPageSpread,
CbxBackgroundColor,
CbxReadingDirection,
CbxSlideshowInterval,
CbxMagnifierZoom,
CbxMagnifierLensSize
} from '../../../../settings/user-management/user.service';
import {ReaderIconComponent, ReaderIconName} from '../../../ebook-reader/shared/icon.component';
import {CbxQuickSettingsService} from './cbx-quick-settings.service';
@Component({
selector: 'app-cbx-quick-settings',
standalone: true,
imports: [CommonModule, TranslocoPipe, ReaderIconComponent],
templateUrl: './cbx-quick-settings.component.html',
styleUrls: ['./cbx-quick-settings.component.scss']
})
export class CbxQuickSettingsComponent {
private readonly quickSettingsService = inject(CbxQuickSettingsService);
private readonly t = inject(TranslocoService);
readonly state = this.quickSettingsService.state;
protected readonly CbxFitMode = CbxFitMode;
protected readonly CbxScrollMode = CbxScrollMode;
protected readonly CbxPageViewMode = CbxPageViewMode;
protected readonly CbxPageSpread = CbxPageSpread;
protected readonly CbxBackgroundColor = CbxBackgroundColor;
protected readonly CbxReadingDirection = CbxReadingDirection;
protected readonly CbxSlideshowInterval = CbxSlideshowInterval;
protected readonly CbxMagnifierZoom = CbxMagnifierZoom;
protected readonly CbxMagnifierLensSize = CbxMagnifierLensSize;
get fitModeOptions(): {value: CbxFitMode, label: string, icon: ReaderIconName}[] {
return [
{value: CbxFitMode.FIT_PAGE, label: this.t.translate('readerCbx.quickSettings.fitPage'), icon: 'fit-page'},
{value: CbxFitMode.FIT_WIDTH, label: this.t.translate('readerCbx.quickSettings.fitWidth'), icon: 'fit-width'},
{value: CbxFitMode.FIT_HEIGHT, label: this.t.translate('readerCbx.quickSettings.fitHeight'), icon: 'fit-height'},
{value: CbxFitMode.ACTUAL_SIZE, label: this.t.translate('readerCbx.quickSettings.actualSize'), icon: 'actual-size'},
{value: CbxFitMode.AUTO, label: this.t.translate('readerCbx.quickSettings.automatic'), icon: 'auto-fit'}
];
}
get scrollModeOptions(): {value: CbxScrollMode, label: string}[] {
return [
{value: CbxScrollMode.PAGINATED, label: this.t.translate('readerCbx.quickSettings.paginated')},
{value: CbxScrollMode.INFINITE, label: this.t.translate('readerCbx.quickSettings.infinite')},
{value: CbxScrollMode.LONG_STRIP, label: this.t.translate('readerCbx.quickSettings.longStrip')}
];
}
slideshowIntervalOptions: {value: CbxSlideshowInterval, label: string}[] = [
{value: CbxSlideshowInterval.THREE_SECONDS, label: '3s'},
{value: CbxSlideshowInterval.FIVE_SECONDS, label: '5s'},
{value: CbxSlideshowInterval.TEN_SECONDS, label: '10s'},
{value: CbxSlideshowInterval.FIFTEEN_SECONDS, label: '15s'},
{value: CbxSlideshowInterval.THIRTY_SECONDS, label: '30s'}
];
magnifierZoomOptions: {value: CbxMagnifierZoom, label: string}[] = [
{value: CbxMagnifierZoom.ZOOM_1_5X, label: '1.5×'},
{value: CbxMagnifierZoom.ZOOM_2X, label: '2×'},
{value: CbxMagnifierZoom.ZOOM_2_5X, label: '2.5×'},
{value: CbxMagnifierZoom.ZOOM_3X, label: '3×'},
{value: CbxMagnifierZoom.ZOOM_4X, label: '4×'}
];
magnifierLensSizeOptions: {value: CbxMagnifierLensSize, label: string}[] = [
{value: CbxMagnifierLensSize.SMALL, label: 'S'},
{value: CbxMagnifierLensSize.MEDIUM, label: 'M'},
{value: CbxMagnifierLensSize.LARGE, label: 'L'},
{value: CbxMagnifierLensSize.EXTRA_LARGE, label: 'XL'}
];
get backgroundOptions() {
return [
{value: CbxBackgroundColor.BLACK, label: this.t.translate('readerCbx.quickSettings.black'), color: '#000000'},
{value: CbxBackgroundColor.GRAY, label: this.t.translate('readerCbx.quickSettings.gray'), color: '#808080'},
{value: CbxBackgroundColor.WHITE, label: this.t.translate('readerCbx.quickSettings.white'), color: '#ffffff'}
];
}
get isTwoPageView(): boolean {
return this.state().pageViewMode === CbxPageViewMode.TWO_PAGE;
}
get isPaginated(): boolean {
return this.state().scrollMode === CbxScrollMode.PAGINATED;
}
get isLongStrip(): boolean {
return this.state().scrollMode === CbxScrollMode.LONG_STRIP;
}
get isPhonePortrait(): boolean {
return window.innerWidth < 768 && window.innerHeight > window.innerWidth;
}
get currentScrollModeLabel(): string {
return this.scrollModeOptions.find(o => o.value === this.state().scrollMode)?.label || this.t.translate('readerCbx.quickSettings.paginated');
}
get currentSlideshowIntervalLabel(): string {
return this.slideshowIntervalOptions.find(o => o.value === this.state().slideshowInterval)?.label || '5s';
}
onFitModeSelect(mode: CbxFitMode): void {
this.quickSettingsService.emitFitModeChange(mode);
}
onScrollModeSelect(mode: CbxScrollMode): void {
this.quickSettingsService.emitScrollModeChange(mode);
}
onPageViewToggle(): void {
const newMode = this.state().pageViewMode === CbxPageViewMode.SINGLE_PAGE
? CbxPageViewMode.TWO_PAGE
: CbxPageViewMode.SINGLE_PAGE;
this.quickSettingsService.emitPageViewModeChange(newMode);
}
onPageSpreadToggle(): void {
const newSpread = this.state().pageSpread === CbxPageSpread.ODD
? CbxPageSpread.EVEN
: CbxPageSpread.ODD;
this.quickSettingsService.emitPageSpreadChange(newSpread);
}
onBackgroundSelect(color: CbxBackgroundColor): void {
this.quickSettingsService.emitBackgroundColorChange(color);
}
onReadingDirectionToggle(): void {
const newDirection = this.state().readingDirection === CbxReadingDirection.LTR
? CbxReadingDirection.RTL
: CbxReadingDirection.LTR;
this.quickSettingsService.emitReadingDirectionChange(newDirection);
}
onSlideshowIntervalSelect(interval: CbxSlideshowInterval): void {
this.quickSettingsService.emitSlideshowIntervalChange(interval);
}
onMagnifierZoomSelect(zoom: CbxMagnifierZoom): void {
this.quickSettingsService.emitMagnifierZoomChange(zoom);
}
onMagnifierLensSizeSelect(size: CbxMagnifierLensSize): void {
this.quickSettingsService.emitMagnifierLensSizeChange(size);
}
onOverlayClick(): void {
this.quickSettingsService.close();
}
}
@@ -0,0 +1,153 @@
import {Injectable, signal} from '@angular/core';
import {Subject} from 'rxjs';
import {CbxBackgroundColor, CbxFitMode, CbxMagnifierLensSize, CbxMagnifierZoom, CbxPageSpread, CbxPageViewMode, CbxScrollMode, CbxReadingDirection, CbxSlideshowInterval} from '../../../../settings/user-management/user.service';
export interface CbxQuickSettingsState {
fitMode: CbxFitMode;
scrollMode: CbxScrollMode;
pageViewMode: CbxPageViewMode;
pageSpread: CbxPageSpread;
backgroundColor: CbxBackgroundColor;
readingDirection: CbxReadingDirection;
slideshowInterval: CbxSlideshowInterval;
magnifierZoom: CbxMagnifierZoom;
magnifierLensSize: CbxMagnifierLensSize;
}
@Injectable()
export class CbxQuickSettingsService {
private readonly defaultState: CbxQuickSettingsState = {
fitMode: CbxFitMode.FIT_PAGE,
scrollMode: CbxScrollMode.PAGINATED,
pageViewMode: CbxPageViewMode.SINGLE_PAGE,
pageSpread: CbxPageSpread.ODD,
backgroundColor: CbxBackgroundColor.GRAY,
readingDirection: CbxReadingDirection.LTR,
slideshowInterval: CbxSlideshowInterval.FIVE_SECONDS,
magnifierZoom: CbxMagnifierZoom.ZOOM_3X,
magnifierLensSize: CbxMagnifierLensSize.MEDIUM
};
private readonly _state = signal<CbxQuickSettingsState>(this.defaultState);
readonly state = this._state.asReadonly();
private readonly _visible = signal(false);
readonly visible = this._visible.asReadonly();
private _fitModeChange = new Subject<CbxFitMode>();
fitModeChange$ = this._fitModeChange.asObservable();
private _scrollModeChange = new Subject<CbxScrollMode>();
scrollModeChange$ = this._scrollModeChange.asObservable();
private _pageViewModeChange = new Subject<CbxPageViewMode>();
pageViewModeChange$ = this._pageViewModeChange.asObservable();
private _pageSpreadChange = new Subject<CbxPageSpread>();
pageSpreadChange$ = this._pageSpreadChange.asObservable();
private _backgroundColorChange = new Subject<CbxBackgroundColor>();
backgroundColorChange$ = this._backgroundColorChange.asObservable();
private _readingDirectionChange = new Subject<CbxReadingDirection>();
readingDirectionChange$ = this._readingDirectionChange.asObservable();
private _slideshowIntervalChange = new Subject<CbxSlideshowInterval>();
slideshowIntervalChange$ = this._slideshowIntervalChange.asObservable();
private _magnifierZoomChange = new Subject<CbxMagnifierZoom>();
magnifierZoomChange$ = this._magnifierZoomChange.asObservable();
private _magnifierLensSizeChange = new Subject<CbxMagnifierLensSize>();
magnifierLensSizeChange$ = this._magnifierLensSizeChange.asObservable();
show(): void {
this._visible.set(true);
}
close(): void {
this._visible.set(false);
}
updateState(partial: Partial<CbxQuickSettingsState>): void {
this._state.update(current => ({...current, ...partial}));
}
setFitMode(mode: CbxFitMode): void {
this.updateState({fitMode: mode});
}
setScrollMode(mode: CbxScrollMode): void {
this.updateState({scrollMode: mode});
}
setPageViewMode(mode: CbxPageViewMode): void {
this.updateState({pageViewMode: mode});
}
setPageSpread(spread: CbxPageSpread): void {
this.updateState({pageSpread: spread});
}
setBackgroundColor(color: CbxBackgroundColor): void {
this.updateState({backgroundColor: color});
}
setReadingDirection(direction: CbxReadingDirection): void {
this.updateState({readingDirection: direction});
}
setSlideshowInterval(interval: CbxSlideshowInterval): void {
this.updateState({slideshowInterval: interval});
}
setMagnifierZoom(zoom: CbxMagnifierZoom): void {
this.updateState({magnifierZoom: zoom});
}
setMagnifierLensSize(size: CbxMagnifierLensSize): void {
this.updateState({magnifierLensSize: size});
}
// Actions emitted from component
emitFitModeChange(mode: CbxFitMode): void {
this._fitModeChange.next(mode);
}
emitScrollModeChange(mode: CbxScrollMode): void {
this._scrollModeChange.next(mode);
}
emitPageViewModeChange(mode: CbxPageViewMode): void {
this._pageViewModeChange.next(mode);
}
emitPageSpreadChange(spread: CbxPageSpread): void {
this._pageSpreadChange.next(spread);
}
emitBackgroundColorChange(color: CbxBackgroundColor): void {
this._backgroundColorChange.next(color);
}
emitReadingDirectionChange(direction: CbxReadingDirection): void {
this._readingDirectionChange.next(direction);
}
emitSlideshowIntervalChange(interval: CbxSlideshowInterval): void {
this._slideshowIntervalChange.next(interval);
}
emitMagnifierZoomChange(zoom: CbxMagnifierZoom): void {
this._magnifierZoomChange.next(zoom);
}
emitMagnifierLensSizeChange(size: CbxMagnifierLensSize): void {
this._magnifierLensSizeChange.next(size);
}
reset(): void {
this._state.set(this.defaultState);
this._visible.set(false);
}
}
@@ -0,0 +1,158 @@
@if (isOpen()) {
<div class="sidebar-overlay" (click)="onOverlayClick()" [class.closing]="closing()">
<aside class="sidebar" (click)="$event.stopPropagation()" [class.closing]="closing()">
<header class="sidebar-header">
@if (bookInfo().coverUrl) {
<img
[src]="bookInfo().coverUrl"
alt="Book cover"
class="book-cover"
/>
}
<div class="book-meta">
<h2 class="book-title">{{ bookInfo().title }}</h2>
@if (bookInfo().authors) {
<p class="book-authors">{{ bookInfo().authors }}</p>
}
</div>
</header>
<nav class="tabs">
<button
class="tab"
[class.active]="activeTab() === 'pages'"
(click)="setActiveTab('pages')">
<app-reader-icon name="book" class="tab-icon"></app-reader-icon>
<span>{{ 'readerCbx.sidebar.contentTab' | transloco }}</span>
</button>
<button
class="tab"
[class.active]="activeTab() === 'bookmarks'"
(click)="setActiveTab('bookmarks')">
<app-reader-icon name="bookmark" class="tab-icon"></app-reader-icon>
<span>{{ 'readerCbx.sidebar.bookmarksTab' | transloco }}</span>
@if (bookmarks().length > 0) {
<span class="badge">{{ bookmarks().length }}</span>
}
</button>
<button
class="tab"
[class.active]="activeTab() === 'notes'"
(click)="setActiveTab('notes')">
<app-reader-icon name="note" class="tab-icon"></app-reader-icon>
<span>{{ 'readerCbx.sidebar.notesTab' | transloco }}</span>
@if (notes().length > 0) {
<span class="badge">{{ notes().length }}</span>
}
</button>
</nav>
<div class="content">
@switch (activeTab()) {
@case ('pages') {
<ul class="page-list">
@for (page of pages(); track page.pageNumber) {
<li>
<button
class="page-row"
[class.active]="isPageActive(page.pageNumber)"
(click)="onPageClick(page.pageNumber)">
<span class="page-number">{{ page.pageNumber }}</span>
<span class="page-label">{{ page.displayName }}</span>
</button>
</li>
}
</ul>
@if (pages().length === 0) {
<div class="empty-state">
<app-reader-icon name="book" class="empty-icon" [size]="48" [strokeWidth]="1.5"></app-reader-icon>
<p>{{ 'readerCbx.sidebar.noPagesFound' | transloco }}</p>
</div>
}
}
@case ('bookmarks') {
@if (bookmarks().length > 0) {
<ul class="item-list">
@for (bookmark of bookmarks(); track bookmark.id) {
<li class="list-item" (click)="onBookmarkClick(bookmark.cfi!)">
<div class="item-content">
<span class="item-title">{{ bookmark.title }}</span>
<span class="item-meta">{{ bookmark.createdAt | date: 'MMM d, y' }}</span>
</div>
<button class="delete-btn" (click)="onDeleteBookmark($event, bookmark.id)" [attr.aria-label]="'readerCbx.sidebar.deleteBookmark' | transloco">
<app-reader-icon name="trash" [size]="16"></app-reader-icon>
</button>
</li>
}
</ul>
} @else {
<div class="empty-state">
<app-reader-icon name="bookmark" class="empty-icon" [size]="48" [strokeWidth]="1.5"></app-reader-icon>
<p>{{ 'readerCbx.sidebar.noBookmarksYet' | transloco }}</p>
<span class="empty-hint">{{ 'readerCbx.sidebar.bookmarkHint' | transloco }}</span>
</div>
}
}
@case ('notes') {
<div class="notes-container">
@if (notes().length > 0) {
<div class="notes-search-wrapper">
<app-reader-icon name="search" class="search-icon" [size]="16"></app-reader-icon>
<input
type="text"
class="search-input"
[placeholder]="'readerCbx.sidebar.searchNotesPlaceholder' | transloco"
[ngModel]="notesSearchQuery()"
(ngModelChange)="onNotesSearchInput($event)"
/>
@if (notesSearchQuery()) {
<button class="clear-btn" (click)="clearNotesSearch()" [attr.aria-label]="'readerCbx.sidebar.clearSearch' | transloco">
<app-reader-icon name="close" [size]="14"></app-reader-icon>
</button>
}
</div>
}
@if (filteredNotes().length > 0) {
<ul class="item-list">
@for (note of filteredNotes(); track note.id) {
<li class="list-item note-item" (click)="onNoteClick(note.cfi)">
<div class="note-bar" [style.background-color]="note.color"></div>
<div class="item-content">
<span class="note-text">{{ note.noteContent }}</span>
@if (note.chapterTitle) {
<span class="item-chapter">{{ note.chapterTitle }}</span>
}
<span class="item-meta">{{ note.createdAt | date: 'MMM d, y' }}</span>
</div>
<div class="action-buttons">
<button class="edit-btn" (click)="onEditNote($event, note)" [attr.aria-label]="'readerCbx.sidebar.editNote' | transloco">
<app-reader-icon name="edit" [size]="16"></app-reader-icon>
</button>
<button class="delete-btn" (click)="onDeleteNote($event, note.id)" [attr.aria-label]="'readerCbx.sidebar.deleteNote' | transloco">
<app-reader-icon name="trash" [size]="16"></app-reader-icon>
</button>
</div>
</li>
}
</ul>
} @else if (notes().length > 0 && notesSearchQuery()) {
<div class="empty-state">
<app-reader-icon name="search" class="empty-icon" [size]="48" [strokeWidth]="1.5"></app-reader-icon>
<p>{{ 'readerCbx.sidebar.noMatchingNotes' | transloco }}</p>
<span class="empty-hint">{{ 'readerCbx.sidebar.tryDifferentSearch' | transloco }}</span>
</div>
} @else {
<div class="empty-state">
<app-reader-icon name="note" class="empty-icon" [size]="48" [strokeWidth]="1.5"></app-reader-icon>
<p>{{ 'readerCbx.sidebar.noNotesYet' | transloco }}</p>
<span class="empty-hint">{{ 'readerCbx.sidebar.notesHint' | transloco }}</span>
</div>
}
</div>
}
}
</div>
</aside>
</div>
}
@@ -0,0 +1,541 @@
// Variables
$sidebar-width: 300px;
$sidebar-bg: #1a1a1a;
$text-primary: rgba(255, 255, 255, 0.95);
$text-secondary: rgba(255, 255, 255, 0.6);
$text-muted: rgba(255, 255, 255, 0.4);
$border-color: rgba(255, 255, 255, 0.08);
$hover-bg: rgba(255, 255, 255, 0.06);
$active-bg: rgba(74, 144, 226, 0.15);
$active-color: #4a90e2;
$transition-fast: 150ms ease;
$transition-normal: 200ms ease;
// Overlay
.sidebar-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.4);
backdrop-filter: blur(2px);
z-index: 12000;
animation: fadeIn $transition-normal;
&.closing {
animation: fadeOut $transition-normal forwards;
}
}
// Sidebar container
.sidebar {
position: fixed;
top: 0;
left: 0;
bottom: 0;
width: $sidebar-width;
background: $sidebar-bg;
display: flex;
flex-direction: column;
color: $text-primary;
box-shadow: 4px 0 24px rgba(0, 0, 0, 0.3);
animation: slideIn 250ms cubic-bezier(0.4, 0, 0.2, 1);
z-index: 12001;
&.closing {
animation: slideOut 200ms cubic-bezier(0.4, 0, 0.2, 1) forwards;
}
}
// Header
.sidebar-header {
display: flex;
gap: 14px;
padding: 20px 16px;
border-bottom: 1px solid $border-color;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.03) 0%, transparent 100%);
}
.book-cover {
width: 60px;
height: 90px;
object-fit: cover;
border-radius: 4px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
flex-shrink: 0;
}
.book-meta {
display: flex;
flex-direction: column;
justify-content: center;
min-width: 0;
gap: 6px;
}
.book-title {
font-size: 14px;
font-weight: 600;
line-height: 1.3;
margin: 0;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
}
.book-authors {
font-size: 12px;
color: $text-secondary;
margin: 0;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 1;
overflow: hidden;
}
// Tabs
.tabs {
display: flex;
border-bottom: 1px solid $border-color;
background: rgba(0, 0, 0, 0.2);
}
.tab {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
padding: 12px 8px;
background: none;
border: none;
color: $text-secondary;
font-size: 11px;
font-weight: 500;
cursor: pointer;
transition: color $transition-fast, background $transition-fast;
position: relative;
&:hover {
color: $text-primary;
background: $hover-bg;
}
&.active {
color: $active-color;
&::after {
content: '';
position: absolute;
bottom: 0;
left: 16px;
right: 16px;
height: 2px;
background: $active-color;
border-radius: 1px 1px 0 0;
}
}
}
.tab-icon {
width: 18px;
height: 18px;
}
.badge {
position: absolute;
top: 6px;
right: calc(50% - 20px);
min-width: 16px;
height: 16px;
padding: 0 4px;
background: $active-color;
color: white;
font-size: 10px;
font-weight: 600;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
}
// Content area
.content {
flex: 1;
overflow-y: auto;
overscroll-behavior: contain;
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.15);
border-radius: 3px;
&:hover {
background: rgba(255, 255, 255, 0.25);
}
}
}
// Page list
.page-list {
list-style: none;
margin: 0;
padding: 8px 0;
}
.page-row {
display: flex;
align-items: center;
width: 100%;
padding: 12px 16px;
background: none;
border: none;
color: $text-primary;
font-size: 13px;
text-align: left;
cursor: pointer;
transition: background $transition-fast;
gap: 12px;
&:hover {
background: $hover-bg;
}
&.active {
background: $active-bg;
color: $active-color;
font-weight: 500;
}
}
.page-number {
min-width: 32px;
text-align: right;
font-size: 12px;
font-weight: 600;
opacity: 0.7;
}
.page-label {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
// PDF Outline list
.outline-list {
list-style: none;
margin: 0;
padding: 8px 0;
}
.outline-item {
list-style: none;
}
.outline-children {
list-style: none;
margin: 0;
padding: 0;
}
.outline-row {
display: flex;
align-items: center;
width: 100%;
padding: 10px 16px;
padding-right: 12px;
background: none;
border: none;
color: $text-primary;
font-size: 13px;
text-align: left;
cursor: pointer;
transition: background $transition-fast;
gap: 8px;
&:hover {
background: $hover-bg;
}
&.active {
background: $active-bg;
color: $active-color;
font-weight: 500;
}
&.has-children {
font-weight: 500;
}
}
.expand-icon {
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
flex-shrink: 0;
color: $text-muted;
transition: transform $transition-fast;
border-radius: 4px;
&:hover {
background: rgba(255, 255, 255, 0.1);
color: $text-primary;
}
&.expanded {
transform: rotate(90deg);
}
}
.outline-title {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.outline-page {
font-size: 11px;
color: $text-muted;
flex-shrink: 0;
min-width: 28px;
text-align: right;
}
// Item list (bookmarks & notes)
.item-list {
list-style: none;
margin: 0;
padding: 8px 0;
}
.list-item {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 16px;
cursor: pointer;
transition: background $transition-fast;
&:hover {
background: $hover-bg;
.delete-btn,
.action-buttons {
opacity: 1;
}
}
}
.note-item {
align-items: flex-start;
}
.note-bar {
width: 3px;
align-self: stretch;
border-radius: 2px;
flex-shrink: 0;
}
.item-content {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 4px;
}
.item-title {
font-size: 13px;
font-weight: 500;
color: $text-primary;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.note-text {
font-size: 13px;
color: $text-primary;
line-height: 1.4;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
}
.item-chapter {
font-size: 11px;
color: $text-secondary;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.item-meta {
font-size: 11px;
color: $text-muted;
}
.action-buttons {
display: flex;
flex-direction: column;
gap: 4px;
opacity: 0;
transition: opacity $transition-fast;
flex-shrink: 0;
}
.edit-btn,
.delete-btn {
width: 28px;
height: 28px;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
background: none;
border: none;
border-radius: 6px;
color: $text-muted;
cursor: pointer;
transition: background $transition-fast, color $transition-fast;
flex-shrink: 0;
opacity: 0;
svg {
width: 16px;
height: 16px;
}
}
.list-item:hover .edit-btn,
.list-item:hover .delete-btn {
opacity: 1;
}
.edit-btn:hover {
background: rgba(74, 144, 226, 0.15);
color: $active-color;
}
.delete-btn:hover {
background: rgba(239, 68, 68, 0.15);
color: #ef4444;
}
// Notes container
.notes-container {
display: flex;
flex-direction: column;
height: 100%;
}
.notes-search-wrapper {
display: flex;
align-items: center;
gap: 10px;
padding: 12px 16px;
background: rgba(0, 0, 0, 0.2);
border-bottom: 1px solid $border-color;
.search-icon {
color: $text-muted;
flex-shrink: 0;
}
.search-input {
flex: 1;
background: none;
border: none;
color: $text-primary;
font-size: 14px;
outline: none;
&::placeholder {
color: $text-muted;
}
}
.clear-btn {
width: 24px;
height: 24px;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(255, 255, 255, 0.1);
border: none;
border-radius: 50%;
color: $text-secondary;
cursor: pointer;
transition: background $transition-fast, color $transition-fast;
flex-shrink: 0;
&:hover {
background: rgba(255, 255, 255, 0.15);
color: $text-primary;
}
}
}
// Empty state
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 48px 24px;
text-align: center;
color: $text-secondary;
.empty-icon {
width: 48px;
height: 48px;
margin-bottom: 16px;
opacity: 0.4;
}
p {
margin: 0 0 8px;
font-size: 14px;
font-weight: 500;
}
}
.empty-hint {
font-size: 12px;
color: $text-muted;
}
// Animations
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes fadeOut {
from { opacity: 1; }
to { opacity: 0; }
}
@keyframes slideIn {
from { transform: translateX(-100%); }
to { transform: translateX(0); }
}
@keyframes slideOut {
from { transform: translateX(0); }
to { transform: translateX(-100%); }
}
@@ -0,0 +1,112 @@
import {Component, DestroyRef, effect, inject, signal} from '@angular/core';
import {CommonModule, DatePipe} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {TranslocoPipe} from '@jsverse/transloco';
import {CbxSidebarService, CbxSidebarTab} from './cbx-sidebar.service';
import {BookNoteV2} from '../../../../../shared/service/book-note-v2.service';
import {ReaderIconComponent} from '../../../ebook-reader';
@Component({
selector: 'app-cbx-sidebar',
standalone: true,
templateUrl: './cbx-sidebar.component.html',
styleUrls: ['./cbx-sidebar.component.scss'],
imports: [CommonModule, FormsModule, TranslocoPipe, ReaderIconComponent, DatePipe]
})
export class CbxSidebarComponent {
private readonly sidebarService = inject(CbxSidebarService);
private readonly destroyRef = inject(DestroyRef);
private closeAnimationTimeout: ReturnType<typeof setTimeout> | null = null;
readonly activeTab = this.sidebarService.activeTab;
readonly bookInfo = this.sidebarService.bookInfo;
readonly pages = this.sidebarService.pages;
readonly currentPage = this.sidebarService.currentPage;
readonly bookmarks = this.sidebarService.bookmarks;
readonly notes = this.sidebarService.notes;
readonly notesSearchQuery = this.sidebarService.notesSearchQuery;
readonly filteredNotes = this.sidebarService.filteredNotes;
readonly isOpen = signal(false);
readonly closing = signal(false);
constructor() {
effect(() => {
if (this.sidebarService.isOpen()) {
this.clearCloseAnimation();
this.isOpen.set(true);
this.closing.set(false);
return;
}
if (this.isOpen()) {
this.closeWithAnimation();
}
});
this.destroyRef.onDestroy(() => this.clearCloseAnimation());
}
private closeWithAnimation(): void {
this.closing.set(true);
this.closeAnimationTimeout = setTimeout(() => {
this.isOpen.set(false);
this.closing.set(false);
this.closeAnimationTimeout = null;
}, 250);
}
private clearCloseAnimation(): void {
if (this.closeAnimationTimeout) {
clearTimeout(this.closeAnimationTimeout);
this.closeAnimationTimeout = null;
}
}
onOverlayClick(): void {
this.sidebarService.close();
}
setActiveTab(tab: CbxSidebarTab): void {
this.sidebarService.setActiveTab(tab);
}
onPageClick(pageNumber: number): void {
this.sidebarService.navigateToPage(pageNumber);
}
isPageActive(pageNumber: number): boolean {
return this.currentPage() === pageNumber;
}
onBookmarkClick(cfi: string): void {
this.sidebarService.navigateToBookmark(cfi);
}
onDeleteBookmark(event: MouseEvent, bookmarkId: number): void {
event.stopPropagation();
this.sidebarService.deleteBookmark(bookmarkId);
}
onNoteClick(cfi: string): void {
this.sidebarService.navigateToNote(cfi);
}
onEditNote(event: MouseEvent, note: BookNoteV2): void {
event.stopPropagation();
this.sidebarService.editNote(note);
}
onDeleteNote(event: MouseEvent, noteId: number): void {
event.stopPropagation();
this.sidebarService.deleteNote(noteId);
}
onNotesSearchInput(query: string): void {
this.sidebarService.setNotesSearchQuery(query);
}
clearNotesSearch(): void {
this.sidebarService.setNotesSearchQuery('');
}
}
@@ -0,0 +1,237 @@
import {computed, inject, Injectable, signal} from '@angular/core';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {TranslocoService} from '@jsverse/transloco';
import {CbxPageInfo, CbxReaderService} from '../../../../book/service/cbx-reader.service';
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
import {Book} from '../../../../book/model/book.model';
import {BookMark, BookMarkService, CreateBookMarkRequest} from '../../../../../shared/service/book-mark.service';
import {BookNoteV2, BookNoteV2Service, CreateBookNoteV2Request, UpdateBookNoteV2Request} from '../../../../../shared/service/book-note-v2.service';
export interface SidebarBookInfo {
id: number | null;
title: string;
authors: string;
coverUrl: string | null;
}
export type CbxSidebarTab = 'pages' | 'bookmarks' | 'notes';
@Injectable()
export class CbxSidebarService {
private urlHelper = inject(UrlHelperService);
private cbxReaderService = inject(CbxReaderService);
private bookMarkService = inject(BookMarkService);
private bookNoteV2Service = inject(BookNoteV2Service);
private readonly t = inject(TranslocoService);
private destroy$ = new Subject<void>();
private bookId!: number;
private altBookType?: string;
private readonly _isOpen = signal(false);
readonly isOpen = this._isOpen.asReadonly();
private readonly _activeTab = signal<CbxSidebarTab>('pages');
readonly activeTab = this._activeTab.asReadonly();
private readonly _bookInfo = signal<SidebarBookInfo>({
id: null,
title: '',
authors: '',
coverUrl: null
});
readonly bookInfo = this._bookInfo.asReadonly();
private readonly _pages = signal<CbxPageInfo[]>([]);
readonly pages = this._pages.asReadonly();
private readonly _currentPage = signal(1);
readonly currentPage = this._currentPage.asReadonly();
private readonly _bookmarks = signal<BookMark[]>([]);
readonly bookmarks = this._bookmarks.asReadonly();
private readonly _notes = signal<BookNoteV2[]>([]);
readonly notes = this._notes.asReadonly();
private readonly _notesSearchQuery = signal('');
readonly notesSearchQuery = this._notesSearchQuery.asReadonly();
readonly filteredNotes = computed(() => {
const query = this._notesSearchQuery().toLowerCase().trim();
const notes = this._notes();
if (!query) {
return notes;
}
return notes.filter(note =>
note.noteContent.toLowerCase().includes(query) ||
note.chapterTitle?.toLowerCase().includes(query)
);
});
private _navigateToPage = new Subject<number>();
private _editNote = new Subject<BookNoteV2>();
navigateToPage$ = this._navigateToPage.asObservable();
editNote$ = this._editNote.asObservable();
initialize(bookId: number, book: Book, destroy$: Subject<void>, altBookType?: string): void {
this.bookId = bookId;
this.altBookType = altBookType;
this.destroy$ = destroy$;
this._bookInfo.set({
id: book.id,
title: book.metadata?.title || book.fileName || this.t.translate('readerCbx.sidebar.untitled'),
authors: (book.metadata?.authors || []).join(', '),
coverUrl: this.urlHelper.getThumbnailUrl(book.id, book.metadata?.coverUpdatedOn)
});
this.loadPageInfo();
this.loadBookmarks();
this.loadNotes();
}
private loadPageInfo(): void {
this.cbxReaderService.getPageInfo(this.bookId, this.altBookType)
.pipe(takeUntil(this.destroy$))
.subscribe(pages => this._pages.set(pages));
}
private loadBookmarks(): void {
this.bookMarkService.getBookmarksForBook(this.bookId)
.pipe(takeUntil(this.destroy$))
.subscribe(bookmarks => this._bookmarks.set(bookmarks));
}
private loadNotes(): void {
this.bookNoteV2Service.getNotesForBook(this.bookId)
.pipe(takeUntil(this.destroy$))
.subscribe(notes => this._notes.set(notes));
}
setCurrentPage(page: number): void {
this._currentPage.set(page);
}
setActiveTab(tab: CbxSidebarTab): void {
this._activeTab.set(tab);
}
open(tab?: CbxSidebarTab): void {
if (tab) {
this._activeTab.set(tab);
}
this._isOpen.set(true);
}
close(): void {
this._isOpen.set(false);
}
navigateToPage(pageNumber: number): void {
this._navigateToPage.next(pageNumber);
this.close();
}
isPageBookmarked(pageNumber: number): boolean {
const pageStr = pageNumber.toString();
return this._bookmarks().some(bookmark => bookmark.cfi === pageStr);
}
getBookmarkForPage(pageNumber: number): BookMark | undefined {
const pageStr = pageNumber.toString();
return this._bookmarks().find(bookmark => bookmark.cfi === pageStr);
}
createBookmark(pageNumber: number, title?: string): void {
const request: CreateBookMarkRequest = {
bookId: this.bookId,
cfi: pageNumber.toString(),
title: title || `${this.t.translate('readerCbx.sidebar.page')} ${pageNumber}`
};
this.bookMarkService.createBookmark(request)
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.loadBookmarks());
}
deleteBookmark(bookmarkId: number): void {
this.bookMarkService.deleteBookmark(bookmarkId)
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.loadBookmarks());
}
toggleBookmark(pageNumber: number): void {
const existingBookmark = this.getBookmarkForPage(pageNumber);
if (existingBookmark) {
this.deleteBookmark(existingBookmark.id);
} else {
this.createBookmark(pageNumber);
}
}
navigateToBookmark(pageNumber: string): void {
const page = parseInt(pageNumber, 10);
if (!isNaN(page)) {
this._navigateToPage.next(page);
this.close();
}
}
pageHasNotes(pageNumber: number): boolean {
const pageStr = pageNumber.toString();
return this._notes().some(note => note.cfi === pageStr);
}
createNote(pageNumber: number, noteContent: string, color?: string): void {
const request: CreateBookNoteV2Request = {
bookId: this.bookId,
cfi: pageNumber.toString(),
noteContent,
color: color || '#FFC107',
chapterTitle: `${this.t.translate('readerCbx.sidebar.page')} ${pageNumber}`
};
this.bookNoteV2Service.createNote(request)
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.loadNotes());
}
updateNote(noteId: number, noteContent: string, color?: string): void {
const request: UpdateBookNoteV2Request = {
noteContent,
color
};
this.bookNoteV2Service.updateNote(noteId, request)
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.loadNotes());
}
deleteNote(noteId: number): void {
this.bookNoteV2Service.deleteNote(noteId)
.pipe(takeUntil(this.destroy$))
.subscribe(() => {
this._notes.update(notes => notes.filter(note => note.id !== noteId));
});
}
editNote(note: BookNoteV2): void {
this.close();
this._editNote.next(note);
}
navigateToNote(pageNumber: string): void {
const page = parseInt(pageNumber, 10);
if (!isNaN(page)) {
this._navigateToPage.next(page);
this.close();
}
}
setNotesSearchQuery(query: string): void {
this._notesSearchQuery.set(query);
}
}
@@ -0,0 +1,60 @@
import {Injectable, inject} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_CONFIG} from '../../../../core/config/api-config';
import {AuthService} from '../../../../shared/service/auth.service';
export interface EpubSpineItem {
idref: string;
href: string;
mediaType: string;
linear: boolean;
}
export interface EpubManifestItem {
id: string;
href: string;
mediaType: string;
properties?: string[];
size: number;
}
export interface EpubTocItem {
label: string;
href: string;
children?: EpubTocItem[];
}
export interface EpubBookInfo {
containerPath: string;
rootPath: string;
spine: EpubSpineItem[];
manifest: EpubManifestItem[];
toc: EpubTocItem;
metadata: Record<string, any>;
coverPath?: string;
}
@Injectable({
providedIn: 'root'
})
export class EpubStreamingService {
private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/epub`;
private http = inject(HttpClient);
private authService = inject(AuthService);
getBookInfo(bookId: number, bookType?: string): Observable<EpubBookInfo> {
if (bookType) {
return this.http.get<EpubBookInfo>(`${this.baseUrl}/${bookId}/info`, { params: { bookType } });
}
return this.http.get<EpubBookInfo>(`${this.baseUrl}/${bookId}/info`);
}
getBaseUrl(): string {
return this.baseUrl;
}
getAuthToken(): string | null {
return this.authService.getInternalAccessToken();
}
}
@@ -0,0 +1,491 @@
import {inject, Injectable} from '@angular/core';
import {Subject} from 'rxjs';
import {ReaderAnnotationService} from '../features/annotations/annotation-renderer.service';
export interface ViewEvent {
type: 'load' | 'relocate' | 'error' | 'middle-single-tap' | 'draw-annotation' | 'show-annotation' | 'text-selected' | 'toggle-fullscreen' | 'toggle-shortcuts-help' | 'escape-pressed' | 'go-first-section' | 'go-last-section' | 'toggle-toc' | 'toggle-search' | 'toggle-notes';
detail?: any;
popupPosition?: { x: number; y: number; showBelow?: boolean };
}
export interface TextSelection {
text: string;
cfi: string;
range: Range;
index: number;
}
interface ViewCallbacks {
prev: () => void;
next: () => void;
getCFI: (index: number, range: Range) => string | null;
getContents: () => Array<{ index: number; doc: Document }> | null;
}
@Injectable({
providedIn: 'root'
})
export class ReaderEventService {
private readonly DOUBLE_CLICK_INTERVAL_MS = 300;
private readonly LONG_HOLD_THRESHOLD_MS = 500;
private readonly LEFT_ZONE_PERCENT = 0.3;
private readonly RIGHT_ZONE_PERCENT = 0.7;
private readonly SWIPE_THRESHOLD_PX = 50;
private annotationService = inject(ReaderAnnotationService);
private view: any;
private viewCallbacks: ViewCallbacks | null = null;
private isNavigating = false;
private lastClickTime = 0;
private lastClickZone: 'left' | 'middle' | 'right' | null = null;
private longHoldTimeout: ReturnType<typeof setTimeout> | null = null;
private keydownHandler?: (event: KeyboardEvent) => void;
private clickedDocs = new WeakSet<Document>();
private touchStartX = 0;
private touchStartY = 0;
private isTextSelectionInProgress = false;
private touchStartTime = 0;
private selectionChangeTimeout: ReturnType<typeof setTimeout> | null = null;
private lastTouchTime = 0;
private eventSubject = new Subject<ViewEvent>();
public events$ = this.eventSubject.asObservable();
initialize(view: any, callbacks: ViewCallbacks): void {
this.view = view;
this.viewCallbacks = callbacks;
this.attachViewEventListeners();
this.attachKeyboardHandler();
this.attachWindowMessageHandler();
}
destroy(): void {
if (this.keydownHandler) {
document.removeEventListener('keydown', this.keydownHandler);
this.keydownHandler = undefined;
}
this.view = null;
this.viewCallbacks = null;
this.clickedDocs = new WeakSet<Document>();
}
emit(event: ViewEvent): void {
this.eventSubject.next(event);
}
private attachViewEventListeners(): void {
if (!this.view) return;
this.view.addEventListener('load', (e: any) => {
this.eventSubject.next({type: 'load', detail: e.detail});
if (e.detail?.doc) {
if (this.keydownHandler) {
e.detail.doc.addEventListener('keydown', this.keydownHandler);
}
this.attachIframeEventHandlers(e.detail.doc);
}
const allAnnotations = this.annotationService.getAllAnnotations();
if (allAnnotations.length > 0 && this.view) {
setTimeout(() => {
allAnnotations.forEach(annotation => {
this.view?.addAnnotation({value: annotation.value});
});
}, 100);
}
});
this.view.addEventListener('relocate', (e: any) => {
this.eventSubject.next({type: 'relocate', detail: e.detail});
});
this.view.addEventListener('error', (e: any) => {
this.eventSubject.next({type: 'error', detail: e.detail});
});
this.view.addEventListener('draw-annotation', (e: any) => {
const {draw, annotation, doc, range} = e.detail;
const storedStyle = this.annotationService.getAnnotationStyle(annotation.value);
if (storedStyle) {
const overlayerStyle = this.annotationService.getOverlayerDrawFunction(storedStyle.style);
draw(overlayerStyle, {color: storedStyle.color});
}
this.eventSubject.next({type: 'draw-annotation', detail: {annotation, doc, range}});
});
this.view.addEventListener('show-annotation', (e: any) => {
this.eventSubject.next({type: 'show-annotation', detail: e.detail});
});
}
private attachKeyboardHandler(): void {
this.keydownHandler = (event: KeyboardEvent) => {
const target = event.target as HTMLElement;
if (target?.tagName === 'INPUT' || target?.tagName === 'TEXTAREA' || target?.isContentEditable) {
return;
}
const k = event.key;
if (k === 'ArrowLeft' || k === 'PageUp') {
this.viewCallbacks?.prev();
event.preventDefault();
} else if (k === 'ArrowRight' || k === 'PageDown') {
this.viewCallbacks?.next();
event.preventDefault();
} else if (k === ' ' && event.shiftKey) {
this.viewCallbacks?.prev();
event.preventDefault();
} else if (k === ' ') {
this.viewCallbacks?.next();
event.preventDefault();
} else if (k === 'Home') {
this.eventSubject.next({type: 'go-first-section'});
event.preventDefault();
} else if (k === 'End') {
this.eventSubject.next({type: 'go-last-section'});
event.preventDefault();
} else if (k === 'f' || k === 'F') {
this.eventSubject.next({type: 'toggle-fullscreen'});
event.preventDefault();
} else if (k === 't' || k === 'T') {
this.eventSubject.next({type: 'toggle-toc'});
event.preventDefault();
} else if (k === 's' || k === 'S') {
this.eventSubject.next({type: 'toggle-search'});
event.preventDefault();
} else if (k === 'n' || k === 'N') {
this.eventSubject.next({type: 'toggle-notes'});
event.preventDefault();
} else if (k === '?') {
this.eventSubject.next({type: 'toggle-shortcuts-help'});
event.preventDefault();
} else if (k === 'Escape') {
this.eventSubject.next({type: 'escape-pressed'});
event.preventDefault();
}
};
document.addEventListener('keydown', this.keydownHandler);
}
private attachWindowMessageHandler(): void {
window.addEventListener('message', (event) => {
if (event.data?.type === 'iframe-click') {
this.handleIframeClickMessage(event.data);
}
});
}
private attachIframeEventHandlers(doc: Document): void {
if (this.clickedDocs.has(doc)) {
return;
}
this.clickedDocs.add(doc);
doc.addEventListener('mousedown', () => {
this.longHoldTimeout = setTimeout(() => {
this.longHoldTimeout = null;
}, this.LONG_HOLD_THRESHOLD_MS);
}, true);
doc.addEventListener('mouseup', () => {
this.handleSelectionEnd(doc);
});
doc.addEventListener('click', (event: MouseEvent) => {
// Ignore synthesized mouse events that follow touch events
if (Date.now() - this.lastTouchTime < 500) {
return;
}
const iframe = doc.defaultView?.frameElement as HTMLIFrameElement | null;
if (!iframe) return;
const iframeRect = iframe.getBoundingClientRect();
const viewportX = iframeRect.left + event.clientX;
const viewportY = iframeRect.top + event.clientY;
window.postMessage({
type: 'iframe-click',
clientX: viewportX,
clientY: viewportY,
iframeLeft: iframeRect.left,
iframeWidth: iframeRect.width,
eventClientX: event.clientX,
target: (event.target as HTMLElement)?.tagName
}, '*');
}, true);
doc.addEventListener('touchstart', (event: TouchEvent) => {
this.handleTouchStart(event, doc);
}, {passive: true});
doc.addEventListener('touchmove', (event: TouchEvent) => {
this.handleTouchMove(event, doc);
}, {passive: false});
doc.addEventListener('touchend', (event: TouchEvent) => {
this.handleTouchEnd(event, doc);
}, {passive: false});
doc.addEventListener('selectionchange', () => {
this.handleSelectionChange(doc);
});
this.injectMobileSelectionStyles(doc);
}
private handleSelectionChange(doc: Document): void {
if (this.selectionChangeTimeout) {
clearTimeout(this.selectionChangeTimeout);
}
this.selectionChangeTimeout = setTimeout(() => {
const selection = doc.defaultView?.getSelection();
if (!selection || selection.isCollapsed || selection.rangeCount === 0) {
return;
}
const range = selection.getRangeAt(0);
const text = range.toString().trim();
if (!text) return;
if ('ontouchstart' in window || navigator.maxTouchPoints > 0) {
this.handleSelectionEnd(doc);
}
}, 300);
}
private injectMobileSelectionStyles(doc: Document): void {
const styleId = 'grimmory-mobile-selection-styles';
if (doc.getElementById(styleId)) return;
const style = doc.createElement('style');
style.id = styleId;
style.textContent = `
* {
-webkit-touch-callout: none !important;
-webkit-user-select: text !important;
user-select: text !important;
}
`;
doc.head.appendChild(style);
}
private handleTouchStart(event: TouchEvent, _doc: Document): void {
if (event.touches.length !== 1) return;
const touch = event.touches[0];
this.touchStartX = touch.clientX;
this.touchStartY = touch.clientY;
this.touchStartTime = Date.now();
this.isTextSelectionInProgress = false;
this.longHoldTimeout = setTimeout(() => {
this.longHoldTimeout = null;
}, this.LONG_HOLD_THRESHOLD_MS);
}
private handleTouchMove(event: TouchEvent, doc: Document): void {
if (event.touches.length !== 1) return;
const touch = event.touches[0];
const deltaX = Math.abs(touch.clientX - this.touchStartX);
const deltaY = Math.abs(touch.clientY - this.touchStartY);
const selection = doc.defaultView?.getSelection();
if (selection && !selection.isCollapsed && selection.rangeCount > 0) {
this.isTextSelectionInProgress = true;
event.preventDefault();
return;
}
if (deltaX > 10 && deltaX > deltaY && !this.isTextSelectionInProgress) {
return;
}
}
private handleTouchEnd(event: TouchEvent, doc: Document): void {
const touchEndTime = Date.now();
const touchDuration = touchEndTime - this.touchStartTime;
this.lastTouchTime = touchEndTime;
const selection = doc.defaultView?.getSelection();
const hasSelection = selection && !selection.isCollapsed && selection.rangeCount > 0;
if (hasSelection) {
this.isTextSelectionInProgress = false;
event.preventDefault();
setTimeout(() => {
this.handleSelectionEnd(doc);
}, 50);
return;
}
if (!this.isTextSelectionInProgress && event.changedTouches.length === 1) {
const touch = event.changedTouches[0];
const deltaX = touch.clientX - this.touchStartX;
const deltaY = Math.abs(touch.clientY - this.touchStartY);
if (Math.abs(deltaX) >= this.SWIPE_THRESHOLD_PX && Math.abs(deltaX) > deltaY) {
if (this.isNavigating) return;
this.isNavigating = true;
if (deltaX < 0) {
this.viewCallbacks?.next();
} else {
this.viewCallbacks?.prev();
}
setTimeout(() => this.isNavigating = false, 300);
return;
}
if (touchDuration < this.LONG_HOLD_THRESHOLD_MS && Math.abs(deltaX) < 10 && deltaY < 10) {
const iframe = doc.defaultView?.frameElement as HTMLIFrameElement | null;
if (!iframe) return;
const iframeRect = iframe.getBoundingClientRect();
const viewportX = iframeRect.left + touch.clientX;
window.postMessage({
type: 'iframe-click',
clientX: viewportX,
clientY: iframeRect.top + touch.clientY,
iframeLeft: iframeRect.left,
iframeWidth: iframeRect.width,
eventClientX: touch.clientX,
target: (event.target as HTMLElement)?.tagName
}, '*');
}
}
this.isTextSelectionInProgress = false;
}
private handleSelectionEnd(doc: Document): void {
setTimeout(() => {
const selection = doc.defaultView?.getSelection();
if (!selection || selection.isCollapsed || selection.rangeCount === 0) {
return;
}
const range = selection.getRangeAt(0);
const text = range.toString().trim();
if (!text) return;
const contents = this.viewCallbacks?.getContents();
if (!contents || contents.length === 0) return;
const {index} = contents[0];
const cfi = this.viewCallbacks?.getCFI(index, range);
if (cfi) {
const iframe = doc.defaultView?.frameElement as HTMLIFrameElement | null;
const rangeRect = range.getBoundingClientRect();
let popupX = rangeRect.left + (rangeRect.width / 2);
let selectionTop = rangeRect.top;
let selectionBottom = rangeRect.bottom;
if (iframe) {
const iframeRect = iframe.getBoundingClientRect();
popupX = iframeRect.left + rangeRect.left + (rangeRect.width / 2);
selectionTop = iframeRect.top + rangeRect.top;
selectionBottom = iframeRect.top + rangeRect.bottom;
}
const minSpaceAbove = 120;
const showBelow = selectionTop < minSpaceAbove;
let popupY: number;
if (showBelow) {
popupY = selectionBottom + 10;
} else {
popupY = selectionTop - 50;
}
popupX = Math.max(100, Math.min(popupX, window.innerWidth - 150));
this.eventSubject.next({
type: 'text-selected',
detail: {text, cfi, range, index},
popupPosition: {x: popupX, y: popupY, showBelow}
});
}
}, 10);
}
private handleIframeClickMessage(data: any): void {
if (!this.view) return;
const now = Date.now();
const timeSinceLastClick = now - this.lastClickTime;
const viewRect = this.view.getBoundingClientRect();
const x = data.clientX - viewRect.left;
const width = viewRect.width;
const leftThreshold = width * this.LEFT_ZONE_PERCENT;
const rightThreshold = width * this.RIGHT_ZONE_PERCENT;
let currentZone: 'left' | 'middle' | 'right';
if (x < leftThreshold) {
currentZone = 'left';
} else if (x > rightThreshold) {
currentZone = 'right';
} else {
currentZone = 'middle';
}
if (timeSinceLastClick < this.DOUBLE_CLICK_INTERVAL_MS && this.lastClickZone === currentZone) {
this.lastClickTime = now;
this.lastClickZone = currentZone;
if (currentZone !== 'middle') {
}
return;
}
this.lastClickTime = now;
this.lastClickZone = currentZone;
setTimeout(() => {
if (Date.now() - this.lastClickTime >= this.DOUBLE_CLICK_INTERVAL_MS) {
this.processIframeClick(data);
}
}, this.DOUBLE_CLICK_INTERVAL_MS);
}
private processIframeClick(data: any): void {
if (!this.longHoldTimeout) {
return;
}
if (this.isNavigating) {
return;
}
if (!this.view) return;
const viewRect = this.view.getBoundingClientRect();
const x = data.clientX - viewRect.left;
const width = viewRect.width;
const leftThreshold = width * this.LEFT_ZONE_PERCENT;
const rightThreshold = width * this.RIGHT_ZONE_PERCENT;
const isMobile = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
if (x < leftThreshold && !isMobile) {
this.isNavigating = true;
this.viewCallbacks?.prev();
setTimeout(() => this.isNavigating = false, 300);
} else if (x > rightThreshold && !isMobile) {
this.isNavigating = true;
this.viewCallbacks?.next();
setTimeout(() => this.isNavigating = false, 300);
} else {
this.eventSubject.next({type: 'middle-single-tap'});
}
}
}
@@ -0,0 +1,37 @@
import {Injectable} from '@angular/core';
import {defer, from, Observable, of} from 'rxjs';
import {switchMap} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ReaderLoaderService {
private scriptLoaded = false;
loadFoliateScript(): Observable<void> {
if (this.scriptLoaded || customElements.get('foliate-view')) {
return of(undefined);
}
return defer(() => new Observable<void>(observer => {
const script = document.createElement('script');
script.type = 'module';
script.src = '/assets/foliate/view.js';
script.onload = () => {
this.scriptLoaded = true;
setTimeout(() => {
observer.next();
observer.complete();
}, 100);
};
script.onerror = () => observer.error(new Error('Failed to load foliate.js'));
document.head.appendChild(script);
}));
}
waitForCustomElement(): Observable<void> {
return defer(() => from(customElements.whenDefined('foliate-view'))).pipe(
switchMap(() => of(undefined))
);
}
}
@@ -0,0 +1,196 @@
import {inject, Injectable} from '@angular/core';
import {ReaderState} from '../state/reader-state.service';
import {EpubCustomFontService} from '../features/fonts/custom-font.service';
@Injectable({
providedIn: 'root'
})
export class ReaderStyleService {
private epubCustomFontService = inject(EpubCustomFontService);
generateCSS(state: ReaderState): string {
const {lineHeight, justify, hyphenate, fontSize, theme, fontFamily} = state;
const userStylesheet = '';
const overrideFont = false;
const mediaActiveClass = 'media-active';
let fontFaceRule = '';
let actualFontFamily = null;
if (fontFamily !== null) {
const customFontId = this.parseCustomFontId(fontFamily);
if (customFontId !== null) {
const customFont = this.epubCustomFontService.getCustomFontById(customFontId);
const blobUrl = this.epubCustomFontService.getBlobUrl(customFontId);
if (customFont && blobUrl) {
const sanitizedFontName = this.epubCustomFontService.sanitizeFontName(customFont.fontName);
actualFontFamily = `"${sanitizedFontName}", sans-serif`;
fontFaceRule = `@font-face {
font-family: "${sanitizedFontName}";
src: url("${blobUrl}") format("truetype");
font-weight: normal;
font-style: normal;
font-display: swap;
}`;
}
} else {
actualFontFamily = fontFamily;
}
}
const fontFamilyRule = actualFontFamily ? `
body {
font-family: ${actualFontFamily} !important;
}
body * {
font-family: inherit !important;
}` : '';
return `
${fontFaceRule}
@namespace epub "http://www.idpf.org/2007/ops";
@media print {
html {
column-width: auto !important;
height: auto !important;
width: auto !important;
}
}
@media screen {
html {
color-scheme: light dark;
color: ${theme.fg || theme.light.fg};
font-size: ${fontSize}px;
}${fontFamilyRule}
a:any-link {
color: ${theme.link || theme.light.link};
text-decoration-color: light-dark(
color-mix(in srgb, currentColor 20%, transparent),
color-mix(in srgb, currentColor 40%, transparent));
text-underline-offset: .1em;
}
a:any-link:hover {
text-decoration-color: unset;
}
@media (prefers-color-scheme: dark) {
html {
color: ${theme.fg || theme.dark.fg};
}
a:any-link {
color: ${theme.link || theme.dark.link};
}
}
aside[epub|type~="footnote"] {
display: none;
}
}
html {
line-height: ${lineHeight};
hanging-punctuation: allow-end last;
orphans: 2;
widows: 2;
}
[align="left"] { text-align: left; }
[align="right"] { text-align: right; }
[align="center"] { text-align: center; }
[align="justify"] { text-align: justify; }
:is(hgroup, header) p {
text-align: unset;
hyphens: unset;
}
h1, h2, h3, h4, h5, h6, hgroup, th {
text-wrap: balance;
}
pre {
white-space: pre-wrap !important;
tab-size: 2;
}
@media screen and (prefers-color-scheme: light) {
${(theme.bg || theme.light.bg) !== '#ffffff' ? `
html, body {
color: ${theme.fg || theme.light.fg} !important;
background: none !important;
}
body * {
color: inherit !important;
border-color: currentColor !important;
background-color: ${theme.bg || theme.light.bg} !important;
}
a:any-link {
color: ${theme.link || theme.light.link} !important;
}
svg, img {
background-color: transparent !important;
mix-blend-mode: multiply;
}
.${mediaActiveClass}, .${mediaActiveClass} * {
color: ${theme.fg || theme.light.fg} !important;
background: color-mix(in hsl, ${theme.fg || theme.light.fg}, #fff 50%) !important;
background: color-mix(in hsl, ${theme.fg || theme.light.fg}, ${theme.bg || theme.light.bg} 85%) !important;
}` : ''}
}
@media screen and (prefers-color-scheme: dark) {
html, body {
color: ${theme.fg || theme.dark.fg} !important;
background: none !important;
}
body * {
color: inherit !important;
border-color: currentColor !important;
background-color: ${theme.bg || theme.dark.bg} !important;
}
a:any-link {
color: ${theme.link || theme.dark.link} !important;
}
.${mediaActiveClass}, .${mediaActiveClass} * {
color: ${theme.fg || theme.dark.fg} !important;
background: color-mix(in hsl, ${theme.fg || theme.dark.fg}, #000 50%) !important;
background: color-mix(in hsl, ${theme.fg || theme.dark.fg}, ${theme.bg || theme.dark.bg} 75%) !important;
}
}
p, li, blockquote, dd {
line-height: ${lineHeight};
text-align: ${justify ? 'justify' : 'start'} !important;
hyphens: ${hyphenate ? 'auto' : 'none'};
}
${overrideFont ? '' : ''}
${userStylesheet}
::selection {
background-color: rgba(128, 128, 128, 0.3);
}
::-moz-selection {
background-color: rgba(128, 128, 128, 0.3);
}
`;
}
private parseCustomFontId(fontFamily: string): number | null {
if (fontFamily.startsWith('custom:')) {
const id = parseInt(fontFamily.substring(7), 10);
return !isNaN(id) ? id : null;
}
const id = parseInt(fontFamily, 10);
return !isNaN(id) && id.toString() === fontFamily ? id : null;
}
applyStylesToRenderer(renderer: any, state: ReaderState): void {
if (!renderer) return;
renderer.setAttribute('max-column-count', state.maxColumnCount);
renderer.setAttribute('gap', `${state.gap * 100}%`);
renderer.setAttribute('max-inline-size', `${state.maxInlineSize}px`);
renderer.setAttribute('max-block-size', `${state.maxBlockSize}px`);
if (typeof renderer.setStyles === 'function') {
const css = this.generateCSS(state);
renderer.setStyles(css);
}
if (state.flow === 'paginated') {
renderer.setAttribute('margin', '40px');
} else {
renderer.removeAttribute('margin');
}
}
}
@@ -0,0 +1,255 @@
import {inject, Injectable} from '@angular/core';
import {defer, from, Observable, of, throwError, timer} from 'rxjs';
import {catchError, map, switchMap} from 'rxjs/operators';
import {ReaderAnnotationService, Annotation} from '../features/annotations/annotation-renderer.service';
import {ReaderEventService, ViewEvent, TextSelection} from './event.service';
import {PageInfo, ThemeInfo, PageDecorator} from '../shared/header-footer.util';
import {EpubStreamingService, EpubBookInfo} from './epub-streaming.service';
export type {ViewEvent, TextSelection} from './event.service';
export type {PageInfo, ThemeInfo} from '../shared/header-footer.util';
interface TocItem {
label: string;
href: string;
subitems?: TocItem[];
}
export interface BookMetadata {
title?: string;
authors?: string[];
language?: string;
publisher?: string;
description?: string;
identifier?: string;
coverUrl?: string;
[key: string]: any;
}
@Injectable({
providedIn: 'root'
})
export class ReaderViewManagerService {
private annotationService = inject(ReaderAnnotationService);
private eventService = inject(ReaderEventService);
private epubStreamingService = inject(EpubStreamingService);
private view: any;
public get events$(): Observable<ViewEvent> {
return this.eventService.events$;
}
createView(container: HTMLElement): void {
this.view = document.createElement('foliate-view');
this.view.style.width = '100%';
this.view.style.height = '100%';
this.view.style.display = 'block';
container.appendChild(this.view);
this.eventService.initialize(this.view, {
prev: () => this.prev(),
next: () => this.next(),
getCFI: (index: number, range: Range) => this.view?.getCFI(index, range),
getContents: () => this.view?.renderer?.getContents() ?? null
});
}
loadEpub(epubPath: string): Observable<void> {
if (!this.view) {
return throwError(() => new Error('View not created'));
}
return timer(100).pipe(
switchMap(() => from(fetch(epubPath))),
switchMap(response => {
if (!response.ok) {
throw new Error(`EPUB not found: ${response.status}`);
}
return from(response.blob());
}),
switchMap(blob => {
const file = new File([blob], epubPath.split('/').pop() || 'book.epub', {
type: 'application/epub+zip'
});
return from(this.view.open(file) as Promise<void>);
}),
map(() => undefined),
catchError(err => throwError(() => err))
);
}
loadEpubStreaming(bookId: number, bookType?: string): Observable<void> {
if (!this.view) {
return throwError(() => new Error('View not created'));
}
return this.epubStreamingService.getBookInfo(bookId, bookType).pipe(
switchMap(bookInfo => from(this.openStreamingBook(bookId, bookInfo, bookType))),
map(() => undefined),
catchError(err => throwError(() => err))
);
}
private async openStreamingBook(bookId: number, bookInfo: EpubBookInfo, bookType?: string): Promise<void> {
const makeStreamingBook = (window as any).makeStreamingBook;
if (!makeStreamingBook) {
throw new Error('makeStreamingBook not available - Foliate script may not be loaded');
}
const baseUrl = this.epubStreamingService.getBaseUrl();
const authToken = this.epubStreamingService.getAuthToken();
const book = await makeStreamingBook(bookId, baseUrl, bookInfo, authToken, bookType);
await this.view.open(book);
}
destroy(): void {
this.eventService.destroy();
this.view?.remove();
this.view = null;
}
goTo(target?: string | number | null): Observable<void> {
const resolvedTarget = target ?? 0;
if (!this.view) {
return of(undefined);
}
return defer(() =>
from(this.view.goTo(resolvedTarget) as Promise<void>)
).pipe(
map(() => undefined)
);
}
goToSection(index: number): Observable<void> {
return this.goTo(index);
}
goToFraction(fraction: number): Observable<void> {
if (!this.view) {
return of(undefined);
}
return defer(() => from(this.view.goToFraction(fraction) as Promise<void>)).pipe(
map(() => undefined)
);
}
prev(): void {
this.view?.prev();
}
next(): void {
this.view?.next();
}
getRenderer(): any {
return this.view?.renderer;
}
getSelection(): TextSelection | null {
const renderer = this.getRenderer();
if (!renderer) return null;
const contents = renderer.getContents();
if (!contents || contents.length === 0) return null;
const {index, doc} = contents[0];
if (!doc) return null;
const selection = doc.defaultView?.getSelection();
if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return null;
const range = selection.getRangeAt(0);
const text = range.toString().trim();
if (!text) return null;
const cfi = this.view?.getCFI(index, range);
if (!cfi) return null;
return {text, cfi, range, index};
}
clearSelection(): void {
this.view?.deselect();
}
addAnnotation(annotation: Annotation): Observable<{index: number; label: string} | undefined> {
return this.annotationService.addAnnotation(this.view, annotation);
}
deleteAnnotation(cfi: string): Observable<void> {
return this.annotationService.deleteAnnotation(this.view, cfi);
}
addAnnotations(annotations: Annotation[]): void {
this.annotationService.addAnnotations(this.view, annotations);
}
updateHeadersAndFooters(chapterName: string, pageInfo?: PageInfo, theme?: ThemeInfo, timeRemainingLabel?: string): void {
const renderer = this.getRenderer();
PageDecorator.updateHeadersAndFooters(renderer, chapterName, pageInfo, theme, timeRemainingLabel);
}
getChapters(): TocItem[] {
if (!this.view?.book?.toc) return [];
const mapToc = (items: any[]): TocItem[] =>
items.map(item => ({
label: item.label,
href: item.href,
subitems: item.subitems?.length ? mapToc(item.subitems) : undefined
}));
return mapToc(this.view.book.toc);
}
getSectionFractions(): number[] {
if (!this.view?.getSectionFractions) return [];
return this.view.getSectionFractions();
}
getMetadata(): Observable<BookMetadata> {
if (!this.view?.book?.metadata) {
return of({});
}
const {metadata} = this.view.book;
return this.getCoverUrl().pipe(
map(coverUrl => ({
title: metadata.title,
authors: metadata.authors,
language: metadata.language,
publisher: metadata.publisher,
description: metadata.description,
identifier: metadata.identifier,
coverUrl,
...metadata
}))
);
}
getCover(): Observable<Blob | null> {
if (!this.view?.book?.getCover) {
return of(null);
}
return defer(() => {
const coverPromise = this.view.book.getCover();
return coverPromise ? from(coverPromise as Promise<Blob | null>) : of(null);
});
}
getCoverUrl(): Observable<string | null> {
return this.getCover().pipe(
map(blob => blob ? URL.createObjectURL(blob) : null)
);
}
async* search(opts: { query: string; matchCase?: boolean; matchWholeWords?: boolean }): AsyncGenerator<any> {
if (!this.view?.search) return;
yield* this.view.search(opts);
}
clearSearch(): void {
this.view?.clearSearch?.();
}
}
@@ -0,0 +1,201 @@
<ng-container *transloco="let t; prefix: 'readerEbook.metadataDialog'">
<div class="dialog-overlay" (click)="close.emit()">
<div class="dialog" (click)="$event.stopPropagation()">
<div class="dialog-header">
<h2>{{ t('title') }}</h2>
<button class="close-btn" (click)="close.emit()">&#10005;</button>
</div>
<div class="dialog-body">
<div class="metadata-container">
<div class="cover-section">
@if (bookCoverUrl) {
<img [src]="bookCoverUrl" [alt]="metadata?.title || t('unknown')" class="book-cover">
} @else {
<div class="cover-placeholder">
<span class="placeholder-icon">&#128218;</span>
</div>
}
</div>
<div class="metadata-section">
<div class="metadata-group">
<h3 class="section-title">{{ t('basicInformation') }}</h3>
<div class="metadata-item">
<span class="label">{{ t('titleLabel') }}</span>
<span class="value">{{ metadata?.title || t('unknown') }}</span>
</div>
@if (metadata?.subtitle) {
<div class="metadata-item">
<span class="label">{{ t('subtitle') }}</span>
<span class="value">{{ metadata?.subtitle }}</span>
</div>
}
<div class="metadata-item">
<span class="label">{{ t('authors') }}</span>
<span class="value">{{ formatAuthors(metadata?.authors) }}</span>
</div>
@if (metadata?.publisher) {
<div class="metadata-item">
<span class="label">{{ t('publisher') }}</span>
<span class="value">{{ metadata?.publisher }}</span>
</div>
}
@if (metadata?.publishedDate) {
<div class="metadata-item">
<span class="label">{{ t('published') }}</span>
<span class="value">{{ formatDate(metadata?.publishedDate) }}</span>
</div>
}
@if (metadata?.language) {
<div class="metadata-item">
<span class="label">{{ t('language') }}</span>
<span class="value">{{ metadata?.language }}</span>
</div>
}
@if (metadata?.pageCount) {
<div class="metadata-item">
<span class="label">{{ t('pages') }}</span>
<span class="value">{{ metadata?.pageCount }}</span>
</div>
}
</div>
@if (metadata?.seriesName) {
<div class="metadata-group">
<h3 class="section-title">{{ t('series') }}</h3>
<div class="metadata-item">
<span class="label">{{ t('seriesName') }}</span>
<span class="value">{{ metadata?.seriesName }}</span>
</div>
@if (metadata?.seriesNumber) {
<div class="metadata-item">
<span class="label">{{ t('bookNumber') }}</span>
<span class="value">
{{ metadata?.seriesNumber }}@if (metadata?.seriesTotal) {
/ {{ metadata?.seriesTotal }}
}
</span>
</div>
}
</div>
}
@if (metadata?.isbn13 || metadata?.isbn10 || metadata?.asin) {
<div class="metadata-group">
<h3 class="section-title">{{ t('identifiers') }}</h3>
@if (metadata?.isbn13) {
<div class="metadata-item">
<span class="label">ISBN-13</span>
<span class="value">{{ metadata?.isbn13 }}</span>
</div>
}
@if (metadata?.isbn10) {
<div class="metadata-item">
<span class="label">ISBN-10</span>
<span class="value">{{ metadata?.isbn10 }}</span>
</div>
}
@if (metadata?.asin) {
<div class="metadata-item">
<span class="label">ASIN</span>
<span class="value">{{ metadata?.asin }}</span>
</div>
}
</div>
}
@if (metadata?.rating || metadata?.goodreadsRating || metadata?.amazonRating) {
<div class="metadata-group">
<h3 class="section-title">{{ t('ratings') }}</h3>
@if (metadata?.goodreadsRating) {
<div class="metadata-item">
<span class="label">Goodreads</span>
<span class="value">
&#11088; {{ metadata?.goodreadsRating?.toFixed(2) }}
@if (metadata?.goodreadsReviewCount) {
<span class="review-count">({{ metadata?.goodreadsReviewCount }} {{ t('reviews') }})</span>
}
</span>
</div>
}
@if (metadata?.amazonRating) {
<div class="metadata-item">
<span class="label">Amazon</span>
<span class="value">
&#11088; {{ metadata?.amazonRating?.toFixed(2) }}
@if (metadata?.amazonReviewCount) {
<span class="review-count">({{ metadata?.amazonReviewCount }} {{ t('reviews') }})</span>
}
</span>
</div>
}
</div>
}
@if (metadata?.categories && metadata?.categories!.length > 0) {
<div class="metadata-group">
<h3 class="section-title">{{ t('categories') }}</h3>
<div class="tags-container">
@for (category of metadata?.categories; track category) {
<span class="tag">{{ category }}</span>
}
</div>
</div>
}
@if (metadata?.tags && metadata?.tags!.length > 0) {
<div class="metadata-group">
<h3 class="section-title">{{ t('tags') }}</h3>
<div class="tags-container">
@for (tag of metadata?.tags; track tag) {
<span class="tag">{{ tag }}</span>
}
</div>
</div>
}
@if (book?.fileSizeKb) {
<div class="metadata-group">
<h3 class="section-title">{{ t('fileInformation') }}</h3>
<div class="metadata-item">
<span class="label">{{ t('fileSize') }}</span>
<span class="value">{{ formatFileSize(book?.fileSizeKb) }}</span>
</div>
@if (book?.fileName) {
<div class="metadata-item">
<span class="label">{{ t('fileName') }}</span>
<span class="value file-name">{{ book?.fileName }}</span>
</div>
}
</div>
}
@if (metadata?.description) {
<div class="metadata-group">
<h3 class="section-title">{{ t('description') }}</h3>
<p class="description">{{ metadata?.description }}</p>
</div>
}
</div>
</div>
</div>
</div>
</div>
</ng-container>
@@ -0,0 +1,289 @@
// Variables matching sidebar styling
$dialog-bg: #1a1a1a;
$text-primary: rgba(255, 255, 255, 0.95);
$text-secondary: rgba(255, 255, 255, 0.6);
$text-muted: rgba(255, 255, 255, 0.4);
$border-color: rgba(255, 255, 255, 0.08);
$hover-bg: rgba(255, 255, 255, 0.08);
$active-color: #818cf8;
$active-bg: rgba(129, 140, 248, 0.15);
$transition-fast: 150ms ease;
$transition-normal: 200ms ease;
.dialog-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(4px);
z-index: 12000;
display: flex;
align-items: center;
justify-content: center;
animation: fadeIn $transition-normal;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.dialog {
background: $dialog-bg;
border: 1px solid $border-color;
border-radius: 12px;
width: 90%;
max-width: 800px;
max-height: 85vh;
display: flex;
flex-direction: column;
overflow: hidden;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
animation: slideUp 250ms cubic-bezier(0.4, 0, 0.2, 1);
@media (max-width: 768px) {
width: 95%;
max-height: 90vh;
margin: 20px;
}
}
@keyframes slideUp {
from {
transform: translateY(20px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.dialog-header {
padding: 16px 20px;
border-bottom: 1px solid $border-color;
display: flex;
align-items: center;
justify-content: space-between;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.02) 0%, transparent 100%);
h2 {
margin: 0;
font-size: 16px;
font-weight: 600;
color: $text-primary;
letter-spacing: -0.3px;
}
}
.close-btn {
background: none;
border: none;
color: $text-muted;
font-size: 18px;
cursor: pointer;
padding: 6px;
border-radius: 6px;
transition: background $transition-fast, color $transition-fast;
line-height: 1;
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
&:hover {
background: $hover-bg;
color: $text-primary;
}
&:focus-visible {
outline: 2px solid $active-color;
outline-offset: 2px;
}
}
.dialog-body {
padding: 20px;
overflow-y: auto;
flex: 1;
min-height: 0;
@media (max-width: 768px) {
padding: 16px;
}
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.15);
border-radius: 3px;
&:hover {
background: rgba(255, 255, 255, 0.25);
}
}
}
.metadata-container {
display: flex;
gap: 24px;
@media (max-width: 768px) {
flex-direction: column;
gap: 20px;
}
}
.cover-section {
flex-shrink: 0;
width: 200px;
@media (max-width: 768px) {
width: 100%;
max-width: 160px;
margin: 0 auto;
}
}
.book-cover {
width: 100%;
height: auto;
border-radius: 8px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
max-height: 300px;
object-fit: cover;
@media (max-width: 768px) {
max-height: 240px;
}
}
.cover-placeholder {
width: 100%;
aspect-ratio: 2/3;
background: linear-gradient(135deg, rgba(255, 255, 255, 0.04) 0%, rgba(255, 255, 255, 0.01) 100%);
border: 2px dashed rgba(255, 255, 255, 0.12);
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
@media (max-width: 768px) {
max-height: 240px;
}
.placeholder-icon {
font-size: 56px;
opacity: 0.3;
@media (max-width: 768px) {
font-size: 44px;
}
}
}
.metadata-section {
flex: 1;
display: flex;
flex-direction: column;
gap: 16px;
min-width: 0;
}
.metadata-group {
animation: fadeIn $transition-normal;
&:not(:last-child) {
padding-bottom: 16px;
border-bottom: 1px solid $border-color;
}
}
.section-title {
color: $text-muted;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 1px;
margin: 0 0 12px 0;
}
.metadata-item {
display: grid;
grid-template-columns: 110px 1fr;
gap: 12px;
margin-bottom: 10px;
align-items: start;
&:last-child {
margin-bottom: 0;
}
@media (max-width: 768px) {
grid-template-columns: 1fr;
gap: 4px;
}
}
.label {
color: $text-secondary;
font-size: 13px;
font-weight: 500;
}
.value {
color: $text-primary;
font-size: 13px;
word-break: break-word;
line-height: 1.5;
&.file-name {
font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Roboto Mono', monospace;
font-size: 12px;
color: $text-secondary;
background: rgba(255, 255, 255, 0.03);
padding: 4px 8px;
border-radius: 4px;
}
}
.review-count {
color: $text-muted;
font-size: 12px;
margin-left: 4px;
}
.tags-container {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.tag {
background: $active-bg;
color: $text-primary;
padding: 4px 12px;
border-radius: 12px;
font-size: 12px;
font-weight: 500;
border: 1px solid rgba(129, 140, 248, 0.2);
transition: background $transition-fast;
&:hover {
background: rgba(129, 140, 248, 0.25);
}
}
.description {
color: $text-secondary;
font-size: 13px;
line-height: 1.7;
margin: 0;
white-space: pre-wrap;
}
@@ -0,0 +1,55 @@
import {Component, EventEmitter, inject, Input, Output} from '@angular/core';
import {CommonModule} from '@angular/common';
import {TranslocoDirective} from '@jsverse/transloco';
import {TranslocoService} from '@jsverse/transloco';
import {Book} from '../../../book/model/book.model';
import {UrlHelperService} from '../../../../shared/service/url-helper.service';
@Component({
selector: 'app-reader-book-metadata-dialog',
standalone: true,
imports: [CommonModule, TranslocoDirective],
templateUrl: './metadata-dialog.component.html',
styleUrls: ['./metadata-dialog.component.scss']
})
export class ReaderBookMetadataDialogComponent {
@Input() book: Book | null = null;
@Output() close = new EventEmitter<void>();
private urlHelperService = inject(UrlHelperService);
private readonly t = inject(TranslocoService);
get metadata() {
return this.book?.metadata;
}
get bookCoverUrl(): string | null {
if (!this.book?.id) return null;
const coverUpdatedOn = this.book.metadata?.coverUpdatedOn;
return this.urlHelperService.getCoverUrl(this.book.id, coverUpdatedOn);
}
formatDate(date: string | undefined): string {
if (!date) return this.t.translate('readerEbook.metadataDialog.na');
try {
return new Date(date).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
} catch {
return date;
}
}
formatAuthors(authors: string[] | undefined): string {
if (!authors || authors.length === 0) return this.t.translate('readerEbook.metadataDialog.unknown');
return authors.join(', ');
}
formatFileSize(sizeKb: number | undefined): string {
if (!sizeKb) return this.t.translate('readerEbook.metadataDialog.na');
if (sizeKb < 1024) return `${sizeKb.toFixed(1)} KB`;
return `${(sizeKb / 1024).toFixed(2)} MB`;
}
}
@@ -0,0 +1,53 @@
<ng-container *transloco="let t; prefix: 'readerEbook.noteDialog'">
<div class="dialog-overlay" (click)="onOverlayClick($event)">
<div class="dialog">
<div class="dialog-header">
<h2>{{ isEditing ? t('editNote') : t('addNote') }}</h2>
<button class="close-btn" (click)="onCancel()">
<app-reader-icon name="close" [size]="18"></app-reader-icon>
</button>
</div>
<div class="dialog-body">
@if (data?.selectedText) {
<div class="selected-text-section">
<span class="section-label">{{ t('selectedText') }}</span>
<p class="selected-text">"{{ data?.selectedText }}"</p>
</div>
}
<div class="note-section">
<label class="section-label" for="noteContent">{{ t('yourNote') }}</label>
<textarea
id="noteContent"
class="note-input"
[(ngModel)]="noteContent"
[placeholder]="t('notePlaceholder')"
rows="6"
autofocus
></textarea>
</div>
<div class="color-section">
<span class="section-label">{{ t('noteColor') }}</span>
<div class="color-buttons">
@for (color of noteColors; track color.value) {
<button
class="color-btn"
[style.--color]="color.value"
[class.selected]="selectedColor === color.value"
[title]="color.label"
(click)="selectColor(color.value)">
</button>
}
</div>
</div>
</div>
<div class="dialog-footer">
<button class="btn btn-secondary" (click)="onCancel()">{{ 'common.cancel' | transloco }}</button>
<button class="btn btn-primary" (click)="onSave()" [disabled]="!noteContent.trim()">{{ isEditing ? t('updateNote') : t('saveNote') }}</button>
</div>
</div>
</div>
</ng-container>
@@ -0,0 +1,261 @@
// Variables matching reader styling
$dialog-bg: #1a1a1a;
$text-primary: rgba(255, 255, 255, 0.95);
$text-secondary: rgba(255, 255, 255, 0.6);
$text-muted: rgba(255, 255, 255, 0.4);
$border-color: rgba(255, 255, 255, 0.08);
$hover-bg: rgba(255, 255, 255, 0.08);
$active-color: #818cf8;
$active-bg: rgba(129, 140, 248, 0.15);
$transition-fast: 150ms ease;
$transition-normal: 200ms ease;
.dialog-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(4px);
z-index: 13000;
display: flex;
align-items: center;
justify-content: center;
animation: fadeIn $transition-normal;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.dialog {
background: $dialog-bg;
border: 1px solid $border-color;
border-radius: 12px;
width: 90%;
max-width: 500px;
max-height: 85vh;
display: flex;
flex-direction: column;
overflow: hidden;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
animation: slideUp 250ms cubic-bezier(0.4, 0, 0.2, 1);
}
@keyframes slideUp {
from {
transform: translateY(20px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.dialog-header {
padding: 16px 20px;
border-bottom: 1px solid $border-color;
display: flex;
align-items: center;
justify-content: space-between;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.02) 0%, transparent 100%);
h2 {
margin: 0;
font-size: 16px;
font-weight: 600;
color: $text-primary;
letter-spacing: -0.3px;
}
}
.close-btn {
background: none;
border: none;
color: $text-muted;
cursor: pointer;
padding: 6px;
border-radius: 6px;
transition: background $transition-fast, color $transition-fast;
line-height: 1;
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
&:hover {
background: $hover-bg;
color: $text-primary;
}
}
.dialog-body {
padding: 20px;
overflow-y: auto;
flex: 1;
display: flex;
flex-direction: column;
gap: 20px;
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.15);
border-radius: 3px;
&:hover {
background: rgba(255, 255, 255, 0.25);
}
}
}
.section-label {
display: block;
color: $text-muted;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 1px;
margin-bottom: 8px;
}
.selected-text-section {
.selected-text {
margin: 0;
padding: 12px 16px;
background: rgba(255, 255, 255, 0.03);
border-left: 3px solid $active-color;
border-radius: 0 8px 8px 0;
color: $text-secondary;
font-size: 13px;
font-style: italic;
line-height: 1.6;
max-height: 100px;
overflow-y: auto;
}
}
.note-section {
flex: 1;
display: flex;
flex-direction: column;
}
.note-input {
flex: 1;
min-height: 120px;
padding: 12px 16px;
background: rgba(255, 255, 255, 0.03);
border: 1px solid $border-color;
border-radius: 8px;
color: $text-primary;
font-size: 14px;
line-height: 1.6;
resize: vertical;
font-family: inherit;
transition: border-color $transition-fast, box-shadow $transition-fast;
&::placeholder {
color: $text-muted;
}
&:focus {
outline: none;
border-color: $active-color;
box-shadow: 0 0 0 3px rgba(129, 140, 248, 0.15);
}
}
.color-section {
.color-buttons {
display: flex;
gap: 10px;
}
}
.color-btn {
width: 32px;
height: 32px;
border-radius: 50%;
border: 2px solid transparent;
background: var(--color);
cursor: pointer;
transition: transform $transition-fast, border-color $transition-fast, box-shadow $transition-fast;
position: relative;
&:hover {
transform: scale(1.1);
}
&.selected {
border-color: $text-primary;
box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.2);
&::after {
content: '✓';
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-size: 14px;
font-weight: bold;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}
}
}
.dialog-footer {
padding: 16px 20px;
border-top: 1px solid $border-color;
display: flex;
justify-content: flex-end;
gap: 12px;
background: linear-gradient(0deg, rgba(255, 255, 255, 0.02) 0%, transparent 100%);
}
.btn {
padding: 10px 20px;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background $transition-fast, transform $transition-fast, opacity $transition-fast;
border: none;
&:active {
transform: scale(0.98);
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
transform: none;
}
}
.btn-secondary {
background: $hover-bg;
color: $text-primary;
&:hover:not(:disabled) {
background: rgba(255, 255, 255, 0.12);
}
}
.btn-primary {
background: $active-color;
color: white;
&:hover:not(:disabled) {
background: #9ba3fa;
}
}
@@ -0,0 +1,78 @@
import {Component, EventEmitter, Input, Output, OnChanges, SimpleChanges} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {TranslocoDirective, TranslocoPipe} from '@jsverse/transloco';
import {ReaderIconComponent} from '../shared/icon.component';
export interface NoteDialogData {
cfi: string;
selectedText?: string;
chapterTitle?: string;
noteId?: number;
noteContent?: string;
color?: string;
}
export interface NoteDialogResult {
noteContent: string;
color: string;
}
@Component({
selector: 'app-reader-note-dialog',
standalone: true,
imports: [CommonModule, FormsModule, TranslocoDirective, TranslocoPipe, ReaderIconComponent],
templateUrl: './note-dialog.component.html',
styleUrls: ['./note-dialog.component.scss']
})
export class ReaderNoteDialogComponent implements OnChanges {
@Input() data: NoteDialogData | null = null;
@Output() save = new EventEmitter<NoteDialogResult>();
@Output() cancel = new EventEmitter<void>();
noteContent = '';
selectedColor = '#FFC107';
get isEditing(): boolean {
return !!this.data?.noteId;
}
ngOnChanges(changes: SimpleChanges): void {
if (changes['data'] && this.data) {
this.noteContent = this.data.noteContent || '';
this.selectedColor = this.data.color || '#FFC107';
}
}
noteColors = [
{value: '#FFC107', label: 'Amber'},
{value: '#4CAF50', label: 'Green'},
{value: '#2196F3', label: 'Blue'},
{value: '#E91E63', label: 'Pink'},
{value: '#9C27B0', label: 'Purple'},
{value: '#FF5722', label: 'Deep Orange'}
];
onSave(): void {
if (this.noteContent.trim()) {
this.save.emit({
noteContent: this.noteContent.trim(),
color: this.selectedColor
});
}
}
onCancel(): void {
this.cancel.emit();
}
selectColor(color: string): void {
this.selectedColor = color;
}
onOverlayClick(event: MouseEvent): void {
if ((event.target as HTMLElement).classList.contains('dialog-overlay')) {
this.onCancel();
}
}
}
@@ -0,0 +1,223 @@
<ng-container *transloco="let t; prefix: 'readerEbook.settingsDialog'">
<div class="dialog-overlay" (click)="close.emit()">
<div class="dialog" (click)="$event.stopPropagation()">
<div class="tabs-row">
<div class="tabs">
<button
class="tab"
[class.active]="activeTab === 'theme'"
(click)="activeTab = 'theme'">
{{ t('themeTab') }}
</button>
<button
class="tab"
[class.active]="activeTab === 'typography'"
(click)="activeTab = 'typography'">
{{ t('typographyTab') }}
</button>
<button
class="tab"
[class.active]="activeTab === 'layout'"
(click)="activeTab = 'layout'">
{{ t('layoutTab') }}
</button>
</div>
<button class="close-btn" (click)="close.emit()">&#10005;</button>
</div>
<div class="dialog-body">
@if (activeTab === 'theme') {
<div class="tab-content">
<div class="section-header dark-mode-header">
{{ t('darkMode') }}
<span class="mode-switch-wrapper">
<span class="mode-icon sun" [class.active]="!state.isDark">&#9728;&#65039;</span>
<button class="switch" [class.active]="state.isDark" (click)="toggleDarkMode()">
<span class="slider"></span>
</button>
<span class="mode-icon moon" [class.active]="state.isDark">&#127769;</span>
</span>
</div>
<div class="section-header">{{ t('themeColors') }}</div>
<div class="theme-grid">
@for (theme of themes; track theme.name) {
<label class="theme-option">
<input
type="radio"
name="theme"
[value]="theme.name"
[checked]="state.theme.name === theme.name"
(change)="onThemeChange(theme.name)">
<div class="theme-card">
<div class="theme-colors">
<span class="color-swatch" [style.background-color]="state.isDark ? theme.dark.bg : theme.light.bg"></span>
<span class="color-swatch" [style.background-color]="state.isDark ? theme.dark.fg : theme.light.fg"></span>
</div>
<span class="theme-name">{{ theme.label }}</span>
</div>
</label>
}
</div>
<div class="section-header">{{ t('annotationHighlighter') }}</div>
<div class="annotation-colors">
@for (color of annotationColors; track color.name) {
<button
class="color-picker-btn"
[class.active]="selectedAnnotationColor === color.value"
[style.background-color]="color.value"
[attr.aria-label]="color.label"
(click)="setAnnotationColor(color.value)">
@if (selectedAnnotationColor === color.value) {
<span class="check-icon">&#10003;</span>
}
</button>
}
</div>
</div>
}
@if (activeTab === 'typography') {
<div class="tab-content">
<div class="section-header">{{ t('fontSettings') }}</div>
<div class="control">
<label>{{ t('fontSize') }}</label>
<div class="control-right">
<div class="stepper">
<button (click)="decreaseFontSize()">&#8722;</button>
<span>{{ state.fontSize }}</span>
<button (click)="increaseFontSize()">+</button>
</div>
</div>
</div>
<div class="control">
<label>{{ t('lineHeight') }}</label>
<div class="control-right">
<div class="stepper">
<button (click)="decreaseLineHeight()">&#8722;</button>
<span>{{ state.lineHeight | number:'1.1-1' }}</span>
<button (click)="increaseLineHeight()">+</button>
</div>
</div>
</div>
<div class="section-header">{{ t('fontFamily') }}</div>
<div class="font-grid">
@for (font of fonts; track font.value) {
<button
class="font-option"
[class.active]="state.fontFamily === font.value"
[style.font-family]="font.value ? getFontFamilyForPreview(font.value) : 'inherit'"
(click)="setFontFamily(font.value)">
<span class="font-preview">Aa</span>
<span class="font-name">{{ font.name }}</span>
</button>
}
</div>
</div>
}
@if (activeTab === 'layout') {
<div class="tab-content">
<div class="section-header">{{ t('layout') }}</div>
<div class="control">
<label>{{ t('readingFlow') }}</label>
<div class="control-right">
<div class="radio-group">
<label>
<input
type="radio"
name="flow"
value="paginated"
[checked]="state.flow === 'paginated'"
(change)="setFlow('paginated')"
/>
{{ t('paginated') }}
</label>
<label>
<input
type="radio"
name="flow"
value="scrolled"
[checked]="state.flow === 'scrolled'"
(change)="setFlow('scrolled')"
/>
{{ t('scrolled') }}
</label>
</div>
</div>
</div>
<div class="control">
<label>{{ t('maxColumns') }}</label>
<div class="control-right">
<div class="stepper">
<button (click)="decreaseMaxColumnCount()">&#8722;</button>
<span>{{ state.maxColumnCount }}</span>
<button (click)="increaseMaxColumnCount()">+</button>
</div>
</div>
</div>
<div class="control">
<label>{{ t('columnGap') }}</label>
<div class="control-right gap-control">
<input
#gapInput
type="range"
min="0"
max="0.5"
step="0.01"
[value]="state.gap"
(input)="setGap(gapInput.valueAsNumber)"
/>
<span class="value">{{ (state.gap * 100) | number : '1.0-0' }}%</span>
</div>
</div>
<div class="control">
<label>{{ t('maxWidth') }}</label>
<div class="control-right">
<div class="stepper">
<button (click)="decreaseMaxInlineSize()">&#8722;</button>
<span>{{ state.maxInlineSize }}</span>
<button (click)="increaseMaxInlineSize()">+</button>
</div>
</div>
</div>
<div class="control">
<label>{{ t('maxHeight') }}</label>
<div class="control-right">
<div class="stepper">
<button (click)="decreaseMaxBlockSize()">&#8722;</button>
<span>{{ state.maxBlockSize }}</span>
<button (click)="increaseMaxBlockSize()">+</button>
</div>
</div>
</div>
<div class="section-header">{{ t('textOptions') }}</div>
<div class="toggle-control">
<span>{{ t('justifyText') }}</span>
<button class="switch" [class.active]="state.justify" (click)="toggleJustify()">
<span class="slider"></span>
</button>
</div>
<div class="toggle-control">
<span>{{ t('hyphenate') }}</span>
<button class="switch" [class.active]="state.hyphenate" (click)="toggleHyphenate()">
<span class="slider"></span>
</button>
</div>
</div>
}
</div>
</div>
</div>
</ng-container>
@@ -0,0 +1,603 @@
// Variables matching sidebar styling
$dialog-bg: #1a1a1a;
$text-primary: rgba(255, 255, 255, 0.95);
$text-secondary: rgba(255, 255, 255, 0.6);
$text-muted: rgba(255, 255, 255, 0.4);
$border-color: rgba(255, 255, 255, 0.08);
$hover-bg: rgba(255, 255, 255, 0.08);
$active-color: #818cf8;
$active-bg: rgba(129, 140, 248, 0.15);
$transition-fast: 150ms ease;
$transition-normal: 200ms ease;
.dialog-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.25);
z-index: 12000;
display: flex;
align-items: center;
justify-content: center;
animation: fadeIn $transition-normal;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.dialog {
background: $dialog-bg;
border: 1px solid $border-color;
border-radius: 12px;
width: 90%;
max-width: 520px;
height: 600px;
max-height: 85vh;
overflow: hidden;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
animation: slideUp 250ms cubic-bezier(0.4, 0, 0.2, 1);
display: flex;
flex-direction: column;
}
@keyframes slideUp {
from {
transform: translateY(20px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.tabs-row {
display: flex;
align-items: center;
border-bottom: 1px solid $border-color;
background: rgba(0, 0, 0, 0.2);
padding: 0 20px;
justify-content: center;
position: relative;
}
.tabs {
display: flex;
align-items: center;
justify-content: center;
flex: 0 1 auto;
}
.tab {
background: none;
border: none;
color: $text-secondary;
padding: 14px 20px;
cursor: pointer;
font-size: 13px;
font-weight: 500;
position: relative;
transition: color $transition-fast;
text-align: center;
min-width: 90px;
display: flex;
align-items: center;
justify-content: center;
&:hover {
color: $text-primary;
}
&.active {
color: $active-color;
&::after {
content: '';
position: absolute;
left: 16px;
right: 16px;
bottom: 0;
height: 2px;
background: $active-color;
border-radius: 1px 1px 0 0;
}
}
}
.close-btn {
position: absolute;
right: 16px;
top: 50%;
transform: translateY(-50%);
background: none;
border: none;
color: $text-muted;
font-size: 18px;
cursor: pointer;
padding: 6px;
border-radius: 6px;
transition: background $transition-fast, color $transition-fast;
line-height: 1;
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
&:hover {
background: $hover-bg;
color: $text-primary;
}
}
.dialog-body {
padding: 20px 24px;
overflow-y: auto;
flex: 1 1 0;
min-height: 0;
max-height: 100%;
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.15);
border-radius: 3px;
&:hover {
background: rgba(255, 255, 255, 0.25);
}
}
}
.tab-content {
animation: fadeIn $transition-normal;
}
.section-header {
color: $text-muted;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 1px;
margin-top: 24px;
margin-bottom: 12px;
padding-bottom: 8px;
border-bottom: 1px solid $border-color;
&:first-child {
margin-top: 0;
}
&.dark-mode-header {
display: flex;
align-items: center;
font-size: 11px;
font-weight: 600;
gap: 30px;
padding-bottom: 8px;
margin-bottom: 24px;
border-bottom: 1px solid $border-color;
}
}
.mode-switch-wrapper {
display: flex;
align-items: center;
gap: 10px;
}
.mode-icon {
font-size: 18px;
opacity: 0.3;
transition: all 300ms ease;
user-select: none;
&.active {
opacity: 1;
transform: scale(1.1);
}
&.sun {
filter: grayscale(100%);
&.active {
filter: grayscale(0%);
}
}
&.moon {
filter: grayscale(100%);
&.active {
filter: grayscale(0%);
}
}
}
.toggle-control {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 0;
margin-bottom: 2px;
span {
color: $text-primary;
font-size: 14px;
font-weight: 500;
}
}
.switch {
position: relative;
width: 44px;
height: 24px;
background: rgba(255, 255, 255, 0.15);
border: none;
border-radius: 12px;
cursor: pointer;
transition: background 300ms ease;
padding: 0;
&.active {
background: $active-color;
.slider {
transform: translateX(20px);
}
}
.slider {
position: absolute;
top: 2px;
left: 2px;
width: 20px;
height: 20px;
background: #ffffff;
border-radius: 50%;
transition: transform 300ms ease;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
&:hover {
background: rgba(255, 255, 255, 0.2);
&.active {
background: #9aa3fa;
}
}
&:focus-visible {
outline: 2px solid $active-color;
outline-offset: 2px;
}
}
.theme-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12px;
margin-bottom: 16px;
}
@media (max-width: 768px) {
.theme-grid {
grid-template-columns: repeat(3, 1fr);
}
}
.theme-option {
cursor: pointer;
input[type="radio"] {
display: none;
}
.theme-card {
background: rgba(255, 255, 255, 0.03);
border: 2px solid $border-color;
border-radius: 8px;
padding: 10px;
transition: all $transition-fast;
display: flex;
flex-direction: column;
gap: 8px;
&:hover {
background: $hover-bg;
border-color: rgba(255, 255, 255, 0.15);
}
}
input:checked + .theme-card {
border-color: $active-color;
background: $active-bg;
}
.theme-colors {
display: flex;
gap: 4px;
height: 24px;
}
.color-swatch {
flex: 1;
border-radius: 4px;
border: 1px solid rgba(0, 0, 0, 0.2);
}
.theme-name {
color: $text-primary;
font-size: 11px;
font-weight: 500;
text-align: center;
}
}
.font-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
margin-bottom: 20px;
}
.font-option {
background: rgba(255, 255, 255, 0.03);
border: 2px solid $border-color;
border-radius: 8px;
padding: 12px;
cursor: pointer;
transition: all $transition-fast;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
&:hover {
background: $hover-bg;
border-color: rgba(255, 255, 255, 0.15);
}
&.active {
border-color: $active-color;
background: $active-bg;
}
.font-preview {
font-size: 24px;
color: $text-primary;
line-height: 1;
}
.font-name {
color: $text-secondary;
font-size: 11px;
font-weight: 500;
text-align: center;
}
}
.control {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 16px;
min-height: 32px;
&:last-child {
margin-bottom: 0;
}
> label {
color: $text-primary;
font-size: 14px;
font-weight: 500;
flex-shrink: 0;
}
input[type="range"] {
flex: 1;
margin: 0 10px;
height: 5px;
background: rgba(255, 255, 255, 0.12);
border-radius: 3px;
outline: none;
cursor: pointer;
-webkit-appearance: none;
&::-webkit-slider-thumb {
-webkit-appearance: none;
width: 14px;
height: 14px;
border-radius: 50%;
background: $active-color;
cursor: pointer;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
transition: all $transition-fast;
&:hover {
transform: scale(1.1);
box-shadow: 0 2px 8px rgba(129, 140, 248, 0.5);
}
}
&::-moz-range-thumb {
width: 14px;
height: 14px;
border-radius: 50%;
background: $active-color;
border: none;
cursor: pointer;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}
}
.value {
color: $text-secondary;
font-size: 12px;
min-width: 42px;
text-align: right;
font-variant-numeric: tabular-nums;
}
}
.control-right {
display: flex;
align-items: center;
gap: 8px;
}
.gap-control {
flex: 1;
max-width: 200px;
min-width: 160px;
input[type="range"] {
flex: 1;
margin-right: 8px;
}
.value {
min-width: 38px;
}
}
.stepper {
display: flex;
align-items: center;
gap: 4px;
background: rgba(255, 255, 255, 0.03);
padding: 3px;
border-radius: 6px;
border: 1px solid $border-color;
button {
width: 28px;
height: 28px;
background: rgba(255, 255, 255, 0.05);
color: $text-secondary;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
display: flex;
align-items: center;
justify-content: center;
transition: all $transition-fast;
font-weight: 300;
&:hover {
background: $hover-bg;
color: $text-primary;
}
&:active {
transform: scale(0.95);
}
}
span {
min-width: 48px;
text-align: center;
color: $text-primary;
font-size: 13px;
font-weight: 500;
font-variant-numeric: tabular-nums;
}
}
.radio-group {
display: flex;
gap: 18px;
label {
display: flex;
align-items: center;
gap: 7px;
cursor: pointer;
font-size: 14px;
color: $text-primary;
font-weight: 500;
position: relative;
user-select: none;
input[type="radio"] {
appearance: none;
width: 18px;
height: 18px;
border: 2px solid $active-color;
border-radius: 50%;
background: rgba(255, 255, 255, 0.05);
margin: 0 6px 0 0;
outline: none;
transition: border-color $transition-fast, box-shadow $transition-fast;
&:checked {
background: $active-color;
box-shadow: 0 0 0 2px rgba(129, 140, 248, 0.15);
border-color: $active-color;
}
&:focus-visible {
box-shadow: 0 0 0 2px $active-color;
}
}
}
}
.annotation-colors {
display: flex;
gap: 14px;
margin-bottom: 20px;
justify-content: center;
padding: 8px 0;
}
.color-picker-btn {
width: 44px;
height: 44px;
border-radius: 50%;
border: 3px solid rgba(255, 255, 255, 0.15);
cursor: pointer;
transition: all $transition-fast;
position: relative;
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
&:hover {
transform: scale(1.08);
border-color: rgba(255, 255, 255, 0.3);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}
&:active {
transform: scale(0.98);
}
&.active {
border-color: $active-color;
border-width: 3px;
box-shadow: 0 0 0 3px rgba(129, 140, 248, 0.25), 0 4px 12px rgba(0, 0, 0, 0.3);
.check-icon {
color: rgba(0, 0, 0, 0.7);
font-size: 18px;
font-weight: bold;
text-shadow: 0 1px 2px rgba(255, 255, 255, 0.5);
}
}
&:focus-visible {
outline: 2px solid $active-color;
outline-offset: 2px;
}
}
@@ -0,0 +1,185 @@
import {Component, EventEmitter, Inject, Input, OnInit, Output, Renderer2} from '@angular/core';
import {DecimalPipe, DOCUMENT} from '@angular/common';
import {TranslocoDirective} from '@jsverse/transloco';
import {ReaderStateService} from '../state/reader-state.service';
import {ReaderViewManagerService} from '../core/view-manager.service';
import {BookService} from '../../../book/service/book.service';
import {EbookViewerSetting} from '../../../book/model/book.model';
import {EpubCustomFontService} from '../features/fonts/custom-font.service';
interface AnnotationColor {
name: string;
value: string;
label: string;
}
@Component({
selector: 'app-settings-dialog',
standalone: true,
imports: [DecimalPipe, TranslocoDirective],
templateUrl: './settings-dialog.component.html',
styleUrls: ['./settings-dialog.component.scss']
})
export class ReaderSettingsDialogComponent implements OnInit {
@Input() stateService!: ReaderStateService;
@Input() viewManager!: ReaderViewManagerService;
@Input() bookId!: number;
@Output() close = new EventEmitter<void>();
activeTab: 'theme' | 'typography' | 'layout' = 'theme';
selectedAnnotationColor: string = '#FFFF00';
annotationColors: AnnotationColor[] = [
{name: 'yellow', value: '#FFFF00', label: 'Yellow'},
{name: 'green', value: '#90EE90', label: 'Green'},
{name: 'blue', value: '#87CEEB', label: 'Blue'},
{name: 'pink', value: '#FFB6C1', label: 'Pink'},
{name: 'orange', value: '#FFD580', label: 'Orange'}
];
constructor(
private bookService: BookService,
private customFontService: EpubCustomFontService,
private renderer: Renderer2,
@Inject(DOCUMENT) private document: Document
) {
}
ngOnInit() {
this.customFontService.injectCustomFontsStylesheet(this.renderer, this.document);
this.selectedAnnotationColor = this.getSelectedAnnotationColor();
}
getFontFamilyForPreview(fontValue: string): string {
return this.customFontService.getFontFamilyForPreview(fontValue);
}
get state() {
return this.stateService.state();
}
get themes() {
return this.stateService.themes;
}
get fonts() {
return this.stateService.fonts();
}
private syncSettingsToBackend() {
const setting: EbookViewerSetting = {
lineHeight: this.state.lineHeight,
justify: this.state.justify,
hyphenate: this.state.hyphenate,
maxColumnCount: this.state.maxColumnCount,
gap: this.state.gap,
fontSize: this.state.fontSize,
theme: typeof this.state.theme === 'object' && 'name' in this.state.theme ? this.state.theme.name : (this.state.theme as any),
maxInlineSize: this.state.maxInlineSize,
maxBlockSize: this.state.maxBlockSize,
fontFamily: this.state.fontFamily,
isDark: this.state.isDark,
flow: this.state.flow,
};
this.bookService.updateViewerSetting({ebookSettings: setting}, this.bookId).subscribe();
}
setFontFamily(value: string | null) {
this.stateService.setFontFamily(value);
this.syncSettingsToBackend();
}
increaseFontSize() {
this.stateService.updateFontSize(1);
this.syncSettingsToBackend();
}
decreaseFontSize() {
this.stateService.updateFontSize(-1);
this.syncSettingsToBackend();
}
increaseLineHeight() {
this.stateService.updateLineHeight(0.1);
this.syncSettingsToBackend();
}
decreaseLineHeight() {
this.stateService.updateLineHeight(-0.1);
this.syncSettingsToBackend();
}
increaseMaxColumnCount() {
this.stateService.updateMaxColumnCount(1);
this.syncSettingsToBackend();
}
decreaseMaxColumnCount() {
this.stateService.updateMaxColumnCount(-1);
this.syncSettingsToBackend();
}
setGap(value: number) {
const delta = value - this.state.gap;
this.stateService.updateGap(delta);
this.syncSettingsToBackend();
}
toggleJustify() {
this.stateService.toggleJustify();
this.syncSettingsToBackend();
}
toggleHyphenate() {
this.stateService.toggleHyphenate();
this.syncSettingsToBackend();
}
increaseMaxInlineSize() {
this.stateService.updateMaxInlineSize(40);
this.syncSettingsToBackend();
}
decreaseMaxInlineSize() {
this.stateService.updateMaxInlineSize(-40);
this.syncSettingsToBackend();
}
increaseMaxBlockSize() {
this.stateService.updateMaxBlockSize(60);
this.syncSettingsToBackend();
}
decreaseMaxBlockSize() {
this.stateService.updateMaxBlockSize(-60);
this.syncSettingsToBackend();
}
toggleDarkMode() {
this.stateService.toggleDarkMode();
this.syncSettingsToBackend();
}
onThemeChange(themeName: string) {
this.stateService.setThemeByName(themeName);
this.syncSettingsToBackend();
}
setFlow(flow: 'paginated' | 'scrolled') {
this.stateService.setFlow(flow);
this.viewManager.getRenderer()?.setAttribute?.('flow', flow);
this.syncSettingsToBackend();
}
setAnnotationColor(color: string): void {
this.selectedAnnotationColor = color;
localStorage.setItem('selectedAnnotationColor', color);
}
getSelectedAnnotationColor(): string {
const stored = localStorage.getItem('selectedAnnotationColor');
return stored || this.selectedAnnotationColor;
}
}
@@ -0,0 +1,42 @@
<div class="dialog-overlay" (click)="onOverlayClick($event)">
<div class="dialog">
<div class="dialog-header">
<h2>{{ 'readerEbook.shortcutsHelp.title' | transloco }}</h2>
<button class="close-btn" (click)="onClose()">
<app-reader-icon name="close" [size]="18"></app-reader-icon>
</button>
</div>
<div class="dialog-body">
@for (group of shortcutGroups; track group.title) {
<div class="shortcut-group">
<h3 class="group-title">{{ group.title }}</h3>
<div class="shortcuts-list">
@for (shortcut of group.shortcuts; track shortcut.description) {
<div class="shortcut-item">
<div class="shortcut-keys">
@for (key of shortcut.keys; track key; let last = $last) {
<kbd class="key">{{ key }}</kbd>
@if (!last) {
<span class="key-separator">+</span>
}
}
</div>
<div class="shortcut-info">
<span class="shortcut-description">{{ shortcut.description }}</span>
@if (isMobile && shortcut.mobileGesture) {
<span class="mobile-gesture">{{ shortcut.mobileGesture }}</span>
}
</div>
</div>
}
</div>
</div>
}
</div>
<div class="dialog-footer">
<button class="btn btn-primary" (click)="onClose()">{{ 'readerEbook.shortcutsHelp.gotIt' | transloco }}</button>
</div>
</div>
</div>
@@ -0,0 +1,245 @@
$dialog-bg: #1a1a1a;
$text-primary: rgba(255, 255, 255, 0.95);
$text-secondary: rgba(255, 255, 255, 0.6);
$text-muted: rgba(255, 255, 255, 0.4);
$border-color: rgba(255, 255, 255, 0.08);
$hover-bg: rgba(255, 255, 255, 0.08);
$active-color: #818cf8;
$transition-fast: 150ms ease;
$transition-normal: 200ms ease;
.dialog-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(4px);
z-index: 13000;
display: flex;
align-items: center;
justify-content: center;
animation: fadeIn $transition-normal;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.dialog {
background: $dialog-bg;
border: 1px solid $border-color;
border-radius: 12px;
width: 90%;
max-width: 480px;
max-height: 85vh;
display: flex;
flex-direction: column;
overflow: hidden;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
animation: slideUp 250ms cubic-bezier(0.4, 0, 0.2, 1);
}
@keyframes slideUp {
from {
transform: translateY(20px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.dialog-header {
padding: 16px 20px;
border-bottom: 1px solid $border-color;
display: flex;
align-items: center;
justify-content: space-between;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.02) 0%, transparent 100%);
h2 {
margin: 0;
font-size: 16px;
font-weight: 600;
color: $text-primary;
letter-spacing: -0.3px;
}
}
.close-btn {
background: none;
border: none;
color: $text-muted;
cursor: pointer;
padding: 6px;
border-radius: 6px;
transition: background $transition-fast, color $transition-fast;
line-height: 1;
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
&:hover {
background: $hover-bg;
color: $text-primary;
}
}
.dialog-body {
padding: 20px;
overflow-y: auto;
flex: 1;
display: flex;
flex-direction: column;
gap: 24px;
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.15);
border-radius: 3px;
&:hover {
background: rgba(255, 255, 255, 0.25);
}
}
}
.shortcut-group {
.group-title {
margin: 0 0 12px 0;
font-size: 11px;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 1px;
color: $text-muted;
}
}
.shortcuts-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.shortcut-item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 8px 12px;
background: rgba(255, 255, 255, 0.03);
border-radius: 8px;
transition: background $transition-fast;
&:hover {
background: rgba(255, 255, 255, 0.05);
}
}
.shortcut-keys {
display: flex;
align-items: center;
gap: 4px;
flex-shrink: 0;
}
.key {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 28px;
height: 26px;
padding: 0 8px;
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 5px;
font-family: inherit;
font-size: 12px;
font-weight: 500;
color: $text-primary;
box-shadow: 0 2px 0 rgba(0, 0, 0, 0.2);
}
.key-separator {
color: $text-muted;
font-size: 12px;
margin: 0 2px;
}
.shortcut-info {
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 2px;
text-align: right;
}
.shortcut-description {
font-size: 13px;
color: $text-secondary;
}
.mobile-gesture {
font-size: 11px;
color: $active-color;
font-style: italic;
}
.dialog-footer {
padding: 16px 20px;
border-top: 1px solid $border-color;
display: flex;
justify-content: flex-end;
background: linear-gradient(0deg, rgba(255, 255, 255, 0.02) 0%, transparent 100%);
}
.btn {
padding: 10px 24px;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: background $transition-fast, transform $transition-fast;
border: none;
&:active {
transform: scale(0.98);
}
}
.btn-primary {
background: $active-color;
color: white;
&:hover {
background: #9ba3fb;
}
}
@media (max-width: 480px) {
.dialog {
width: 95%;
max-height: 90vh;
}
.shortcut-item {
flex-direction: column;
align-items: flex-start;
gap: 8px;
}
.shortcut-info {
align-items: flex-start;
text-align: left;
}
}
@@ -0,0 +1,79 @@
import {Component, EventEmitter, inject, Output} from '@angular/core';
import {CommonModule} from '@angular/common';
import {TranslocoPipe, TranslocoService} from '@jsverse/transloco';
import {ReaderIconComponent} from '../shared/icon.component';
interface ShortcutItem {
keys: string[];
description: string;
mobileGesture?: string;
}
interface ShortcutGroup {
title: string;
shortcuts: ShortcutItem[];
}
@Component({
selector: 'app-ebook-shortcuts-help',
standalone: true,
imports: [CommonModule, TranslocoPipe, ReaderIconComponent],
templateUrl: './shortcuts-help.component.html',
styleUrls: ['./shortcuts-help.component.scss']
})
export class EbookShortcutsHelpComponent {
@Output() close = new EventEmitter<void>();
private readonly t = inject(TranslocoService);
get shortcutGroups(): ShortcutGroup[] {
return [
{
title: this.t.translate('readerEbook.shortcutsHelp.navigation'),
shortcuts: [
{keys: ['\u2190'], description: this.t.translate('readerEbook.shortcutsHelp.previousPage'), mobileGesture: this.t.translate('readerEbook.shortcutsHelp.swipeRight')},
{keys: ['\u2192'], description: this.t.translate('readerEbook.shortcutsHelp.nextPage'), mobileGesture: this.t.translate('readerEbook.shortcutsHelp.swipeLeft')},
{keys: ['Space'], description: this.t.translate('readerEbook.shortcutsHelp.nextPage')},
{keys: ['Shift', 'Space'], description: this.t.translate('readerEbook.shortcutsHelp.previousPage')},
{keys: ['Home'], description: this.t.translate('readerEbook.shortcutsHelp.firstSection')},
{keys: ['End'], description: this.t.translate('readerEbook.shortcutsHelp.lastSection')},
{keys: ['Page Up'], description: this.t.translate('readerEbook.shortcutsHelp.previousPage')},
{keys: ['Page Down'], description: this.t.translate('readerEbook.shortcutsHelp.nextPage')}
]
},
{
title: this.t.translate('readerEbook.shortcutsHelp.panels'),
shortcuts: [
{keys: ['T'], description: this.t.translate('readerEbook.shortcutsHelp.tableOfContents')},
{keys: ['S'], description: this.t.translate('readerEbook.shortcutsHelp.searchShortcut')},
{keys: ['N'], description: this.t.translate('readerEbook.shortcutsHelp.notesShortcut')}
]
},
{
title: this.t.translate('readerEbook.shortcutsHelp.display'),
shortcuts: [
{keys: ['F'], description: this.t.translate('readerEbook.shortcutsHelp.toggleFullscreen')},
{keys: ['Escape'], description: this.t.translate('readerEbook.shortcutsHelp.exitFullscreenCloseDialogs')}
]
},
{
title: this.t.translate('readerEbook.shortcutsHelp.other'),
shortcuts: [
{keys: ['?'], description: this.t.translate('readerEbook.shortcutsHelp.showHelpDialog')}
]
}
];
}
isMobile = window.innerWidth < 768;
onClose(): void {
this.close.emit();
}
onOverlayClick(event: MouseEvent): void {
if ((event.target as HTMLElement).classList.contains('dialog-overlay')) {
this.onClose();
}
}
}
@@ -0,0 +1,89 @@
<div
class="reader"
[style.background-color]="readerState().theme.bg ?? ''">
<div class="header-trigger-zone"
[class.inactive]="headerVisible"
(mouseenter)="onHeaderTriggerZoneEnter()"></div>
<div class="footer-trigger-zone"
[class.inactive]="forceNavbarVisible"
(mouseenter)="onFooterTriggerZoneEnter()"></div>
@if (isLoading) {
<div class="loader-overlay">
<div class="loader-content">
<div class="spinner"></div>
<p class="loader-text">{{ 'readerEbook.reader.loadingBook' | transloco }}</p>
</div>
</div>
}
<app-reader-header></app-reader-header>
<div class="reader-content" style="position: relative;">
@if (isCurrentCfiBookmarked()) {
<div class="bookmark-indicator">
<svg width="48" height="64" viewBox="0 0 48 64">
<polygon points="0,0 48,0 48,64 24,48 0,64" fill="red"/>
</svg>
</div>
}
<div id="foliate-container" tabindex="0"></div>
</div>
<app-reader-navbar
[progressData]="currentProgressData"
[forceVisible]="forceNavbarVisible"
[sectionFractions]="sectionFractions"
(progressChange)="onProgressChange($event)">
</app-reader-navbar>
<app-reader-sidebar></app-reader-sidebar>
<app-reader-left-sidebar></app-reader-left-sidebar>
@if (showQuickSettings) {
<app-reader-quick-settings
[stateService]="stateService"
[bookId]="bookId"
(close)="showQuickSettings = false"
(openFullSettings)="showControls = true">
</app-reader-quick-settings>
}
@if (showControls) {
<app-settings-dialog
[stateService]="stateService"
[viewManager]="viewManager"
[bookId]="bookId"
(close)="showControls = false">
</app-settings-dialog>
}
@if (showMetadata) {
<app-reader-book-metadata-dialog
[book]="book"
(close)="showMetadata = false"
></app-reader-book-metadata-dialog>
}
<app-text-selection-popup
[visible]="selectionState().visible"
[position]="selectionState().position"
[showBelow]="selectionState().showBelow"
[overlappingAnnotationId]="selectionState().overlappingAnnotationId"
[selectedText]="selectionState().selectedText"
(action)="handleSelectionAction($event)"
></app-text-selection-popup>
@if (noteDialogState().visible) {
<app-reader-note-dialog
[data]="noteDialogState().data"
(save)="onNoteSave($event)"
(cancel)="onNoteCancel()"
></app-reader-note-dialog>
}
@if (showShortcutsHelp) {
<app-ebook-shortcuts-help (close)="showShortcutsHelp = false"></app-ebook-shortcuts-help>
}
</div>
@@ -0,0 +1,159 @@
.reader {
width: 100vw;
height: 100dvh;
overflow: hidden;
position: fixed;
top: 0;
left: 0;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
}
.header-trigger-zone {
position: fixed;
top: 0;
left: 0;
right: 0;
height: 20px;
z-index: 9998;
pointer-events: auto;
&.inactive {
pointer-events: none;
}
}
.footer-trigger-zone {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 30px;
z-index: 9998;
pointer-events: auto;
&.inactive {
pointer-events: none;
}
}
.reader-content {
position: relative;
flex: 1;
overflow: hidden;
width: 100%;
height: 100%;
}
.bookmark-indicator {
position: absolute;
top: 0;
left: 12px;
z-index: 10;
width: 48px;
height: 64px;
background: none;
pointer-events: none;
}
.navigation-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 10;
cursor: pointer;
pointer-events: auto;
background: transparent;
}
#foliate-container {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
pointer-events: auto;
}
::ng-deep foliate-view {
width: 100% !important;
height: 100% !important;
display: block !important;
position: absolute !important;
top: 0 !important;
left: 0 !important;
}
.loader-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.8);
display: flex;
align-items: center;
justify-content: center;
z-index: 9999;
}
.loader-content {
display: flex;
flex-direction: column;
align-items: center;
gap: 1.5rem;
}
.spinner {
width: 48px;
height: 48px;
border: 4px solid rgba(255, 255, 255, 0.2);
border-top-color: #fff;
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
.loader-text {
color: #fff;
font-size: 1.1rem;
margin: 0;
font-weight: 500;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
foliate-view::part(head) {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 16px;
font-size: 0.875rem;
color: var(--text-secondary, #666);
border-bottom: 1px solid var(--border-color, #e0e0e0);
font-family: inherit;
min-height: 32px;
box-sizing: border-box;
}
foliate-view::part(foot) {
display: flex;
justify-content: space-between;
align-items: center;
padding: 8px 16px;
font-size: 0.875rem;
color: var(--text-secondary, #666);
border-top: 1px solid var(--border-color, #e0e0e0);
font-family: inherit;
min-height: 32px;
box-sizing: border-box;
}
@@ -0,0 +1,459 @@
import {Component, CUSTOM_ELEMENTS_SCHEMA, effect, HostListener, inject, OnDestroy, OnInit} from '@angular/core';
import {CommonModule} from '@angular/common';
import {from, Observable, of, Subject, throwError} from 'rxjs';
import {catchError, map, switchMap, takeUntil, tap} from 'rxjs/operators';
import {MessageService} from 'primeng/api';
import {ReaderLoaderService} from './core/loader.service';
import {ReaderViewManagerService} from './core/view-manager.service';
import {ReaderStateService} from './state/reader-state.service';
import {ReaderStyleService} from './core/style.service';
import {ReaderBookmarkService} from './features/bookmarks/bookmark.service';
import {ReaderAnnotationHttpService} from './features/annotations/annotation.service';
import {ReaderProgressService} from './state/progress.service';
import {ReaderSelectionService} from './features/selection/selection.service';
import {ReaderSidebarService} from './layout/sidebar/sidebar.service';
import {ReaderLeftSidebarService} from './layout/panel/panel.service';
import {ReaderHeaderService} from './layout/header/header.service';
import {ReaderNoteService} from './features/notes/note.service';
import {BookService} from '../../book/service/book.service';
import {BookFileService} from '../../book/service/book-file.service';
import {ActivatedRoute} from '@angular/router';
import {Book, BookType} from '../../book/model/book.model';
import {ReaderHeaderComponent} from './layout/header/header.component';
import {ReaderSidebarComponent} from './layout/sidebar/sidebar.component';
import {ReaderLeftSidebarComponent} from './layout/panel/panel.component';
import {ReaderNavbarComponent} from './layout/footer/footer.component';
import {ReaderSettingsDialogComponent} from './dialogs/settings-dialog.component';
import {ReaderQuickSettingsComponent} from './layout/header/quick-settings.component';
import {ReaderBookMetadataDialogComponent} from './dialogs/metadata-dialog.component';
import {ReaderHeaderFooterVisibilityManager} from './shared/visibility.util';
import {EpubCustomFontService} from './features/fonts/custom-font.service';
import {TextSelectionAction, TextSelectionPopupComponent} from './shared/selection-popup.component';
import {NoteDialogResult, ReaderNoteDialogComponent} from './dialogs/note-dialog.component';
import {EbookShortcutsHelpComponent} from './dialogs/shortcuts-help.component';
import {TranslocoPipe} from '@jsverse/transloco';
@Component({
selector: 'app-ebook-reader',
standalone: true,
imports: [
CommonModule,
ReaderHeaderComponent,
ReaderSettingsDialogComponent,
ReaderQuickSettingsComponent,
ReaderBookMetadataDialogComponent,
ReaderSidebarComponent,
ReaderLeftSidebarComponent,
ReaderNavbarComponent,
TextSelectionPopupComponent,
ReaderNoteDialogComponent,
EbookShortcutsHelpComponent,
TranslocoPipe
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
providers: [
MessageService,
ReaderLoaderService,
ReaderViewManagerService,
ReaderStateService,
ReaderStyleService,
ReaderBookmarkService,
ReaderAnnotationHttpService,
ReaderProgressService,
ReaderSelectionService,
ReaderSidebarService,
ReaderLeftSidebarService,
ReaderHeaderService,
ReaderNoteService
],
templateUrl: './ebook-reader.component.html',
styleUrls: ['./ebook-reader.component.scss']
})
export class EbookReaderComponent implements OnInit, OnDestroy {
private destroy$ = new Subject<void>();
private loaderService = inject(ReaderLoaderService);
private styleService = inject(ReaderStyleService);
private bookService = inject(BookService);
private bookFileService = inject(BookFileService);
private route = inject(ActivatedRoute);
private epubCustomFontService = inject(EpubCustomFontService);
private annotationService = inject(ReaderAnnotationHttpService);
private progressService = inject(ReaderProgressService);
private selectionService = inject(ReaderSelectionService);
private headerService = inject(ReaderHeaderService);
private noteService = inject(ReaderNoteService);
public sidebarService = inject(ReaderSidebarService);
public leftSidebarService = inject(ReaderLeftSidebarService);
public viewManager = inject(ReaderViewManagerService);
public stateService = inject(ReaderStateService);
protected bookId!: number;
protected altBookType?: string;
private hasLoadedOnce = false;
private _fileUrl: string | null = null;
private visibilityManager!: ReaderHeaderFooterVisibilityManager;
private relocateTimeout: any;
private sectionFractionsTimeout: any;
isLoading = true;
showQuickSettings = false;
showControls = false;
showMetadata = false;
forceNavbarVisible = false;
headerVisible = false;
book: Book | null = null;
sectionFractions: number[] = [];
isFullscreen = false;
showShortcutsHelp = false;
readonly readerState = this.stateService.state;
readonly selectionState = this.selectionService.state;
readonly noteDialogState = this.noteService.dialogState;
readonly isCurrentCfiBookmarked = this.headerService.isCurrentCfiBookmarked;
constructor() {
effect(() => {
this.stateService.state();
this.applyStyles();
});
effect(
() => {
this.sidebarService.bookmarks();
this.updateBookmarkIndicator();
},
{allowSignalWrites: true}
);
}
get currentProgressData(): any {
return this.progressService.currentProgressData;
}
ngOnInit() {
this.visibilityManager = new ReaderHeaderFooterVisibilityManager(window.innerHeight);
this.visibilityManager.onStateChange((state) => {
this.headerVisible = state.headerVisible;
this.headerService.setForceVisible(state.headerVisible);
this.forceNavbarVisible = state.footerVisible;
});
this.sidebarService.showMetadata$
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.showMetadata = true);
this.headerService.showControls$
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.showQuickSettings = true);
this.headerService.showMetadata$
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.showMetadata = true);
this.headerService.toggleFullscreen$
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.toggleFullscreen());
this.headerService.showShortcutsHelp$
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.showShortcutsHelp = true);
this.isLoading = true;
this.initializeFoliate().pipe(
switchMap(() => this.epubCustomFontService.loadAndCacheFonts()),
tap(() => this.stateService.refreshCustomFonts()),
switchMap(() => this.setupView()),
tap(() => {
this.subscribeToViewEvents();
}),
switchMap(() => this.loadBookFromAPI()),
tap(() => this.isLoading = false),
catchError(() => {
this.isLoading = false;
return of(null);
}),
takeUntil(this.destroy$)
).subscribe();
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
this.viewManager.destroy();
this.annotationService.reset();
this.progressService.endSession();
this.progressService.reset();
this.selectionService.reset();
this.sidebarService.reset();
this.leftSidebarService.reset();
this.headerService.reset();
this.noteService.reset();
this.epubCustomFontService.cleanup();
if (this._fileUrl) {
URL.revokeObjectURL(this._fileUrl);
this._fileUrl = null;
}
}
private initializeFoliate(): Observable<void> {
return this.loaderService.loadFoliateScript().pipe(
switchMap(() => this.loaderService.waitForCustomElement())
);
}
private setupView(): Observable<void> {
const container = document.getElementById('foliate-container');
if (!container) {
return throwError(() => new Error('Container not found'));
}
container.setAttribute('tabindex', '0');
this.viewManager.createView(container);
return of(undefined);
}
private loadBookFromAPI(): Observable<void> {
this.bookId = +this.route.snapshot.paramMap.get('bookId')!;
this.altBookType = this.route.snapshot.queryParamMap.get('bookType') ?? undefined;
return from(this.bookService.ensureBookDetail(this.bookId, false)).pipe(
switchMap((book) => {
this.book = book;
// Use alternative bookType from query param if provided, otherwise use primary
const bookType = (this.altBookType as BookType | undefined) ?? book.primaryFile?.bookType;
if (!bookType) {
return throwError(() => new Error('Book type not found'));
}
// Determine which file ID to use for progress tracking
let bookFileId: number | undefined;
if (this.altBookType) {
// Look for the alternative format file with matching type
const altFile = book.alternativeFormats?.find(f => f.bookType === this.altBookType);
bookFileId = altFile?.id;
} else {
// Use the primary file
bookFileId = book.primaryFile?.id;
}
return this.stateService.initializeState(this.bookId, bookFileId!).pipe(
map(() => ({book, bookType, bookFileId}))
);
}),
switchMap(({book, bookType, bookFileId}) => {
this.progressService.initialize(this.bookId, bookType, bookFileId);
this.selectionService.initialize(this.bookId, this.destroy$);
this.headerService.initialize(this.bookId, book.metadata?.title || '');
// Use streaming for EPUB if query param is set, blob loading otherwise (default)
const useStreaming = this.route.snapshot.queryParamMap.get('streaming') === 'true';
const loadBook$ = bookType === 'EPUB' && useStreaming
? this.viewManager.loadEpubStreaming(this.bookId, this.altBookType)
: this.loadBookBlob();
return loadBook$.pipe(
tap(() => {
this.applyStyles();
this.sidebarService.initialize(this.bookId, book, this.destroy$);
this.leftSidebarService.initialize(this.bookId, this.destroy$);
this.noteService.initialize(this.bookId, this.destroy$);
}),
switchMap(() => this.viewManager.getMetadata()),
switchMap(() => {
if (!this.hasLoadedOnce) {
this.hasLoadedOnce = true;
// Navigate to saved position if progress exists, otherwise go to first page
if (book.epubProgress?.cfi) {
return this.viewManager.goTo(book.epubProgress.cfi);
} else if (book.epubProgress?.percentage && book.epubProgress.percentage > 0) {
return this.viewManager.goToFraction(book.epubProgress.percentage / 100);
} else {
return this.viewManager.goTo(0);
}
}
return of(undefined);
})
);
})
);
}
private loadBookBlob(): Observable<void> {
return this.bookFileService.getFileContent(this.bookId, this.altBookType).pipe(
switchMap(fileBlob => {
const fileUrl = URL.createObjectURL(fileBlob);
this._fileUrl = fileUrl;
return this.viewManager.loadEpub(fileUrl);
})
);
}
private subscribeToViewEvents(): void {
this.viewManager.events$
.pipe(takeUntil(this.destroy$))
.subscribe(event => {
switch (event.type) {
case 'load':
this.applyStyles();
this.sidebarService.updateChapters();
this.updateSectionFractions();
break;
case 'relocate':
if (this.relocateTimeout) clearTimeout(this.relocateTimeout);
this.relocateTimeout = setTimeout(() => {
this.progressService.handleRelocateEvent(event.detail);
this.updateBookmarkIndicator();
}, 100);
if (this.sectionFractionsTimeout) clearTimeout(this.sectionFractionsTimeout);
this.sectionFractionsTimeout = setTimeout(() => {
this.updateSectionFractions();
}, 500);
break;
case 'middle-single-tap':
this.toggleHeaderNavbarPinned();
break;
case 'text-selected':
this.selectionService.handleTextSelected(event.detail, event.popupPosition);
break;
case 'toggle-fullscreen':
this.toggleFullscreen();
break;
case 'toggle-shortcuts-help':
this.showShortcutsHelp = !this.showShortcutsHelp;
break;
case 'go-first-section':
this.viewManager.goToSection(0).subscribe();
break;
case 'go-last-section': {
const s = this.progressService.currentProgressData?.section;
if (s && s.total > 0) {
this.viewManager.goToSection(s.total - 1).subscribe();
}
break;
}
case 'toggle-toc':
this.sidebarService.toggle('chapters');
break;
case 'toggle-search':
this.leftSidebarService.toggle('search');
break;
case 'toggle-notes':
this.leftSidebarService.toggle('notes');
break;
case 'escape-pressed':
if (this.showShortcutsHelp) {
this.showShortcutsHelp = false;
} else if (this.noteDialogState().visible) {
this.noteService.closeDialog();
} else if (this.showControls) {
this.showControls = false;
} else if (this.showQuickSettings) {
this.showQuickSettings = false;
} else if (this.showMetadata) {
this.showMetadata = false;
} else if (this.isFullscreen) {
this.exitFullscreen();
}
break;
}
});
}
private updateSectionFractions(): void {
this.sectionFractions = this.viewManager.getSectionFractions();
}
private updateBookmarkIndicator(): void {
const currentCfi = this.progressService.currentCfi;
const isBookmarked = currentCfi
? this.sidebarService.bookmarks().some(bookmark => bookmark.cfi === currentCfi)
: false;
this.headerService.setCurrentCfiBookmarked(isBookmarked);
}
private applyStyles(): void {
const renderer = this.viewManager.getRenderer();
if (renderer) {
const state = this.stateService.state();
this.styleService.applyStylesToRenderer(renderer, state);
if (state.flow) {
renderer.setAttribute?.('flow', state.flow);
}
}
}
@HostListener('document:fullscreenchange')
onFullscreenChange(): void {
this.isFullscreen = !!document.fullscreenElement;
this.headerService.setFullscreen(this.isFullscreen);
}
toggleFullscreen(): void {
if (document.fullscreenElement) {
this.exitFullscreen();
} else {
this.enterFullscreen();
}
}
private enterFullscreen(): void {
document.documentElement.requestFullscreen?.();
}
private exitFullscreen(): void {
document.exitFullscreen?.();
}
onProgressChange(fraction: number): void {
this.viewManager.goToFraction(fraction)
.pipe(takeUntil(this.destroy$))
.subscribe();
}
private toggleHeaderNavbarPinned(): void {
this.visibilityManager.togglePinned();
}
@HostListener('document:mousemove', ['$event'])
onMouseMove(event: MouseEvent): void {
this.visibilityManager.handleMouseMove(event.clientY);
}
@HostListener('document:mouseleave', ['$event'])
onMouseLeave(event: MouseEvent): void {
this.visibilityManager.handleMouseLeave();
}
@HostListener('window:resize', ['$event'])
onWindowResize(event: Event): void {
this.visibilityManager.updateWindowHeight(window.innerHeight);
}
onHeaderTriggerZoneEnter(): void {
this.visibilityManager.handleHeaderZoneEnter();
}
onFooterTriggerZoneEnter(): void {
this.visibilityManager.handleFooterZoneEnter();
}
handleSelectionAction(action: TextSelectionAction): void {
if (action.type === 'note') {
this.noteService.openNewNoteDialog();
} else {
this.selectionService.handleAction(action);
}
}
onNoteSave(result: NoteDialogResult): void {
this.noteService.saveNote(result);
}
onNoteCancel(): void {
this.noteService.closeDialog();
}
}
@@ -0,0 +1,160 @@
import {Injectable} from '@angular/core';
import {defer, from, Observable, of} from 'rxjs';
import {AnnotationStyle} from '../../../../../shared/service/annotation.service';
export type {AnnotationStyle};
export interface Annotation {
value: string;
color?: string;
style?: AnnotationStyle;
}
@Injectable({
providedIn: 'root'
})
export class ReaderAnnotationService {
private annotationStyles = new Map<string, { color: string; style: AnnotationStyle }>();
private allAnnotations: Annotation[] = [];
addAnnotation(view: any, annotation: Annotation): Observable<{ index: number; label: string } | undefined> {
if (!view) return of(undefined);
const style = annotation.style || 'highlight';
const color = annotation.color || '#FACC15';
this.annotationStyles.set(annotation.value, {color, style});
const existingIndex = this.allAnnotations.findIndex(a => a.value === annotation.value);
if (existingIndex >= 0) {
this.allAnnotations[existingIndex] = annotation;
} else {
this.allAnnotations.push(annotation);
}
return defer(() => from(view.addAnnotation({value: annotation.value}) as Promise<{ index: number; label: string } | undefined>));
}
deleteAnnotation(view: any, cfi: string): Observable<void> {
if (!view) return of(undefined);
this.annotationStyles.delete(cfi);
this.allAnnotations = this.allAnnotations.filter(a => a.value !== cfi);
return defer(() => from(view.deleteAnnotation({value: cfi}) as Promise<void>));
}
showAnnotation(view: any, cfi: string): Observable<void> {
if (!view) return of(undefined);
return defer(() => from(view.showAnnotation({value: cfi}) as Promise<void>));
}
addAnnotations(view: any, annotations: Annotation[]): void {
annotations.forEach(annotation => {
const style = annotation.style || 'highlight';
const color = annotation.color || '#FACC15';
this.annotationStyles.set(annotation.value, {color, style});
const existingIndex = this.allAnnotations.findIndex(a => a.value === annotation.value);
if (existingIndex >= 0) {
this.allAnnotations[existingIndex] = annotation;
} else {
this.allAnnotations.push(annotation);
}
view?.addAnnotation({value: annotation.value});
});
}
getAnnotationStyle(cfi: string): { color: string; style: AnnotationStyle } | undefined {
return this.annotationStyles.get(cfi);
}
getOverlayerDrawFunction(style: AnnotationStyle): (rects: DOMRectList, options: { color?: string }) => SVGElement {
const createSVGElement = (tag: string): SVGElement =>
document.createElementNS('http://www.w3.org/2000/svg', tag);
switch (style) {
case 'underline':
return (rects: DOMRectList, options: { color?: string; width?: number } = {}) => {
const {color = 'red', width: strokeWidth = 2} = options;
const g = createSVGElement('g');
g.setAttribute('fill', color);
for (const {left, bottom, width} of Array.from(rects)) {
const el = createSVGElement('rect');
el.setAttribute('x', String(left));
el.setAttribute('y', String(bottom - strokeWidth));
el.setAttribute('height', String(strokeWidth));
el.setAttribute('width', String(width));
g.append(el);
}
return g;
};
case 'strikethrough':
return (rects: DOMRectList, options: { color?: string; width?: number } = {}) => {
const {color = 'red', width: strokeWidth = 2} = options;
const g = createSVGElement('g');
g.setAttribute('fill', color);
for (const {left, top, bottom, width} of Array.from(rects)) {
const el = createSVGElement('rect');
el.setAttribute('x', String(left));
el.setAttribute('y', String((top + bottom) / 2));
el.setAttribute('height', String(strokeWidth));
el.setAttribute('width', String(width));
g.append(el);
}
return g;
};
case 'squiggly':
return (rects: DOMRectList, options: { color?: string; width?: number } = {}) => {
const {color = 'red', width: strokeWidth = 2} = options;
const g = createSVGElement('g');
g.setAttribute('fill', 'none');
g.setAttribute('stroke', color);
g.setAttribute('stroke-width', String(strokeWidth));
const block = strokeWidth * 1.5;
for (const {left, bottom, width} of Array.from(rects)) {
const el = createSVGElement('path');
const n = Math.round(width / block / 1.5);
const inline = width / n;
const ls = Array.from({length: n}, (_, i) =>
`l${inline} ${i % 2 ? block : -block}`).join('');
el.setAttribute('d', `M${left} ${bottom}${ls}`);
g.append(el);
}
return g;
};
case 'highlight':
default:
return (rects: DOMRectList, options: { color?: string } = {}) => {
const {color = 'yellow'} = options;
const g = createSVGElement('g');
g.setAttribute('fill', color);
(g as SVGElement).style.opacity = 'var(--overlayer-highlight-opacity, .3)';
(g as SVGElement).style.mixBlendMode = 'var(--overlayer-highlight-blend-mode, multiply)';
for (const {left, top, height, width} of Array.from(rects)) {
const el = createSVGElement('rect');
el.setAttribute('x', String(left));
el.setAttribute('y', String(top));
el.setAttribute('height', String(height));
el.setAttribute('width', String(width));
g.append(el);
}
return g;
};
}
}
getAllAnnotations(): Annotation[] {
return [...this.allAnnotations];
}
resetAnnotations(): void {
this.annotationStyles.clear();
this.allAnnotations = [];
}
}
@@ -0,0 +1,134 @@
import {inject, Injectable} from '@angular/core';
import {Observable, of} from 'rxjs';
import {catchError, map, tap} from 'rxjs/operators';
import {MessageService} from 'primeng/api';
import {TranslocoService} from '@jsverse/transloco';
import {
Annotation,
AnnotationService,
AnnotationStyle,
CreateAnnotationRequest
} from '../../../../../shared/service/annotation.service';
import {Annotation as ViewAnnotation, ReaderAnnotationService} from './annotation-renderer.service';
@Injectable()
export class ReaderAnnotationHttpService {
private annotationService = inject(AnnotationService);
private messageService = inject(MessageService);
private readonly t = inject(TranslocoService);
private readerAnnotationService = inject(ReaderAnnotationService);
private currentChapterTitle: string | null = null;
updateCurrentChapter(chapterTitle: string): void {
this.currentChapterTitle = chapterTitle;
}
createAnnotation(
bookId: number,
cfi: string,
text: string,
color: string = '#FACC15',
style: AnnotationStyle = 'highlight',
note?: string
): Observable<Annotation | null> {
const request: CreateAnnotationRequest = {
bookId,
cfi,
text,
color,
style,
note,
chapterTitle: this.currentChapterTitle || undefined
};
return this.annotationService.createAnnotation(request).pipe(
tap(() => {
this.messageService.add({
severity: 'success',
summary: this.t.translate('readerEbook.toast.highlightAddedSummary'),
detail: this.t.translate('readerEbook.toast.highlightAddedDetail')
});
}),
catchError(error => {
const isDuplicate = error?.status === 409;
this.messageService.add(
isDuplicate
? {
severity: 'warn',
summary: this.t.translate('readerEbook.toast.highlightExistsSummary'),
detail: this.t.translate('readerEbook.toast.highlightExistsDetail')
}
: {
severity: 'error',
summary: this.t.translate('readerEbook.toast.highlightFailedSummary'),
detail: this.t.translate('readerEbook.toast.highlightFailedDetail')
}
);
return of(null);
})
);
}
getAnnotations(bookId: number): Observable<Annotation[]> {
return this.annotationService.getAnnotationsForBook(bookId).pipe(
catchError(() => {
return of([]);
})
);
}
deleteAnnotation(annotationId: number): Observable<boolean> {
return this.annotationService.deleteAnnotation(annotationId).pipe(
map(() => {
this.messageService.add({
severity: 'success',
summary: this.t.translate('readerEbook.toast.highlightRemovedSummary'),
detail: this.t.translate('readerEbook.toast.highlightRemovedDetail')
});
return true;
}),
catchError(() => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('readerEbook.toast.highlightRemoveFailedSummary'),
detail: this.t.translate('readerEbook.toast.highlightRemoveFailedDetail')
});
return of(false);
})
);
}
updateAnnotationNote(annotationId: number, note: string): Observable<Annotation | null> {
return this.annotationService.updateAnnotation(annotationId, {note}).pipe(
tap(() => {
this.messageService.add({
severity: 'success',
summary: this.t.translate('readerEbook.toast.noteAnnotationUpdatedSummary'),
detail: this.t.translate('readerEbook.toast.noteAnnotationUpdatedDetail')
});
}),
catchError(() => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('readerEbook.toast.noteAnnotationUpdateFailedSummary'),
detail: this.t.translate('readerEbook.toast.noteAnnotationUpdateFailedDetail')
});
return of(null);
})
);
}
toViewAnnotations(annotations: Annotation[]): ViewAnnotation[] {
return annotations.map(a => ({
value: a.cfi,
color: a.color,
style: a.style
}));
}
reset(): void {
this.currentChapterTitle = null;
this.readerAnnotationService.resetAnnotations();
}
}
@@ -0,0 +1,66 @@
import {inject, Injectable} from '@angular/core';
import {Observable, of} from 'rxjs';
import {catchError, map} from 'rxjs/operators';
import {BookMarkService} from '../../../../../shared/service/book-mark.service';
import {MessageService} from 'primeng/api';
import {TranslocoService} from '@jsverse/transloco';
@Injectable()
export class ReaderBookmarkService {
private currentCFI: string | null = null;
private currentChapterName: string | null = null;
private bookMarkService = inject(BookMarkService);
private messageService = inject(MessageService);
private readonly t = inject(TranslocoService);
updateCurrentPosition(cfi: string, chapterName?: string): void {
this.currentCFI = cfi;
if (chapterName) {
this.currentChapterName = chapterName;
}
}
createBookmarkAtCurrentPosition(bookId: number): Observable<boolean> {
const cfi = this.currentCFI;
if (!cfi) {
return of(false);
}
const title = this.currentChapterName || 'Bookmark';
return this.bookMarkService.createBookmark({bookId, cfi, title}).pipe(
map(() => {
this.messageService.add({
severity: 'success',
summary: this.t.translate('readerEbook.toast.bookmarkAddedSummary'),
detail: this.t.translate('readerEbook.toast.bookmarkAddedDetail')
});
return true;
}),
catchError(error => {
const isDuplicate = error?.status === 409;
this.messageService.add(
isDuplicate
? {
severity: 'warn',
summary: this.t.translate('readerEbook.toast.bookmarkExistsSummary'),
detail: this.t.translate('readerEbook.toast.bookmarkExistsDetail')
}
: {
severity: 'error',
summary: this.t.translate('readerEbook.toast.bookmarkFailedSummary'),
detail: this.t.translate('readerEbook.toast.bookmarkFailedDetail')
}
);
return of(false);
})
);
}
reset(): void {
this.currentCFI = null;
this.currentChapterName = null;
}
}
@@ -0,0 +1,123 @@
import {Injectable, inject} from '@angular/core';
import {CustomFontService} from '../../../../../shared/service/custom-font.service';
import {CustomFont} from '../../../../../shared/model/custom-font.model';
import {Observable, forkJoin, of, from} from 'rxjs';
import {map, switchMap, tap, catchError} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class EpubCustomFontService {
private customFontService = inject(CustomFontService);
private customFonts: CustomFont[] = [];
private customFontBlobUrls = new Map<number, string>();
loadAndCacheFonts(): Observable<CustomFont[]> {
return from(this.customFontService.ensureFonts()).pipe(
tap(fonts => this.customFonts = fonts),
switchMap(fonts =>
from(this.customFontService.loadAllFonts(fonts)).pipe(
switchMap(() => this.cacheCustomFontsAsBlobs(fonts)),
map(() => fonts)
)
),
catchError(() => of([]))
);
}
private cacheCustomFontsAsBlobs(fonts: CustomFont[]): Observable<void> {
if (fonts.length === 0) {
return of(undefined);
}
const requests = fonts.map(font =>
this.cacheSingleFont(font).pipe(
catchError(() => of(undefined))
)
);
return forkJoin(requests).pipe(map(() => undefined));
}
private cacheSingleFont(font: CustomFont): Observable<void> {
const fontUrl = this.customFontService.getFontUrl(font.id);
const fontUrlWithToken = this.customFontService.appendToken(fontUrl);
return from(fetch(fontUrlWithToken)).pipe(
switchMap(response => from(response.blob())),
tap(blob => {
const blobUrl = URL.createObjectURL(blob);
this.customFontBlobUrls.set(font.id, blobUrl);
}),
map(() => undefined)
);
}
getBlobUrl(fontId: number): string | undefined {
return this.customFontBlobUrls.get(fontId);
}
getCustomFonts(): CustomFont[] {
return this.customFonts;
}
getCustomFontById(fontId: number): CustomFont | undefined {
return this.customFonts.find(f => f.id === fontId);
}
cleanup(): void {
this.customFontBlobUrls.forEach(url => URL.revokeObjectURL(url));
this.customFontBlobUrls.clear();
}
sanitizeFontName(fontName: string): string {
return fontName.replace(/\.(ttf|otf|woff|woff2)$/i, '').replace(/["'()]/g, '').replace(/\s+/g, '-');
}
getFontFamilyForPreview(fontValue: string): string {
if (fontValue.startsWith('custom:')) {
const id = parseInt(fontValue.substring(7), 10);
if (!isNaN(id)) {
const customFont = this.getCustomFontById(id);
if (customFont) {
return `"${this.sanitizeFontName(customFont.fontName)}", sans-serif`;
}
}
}
return fontValue;
}
generateCustomFontsStylesheet(): string {
const customFonts = this.getCustomFonts();
if (customFonts.length === 0) return '';
let css = '';
customFonts.forEach(font => {
const blobUrl = this.getBlobUrl(font.id);
if (blobUrl) {
const sanitizedName = this.sanitizeFontName(font.fontName);
css += `
@font-face {
font-family: "${sanitizedName}";
src: url("${blobUrl}") format("truetype");
font-weight: normal;
font-style: normal;
font-display: swap;
}
`;
}
});
return css;
}
injectCustomFontsStylesheet(renderer: any, document: Document): void {
const css = this.generateCustomFontsStylesheet();
if (css) {
const styleEl = renderer.createElement('style');
styleEl.textContent = css;
renderer.appendChild(document.head, styleEl);
}
}
}
@@ -0,0 +1,162 @@
import {inject, Injectable, signal} from '@angular/core';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {MessageService} from 'primeng/api';
import {TranslocoService} from '@jsverse/transloco';
import {BookNoteV2Service, CreateBookNoteV2Request, UpdateBookNoteV2Request} from '../../../../../shared/service/book-note-v2.service';
import {NoteDialogData, NoteDialogResult} from '../../dialogs/note-dialog.component';
import {ReaderSelectionService} from '../selection/selection.service';
import {ReaderProgressService} from '../../state/progress.service';
import {ReaderLeftSidebarService} from '../../layout/panel/panel.service';
import {ReaderViewManagerService} from '../../core/view-manager.service';
export interface NoteDialogState {
visible: boolean;
data: NoteDialogData | null;
}
@Injectable()
export class ReaderNoteService {
private bookNoteV2Service = inject(BookNoteV2Service);
private messageService = inject(MessageService);
private readonly t = inject(TranslocoService);
private selectionService = inject(ReaderSelectionService);
private progressService = inject(ReaderProgressService);
private leftSidebarService = inject(ReaderLeftSidebarService);
private viewManager = inject(ReaderViewManagerService);
private bookId!: number;
private destroy$ = new Subject<void>();
private readonly _dialogState = signal<NoteDialogState>({
visible: false,
data: null
});
readonly dialogState = this._dialogState.asReadonly();
initialize(bookId: number, destroy$: Subject<void>): void {
this.bookId = bookId;
this.destroy$ = destroy$;
this.leftSidebarService.editNote$
.pipe(takeUntil(this.destroy$))
.subscribe(note => {
this.openEditDialog({
cfi: note.cfi,
selectedText: note.selectedText,
chapterTitle: note.chapterTitle,
noteId: note.id,
noteContent: note.noteContent,
color: note.color
});
});
}
openNewNoteDialog(): void {
const selectionData = this.selectionService.getCurrentSelection();
if (selectionData) {
this._dialogState.set({
visible: true,
data: {
cfi: selectionData.cfi,
selectedText: selectionData.text,
chapterTitle: this.progressService.currentChapterName || undefined
}
});
this.selectionService.hidePopup();
}
}
openEditDialog(data: NoteDialogData): void {
this._dialogState.set({
visible: true,
data
});
}
saveNote(result: NoteDialogResult): void {
const data = this._dialogState().data;
if (!data) return;
if (data.noteId) {
this.updateNote(data.noteId, result);
} else {
this.createNote(data, result);
}
}
private createNote(data: NoteDialogData, result: NoteDialogResult): void {
const createRequest: CreateBookNoteV2Request = {
bookId: this.bookId,
cfi: data.cfi,
selectedText: data.selectedText,
noteContent: result.noteContent,
color: result.color,
chapterTitle: data.chapterTitle
};
this.bookNoteV2Service.createNote(createRequest)
.pipe(takeUntil(this.destroy$))
.subscribe({
next: () => {
this.closeDialog();
this.viewManager.clearSelection();
this.leftSidebarService.refreshNotes();
this.messageService.add({
severity: 'success',
summary: this.t.translate('readerEbook.toast.noteSavedSummary'),
detail: this.t.translate('readerEbook.toast.noteSavedDetail')
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('readerEbook.toast.saveFailedSummary'),
detail: this.t.translate('readerEbook.toast.saveFailedDetail')
});
}
});
}
private updateNote(noteId: number, result: NoteDialogResult): void {
const updateRequest: UpdateBookNoteV2Request = {
noteContent: result.noteContent,
color: result.color
};
this.bookNoteV2Service.updateNote(noteId, updateRequest)
.pipe(takeUntil(this.destroy$))
.subscribe({
next: () => {
this.closeDialog();
this.leftSidebarService.refreshNotes();
this.messageService.add({
severity: 'success',
summary: this.t.translate('readerEbook.toast.noteUpdatedSummary'),
detail: this.t.translate('readerEbook.toast.noteUpdatedDetail')
});
},
error: () => {
this.messageService.add({
severity: 'error',
summary: this.t.translate('readerEbook.toast.updateFailedSummary'),
detail: this.t.translate('readerEbook.toast.updateFailedDetail')
});
}
});
}
closeDialog(): void {
this._dialogState.set({
visible: false,
data: null
});
}
reset(): void {
this._dialogState.set({
visible: false,
data: null
});
}
}
@@ -0,0 +1,313 @@
import {inject, Injectable, signal} from '@angular/core';
import {Subject} from 'rxjs';
import {switchMap, takeUntil, tap} from 'rxjs/operators';
import {of} from 'rxjs';
import {Annotation} from '../../../../../shared/service/annotation.service';
import {ReaderViewManagerService} from '../../core/view-manager.service';
import {ReaderAnnotationHttpService} from '../annotations/annotation.service';
import {ReaderLeftSidebarService} from '../../layout/panel/panel.service';
import {TextSelectionAction, AnnotationStyle} from '../../shared/selection-popup.component';
export interface SelectionState {
visible: boolean;
position: { x: number; y: number };
showBelow: boolean;
overlappingAnnotationId: number | null;
selectedText: string;
}
export interface SelectionDetail {
text: string;
cfi: string;
range: Range;
index: number;
}
@Injectable()
export class ReaderSelectionService {
private viewManager = inject(ReaderViewManagerService);
private annotationService = inject(ReaderAnnotationHttpService);
private leftSidebarService = inject(ReaderLeftSidebarService);
private bookId!: number;
private annotations: Annotation[] = [];
private currentSelection: SelectionDetail | null = null;
private destroy$ = new Subject<void>();
private _visible = false;
private _position = { x: 0, y: 0 };
private _showBelow = false;
private _overlappingAnnotationId: number | null = null;
private previewCfi: string | null = null;
private previewColor: string | null = null;
private previewStyle: AnnotationStyle | null = null;
private readonly defaultState: SelectionState = {
visible: false,
position: {x: 0, y: 0},
showBelow: false,
overlappingAnnotationId: null,
selectedText: ''
};
private readonly _state = signal<SelectionState>(this.defaultState);
readonly state = this._state.asReadonly();
private annotationsChangedSubject = new Subject<Annotation[]>();
public annotationsChanged$ = this.annotationsChangedSubject.asObservable();
initialize(bookId: number, destroy$: Subject<void>): void {
this.bookId = bookId;
this.destroy$ = destroy$;
}
setAnnotations(annotations: Annotation[]): void {
this.annotations = annotations;
}
handleTextSelected(detail: SelectionDetail, popupPosition?: { x: number; y: number; showBelow?: boolean }): void {
this.currentSelection = detail;
this._overlappingAnnotationId = this.findOverlappingAnnotation(detail.cfi);
this._visible = true;
this._position = popupPosition || { x: 0, y: 0 };
this._showBelow = popupPosition?.showBelow || false;
this.emitState();
}
handleAction(action: TextSelectionAction): void {
if (action.type === 'preview' && this.currentSelection) {
this.updatePreview(
this.currentSelection.cfi,
action.color || '#FFFF00',
action.style || 'highlight'
);
return;
}
this._visible = false;
this._overlappingAnnotationId = null;
if (action.type === 'dismiss') {
this.clearPreview();
this.viewManager.clearSelection();
this.currentSelection = null;
this.emitState();
return;
}
if (action.type === 'select') {
this.clearPreview();
if (this.currentSelection?.text) {
navigator.clipboard.writeText(this.currentSelection.text);
}
this.viewManager.clearSelection();
this.emitState();
} else if (action.type === 'search' && action.searchText) {
this.clearPreview();
this.viewManager.clearSelection();
this.leftSidebarService.openWithSearch(action.searchText);
this.emitState();
} else if (action.type === 'delete' && action.annotationId) {
this.clearPreview();
this.deleteAnnotation(action.annotationId);
this.viewManager.clearSelection();
} else if (action.type === 'annotate' && this.currentSelection) {
this.clearPreview();
this.createAnnotation(
this.currentSelection.text,
this.currentSelection.cfi,
action.color || '#FFFF00',
action.style || 'highlight'
);
}
this.currentSelection = null;
this.emitState();
}
private updatePreview(cfi: string, color: string, style: AnnotationStyle): void {
if (this.previewCfi) {
this.viewManager.deleteAnnotation(this.previewCfi)
.pipe(takeUntil(this.destroy$))
.subscribe();
}
this.previewCfi = cfi;
this.previewColor = color;
this.previewStyle = style;
this.viewManager.addAnnotation({
value: cfi,
color: color,
style: style
}).pipe(takeUntil(this.destroy$)).subscribe();
}
private clearPreview(): void {
if (this.previewCfi) {
this.viewManager.deleteAnnotation(this.previewCfi)
.pipe(takeUntil(this.destroy$))
.subscribe();
this.previewCfi = null;
this.previewColor = null;
this.previewStyle = null;
}
}
private createAnnotation(text: string, cfi: string, color: string, style: AnnotationStyle): void {
this.annotationService.createAnnotation(
this.bookId,
cfi,
text,
color,
style
).pipe(
switchMap(savedAnnotation => {
if (!savedAnnotation) return of(null);
this.annotations = [...this.annotations, savedAnnotation];
this.annotationsChangedSubject.next(this.annotations);
return this.viewManager.addAnnotation({
value: savedAnnotation.cfi,
color: savedAnnotation.color,
style: savedAnnotation.style
}).pipe(
tap(() => this.viewManager.clearSelection())
);
}),
takeUntil(this.destroy$)
).subscribe();
}
deleteAnnotation(annotationId: number): void {
const annotation = this.annotations.find(a => a.id === annotationId);
if (!annotation) return;
this.annotationService.deleteAnnotation(annotationId)
.pipe(takeUntil(this.destroy$))
.subscribe(success => {
if (success) {
this.viewManager.deleteAnnotation(annotation.cfi)
.pipe(takeUntil(this.destroy$))
.subscribe();
this.annotations = this.annotations.filter(a => a.id !== annotationId);
this.annotationsChangedSubject.next(this.annotations);
}
});
}
private findOverlappingAnnotation(selectionCfi: string): number | null {
if (!selectionCfi || !this.annotations.length) {
return null;
}
const selectionRange = this.parseCfiRange(selectionCfi);
if (!selectionRange) return null;
for (const annotation of this.annotations) {
const annotationRange = this.parseCfiRange(annotation.cfi);
if (!annotationRange) continue;
// Check if base paths match (same text node/element)
if (selectionRange.basePath !== annotationRange.basePath) continue;
// Check if character ranges actually overlap
// Two ranges [a, b] and [c, d] overlap if a < d AND c < b
if (selectionRange.startOffset < annotationRange.endOffset &&
annotationRange.startOffset < selectionRange.endOffset) {
return annotation.id;
}
}
return null;
}
/**
* Parses a CFI range and extracts the base path and character offsets.
* CFI range format: epubcfi(parent_path,relative_start,relative_end)
* Example: epubcfi(/6/4!/4/2/1:0,/4/2/1:15)
*/
private parseCfiRange(cfi: string): { basePath: string; startOffset: number; endOffset: number } | null {
// Remove epubcfi() wrapper
const inner = cfi.replace(/^epubcfi\(/, '').replace(/\)$/, '');
// Find the comma that separates parent path from relative offsets
const commaIndex = inner.indexOf(',');
if (commaIndex <= 0) {
// Not a range CFI, might be a point CFI - treat as zero-width range
const offsetMatch = inner.match(/:(\d+)$/);
if (offsetMatch) {
const basePath = inner.replace(/:\d+$/, '');
const offset = parseInt(offsetMatch[1], 10);
return { basePath, startOffset: offset, endOffset: offset };
}
return null;
}
// Extract parent path (before first comma)
const parentPath = inner.substring(0, commaIndex);
// Extract relative start and end parts (after commas)
const relativePartsStr = inner.substring(commaIndex + 1);
const relativeParts = relativePartsStr.split(',');
if (relativeParts.length !== 2) return null;
const relativeStart = relativeParts[0];
const relativeEnd = relativeParts[1];
// Extract character offsets from relative parts
const startOffsetMatch = relativeStart.match(/:(\d+)$/);
const endOffsetMatch = relativeEnd.match(/:(\d+)$/);
if (!startOffsetMatch || !endOffsetMatch) return null;
const startOffset = parseInt(startOffsetMatch[1], 10);
const endOffset = parseInt(endOffsetMatch[1], 10);
// Build the full base path by combining parent with the common path structure
// Strip character offsets from the path to get the node path
const startNodePath = relativeStart.replace(/:\d+$/, '');
// Use parent + start node path as base (start and end should be in same node for highlights)
const basePath = `${parentPath}${startNodePath}`;
return { basePath, startOffset, endOffset };
}
private emitState(): void {
this._state.set({
visible: this._visible,
position: this._position,
showBelow: this._showBelow,
overlappingAnnotationId: this._overlappingAnnotationId,
selectedText: this.currentSelection?.text || ''
});
}
reset(): void {
this._visible = false;
this._position = { x: 0, y: 0 };
this._showBelow = false;
this._overlappingAnnotationId = null;
this.currentSelection = null;
this.annotations = [];
this.previewCfi = null;
this.previewColor = null;
this.previewStyle = null;
this._state.set(this.defaultState);
}
getCurrentSelection(): SelectionDetail | null {
return this.currentSelection;
}
hidePopup(): void {
this._visible = false;
this._overlappingAnnotationId = null;
this.clearPreview();
this.emitState();
}
}
@@ -0,0 +1,34 @@
export * from './ebook-reader.component';
export * from './core/loader.service';
export * from './core/view-manager.service';
export * from './core/event.service';
export * from './core/style.service';
export * from './state/reader-state.service';
export * from './state/progress.service';
export * from './state/themes.constant';
export * from './features/annotations/annotation.service';
export * from './features/annotations/annotation-renderer.service';
export * from './features/bookmarks/bookmark.service';
export * from './features/notes/note.service';
export * from './features/selection/selection.service';
export * from './features/fonts/custom-font.service';
export * from './layout/header/header.component';
export * from './layout/header/header.service';
export * from './layout/header/quick-settings.component';
export * from './layout/footer/footer.component';
export * from './layout/sidebar/sidebar.component';
export * from './layout/sidebar/sidebar.service';
export * from './layout/panel/panel.component';
export * from './layout/panel/panel.service';
export * from './dialogs/settings-dialog.component';
export * from './dialogs/metadata-dialog.component';
export * from './dialogs/note-dialog.component';
export * from './shared/icon.component';
export * from './shared/visibility.util';
export * from './shared/header-footer.util';
@@ -0,0 +1,102 @@
<ng-container *transloco="let t; prefix: 'readerEbook.footer'">
<div class="reader-navbar" [class.visible]="navbarVisible">
<button class="icon-btn" [title]="t('previousSection')" [disabled]="!canGoPrevious" (click)="onPreviousSection()">
<app-reader-icon name="chevron-left"></app-reader-icon>
</button>
<div class="progress-section">
<button class="location-btn" (click)="toggleLocationPopover()" [title]="t('location')">
<span class="location-text">{{ currentPercentage }}%</span>
</button>
<div class="progress-slider-wrapper">
<input
type="range"
class="progress-slider"
[min]="0"
[max]="100"
[value]="currentPercentage"
(input)="onProgressChange($event)"
[title]="t('progress')"/>
<div class="progress-ticks">
@for (frac of displaySectionFractions; track frac) {
<span class="progress-tick" [style.left.%]="frac * 100"></span>
}
</div>
</div>
</div>
<button class="icon-btn" [title]="t('nextSection')" [disabled]="!canGoNext" (click)="onNextSection()">
<app-reader-icon name="chevron-right"></app-reader-icon>
</button>
</div>
@if (showLocationPopover) {
<div class="location-popover">
<div class="popover-content">
<div class="time-info">
<div class="time-section">
<span class="label">{{ t('timeLeftInSection') }}</span>
<span class="value">{{ timeSection }}</span>
</div>
<div class="separator"></div>
<div class="time-section">
<span class="label">{{ t('timeLeftInBook') }}</span>
<span class="value">{{ timeTotal }}</span>
</div>
</div>
<div class="divider"></div>
<div class="book-info">
<div class="chapter-info">
<span class="label">{{ t('chapter') }}</span>
<span class="chapter-name">{{ currentChapter }}</span>
</div>
<div class="info-row">
<div class="info-column">
<span class="label">{{ t('section') }}</span>
<span class="value">{{ sectionCurrent }} / {{ sectionTotal }}</span>
</div>
@if (progressData?.pageItem) {
<div class="info-separator"></div>
<div class="info-column">
<span class="label">{{ t('page') }}</span>
<span class="value">{{ currentPage }}</span>
</div>
}
</div>
</div>
<div class="divider"></div>
<div class="nav-section">
<div class="goto-row">
<label>{{ t('goTo') }}</label>
<input type="number" [value]="currentPercentage" #percentInput
(keydown.enter)="onGoToPercentage(percentInput.value)" [min]="0" [max]="100"/>
<span>%</span>
<button class="go-btn" (click)="onGoToPercentage(percentInput.value)" [title]="t('goToPercentage')">{{ t('go') }}</button>
</div>
<div class="section-navigation">
<button class="nav-btn" [title]="t('firstSection')" (click)="onFirstSection()">
<app-reader-icon name="chevron-first" [size]="20"></app-reader-icon>
</button>
<button class="nav-btn" [title]="t('previousSection')" (click)="onPreviousSection()">
<app-reader-icon name="chevron-left" [size]="20"></app-reader-icon>
</button>
<button class="nav-btn" [title]="t('jumpTo')">
<app-reader-icon name="dots-vertical" [size]="20"></app-reader-icon>
</button>
<button class="nav-btn" [title]="t('nextSection')" (click)="onNextSection()">
<app-reader-icon name="chevron-right" [size]="20"></app-reader-icon>
</button>
<button class="nav-btn" [title]="t('lastSection')" (click)="onLastSection()">
<app-reader-icon name="chevron-last" [size]="20"></app-reader-icon>
</button>
</div>
</div>
</div>
</div>
}
</ng-container>
@@ -0,0 +1,445 @@
// Variables matching sidebar styling
$navbar-bg: #1a1a1a;
$text-primary: rgba(255, 255, 255, 0.95);
$text-secondary: rgba(255, 255, 255, 0.6);
$text-muted: rgba(255, 255, 255, 0.4);
$border-color: rgba(255, 255, 255, 0.08);
$hover-bg: rgba(255, 255, 255, 0.08);
$active-color: #818cf8;
$transition-fast: 150ms ease;
$transition-normal: 200ms ease;
.reader-navbar {
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 48px;
padding: 0 12px;
display: flex;
align-items: center;
gap: 8px;
z-index: 1000;
background: $navbar-bg;
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
border-top: 1px solid $border-color;
box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.3);
color: $text-primary;
opacity: 0;
pointer-events: none;
transform: translateY(100%);
transition: opacity 250ms cubic-bezier(0.4, 0, 0.2, 1),
transform 250ms cubic-bezier(0.4, 0, 0.2, 1);
&.visible {
opacity: 1;
pointer-events: auto;
transform: translateY(0);
}
}
.icon-btn {
background: none;
border: none;
color: $text-secondary;
cursor: pointer;
padding: 8px;
border-radius: 8px;
transition: background $transition-fast, color $transition-fast;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
svg {
display: block;
}
&:hover:not(:disabled) {
background: $hover-bg;
color: $text-primary;
}
&:disabled {
opacity: 0.3;
cursor: not-allowed;
}
&:focus-visible {
outline: 2px solid $active-color;
outline-offset: 2px;
}
}
.progress-section {
flex: 1;
display: flex;
align-items: center;
gap: 12px;
.location-btn {
background: rgba(255, 255, 255, 0.05);
border: 1px solid $border-color;
color: $text-primary;
padding: 6px 14px;
border-radius: 6px;
cursor: pointer;
font-size: 13px;
font-weight: 500;
transition: background $transition-fast, border-color $transition-fast;
font-variant-numeric: tabular-nums;
&:hover {
background: $hover-bg;
border-color: rgba(255, 255, 255, 0.15);
}
&:focus-visible {
outline: 2px solid $active-color;
outline-offset: 2px;
}
}
.progress-slider-wrapper {
position: relative;
flex: 1;
display: flex;
align-items: center;
.progress-slider {
flex: 1;
height: 6px;
border-radius: 3px;
outline: none;
-webkit-appearance: none;
background: rgba(255, 255, 255, 0.12);
position: relative;
z-index: 1;
cursor: pointer;
&::-webkit-slider-thumb {
-webkit-appearance: none;
width: 16px;
height: 16px;
border-radius: 50%;
background: $active-color;
cursor: pointer;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
transition: transform $transition-fast, box-shadow $transition-fast;
&:hover {
transform: scale(1.1);
box-shadow: 0 2px 8px rgba(129, 140, 248, 0.4);
}
}
&::-moz-range-thumb {
width: 16px;
height: 16px;
border-radius: 50%;
background: $active-color;
cursor: pointer;
border: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
&:focus-visible {
outline: 2px solid $active-color;
outline-offset: 4px;
}
}
.progress-ticks {
position: absolute;
left: 0;
top: 50%;
width: 100%;
height: 10px;
transform: translateY(-50%);
pointer-events: none;
z-index: 0;
}
.progress-tick {
position: absolute;
top: 0;
width: 1.5px;
height: 10px;
background: rgba(255, 255, 255, 0.4);
border-radius: 2px;
}
}
}
.location-popover {
position: absolute;
bottom: 60px;
left: 50%;
transform: translateX(-50%);
background: $navbar-bg;
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
border: 1px solid $border-color;
border-radius: 12px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
z-index: 1001;
min-width: 380px;
animation: popoverSlideIn 200ms cubic-bezier(0.4, 0, 0.2, 1);
color: $text-primary;
.popover-content {
padding: 16px 20px;
}
.time-info {
display: flex;
gap: 24px;
align-items: center;
justify-content: space-around;
padding: 4px 0;
.time-section {
display: flex;
flex-direction: column;
gap: 4px;
text-align: center;
flex: 1;
.label {
font-size: 11px;
color: $text-muted;
text-transform: uppercase;
letter-spacing: 0.5px;
font-weight: 600;
}
.value {
font-size: 20px;
font-weight: 600;
letter-spacing: -0.3px;
color: $text-primary;
}
}
.separator {
width: 1px;
height: 44px;
background: $border-color;
}
}
.divider {
height: 1px;
background: $border-color;
margin: 12px 0;
}
.book-info {
display: flex;
flex-direction: column;
gap: 12px;
.chapter-info {
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
text-align: center;
.label {
font-size: 11px;
color: $text-muted;
text-transform: uppercase;
letter-spacing: 0.5px;
font-weight: 600;
}
.chapter-name {
font-size: 14px;
font-weight: 500;
color: $text-primary;
line-height: 1.3;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
}
}
.info-row {
display: flex;
align-items: center;
justify-content: center;
gap: 24px;
.info-column {
display: flex;
flex-direction: column;
gap: 4px;
text-align: center;
.label {
font-size: 11px;
color: $text-muted;
text-transform: uppercase;
letter-spacing: 0.5px;
font-weight: 600;
}
.value {
font-size: 18px;
font-weight: 600;
letter-spacing: -0.3px;
color: $text-primary;
}
}
.info-separator {
width: 1px;
height: 36px;
background: $border-color;
}
}
}
.nav-section {
display: flex;
flex-direction: column;
gap: 10px;
}
.goto-row {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
label {
font-size: 13px;
font-weight: 500;
color: $text-secondary;
}
input {
width: 65px;
padding: 6px 10px;
background: rgba(255, 255, 255, 0.05);
border: 1px solid $border-color;
border-radius: 6px;
color: $text-primary;
font-size: 13px;
text-align: right;
transition: background $transition-fast, border-color $transition-fast;
font-variant-numeric: tabular-nums;
&:focus {
outline: none;
background: $hover-bg;
border-color: $active-color;
}
}
span {
font-size: 13px;
color: $text-secondary;
}
.go-btn {
padding: 7px 18px;
background: $active-color;
border: none;
border-radius: 6px;
color: white;
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: background $transition-fast;
flex-shrink: 0;
&:hover {
background: #9ba3fb;
}
}
}
.section-navigation {
display: flex;
gap: 8px;
justify-content: center;
align-items: center;
.nav-btn {
background: none;
border: none;
color: $text-secondary;
padding: 0;
margin: 0;
border-radius: 8px;
cursor: pointer;
transition: background $transition-fast, color $transition-fast, transform $transition-fast;
width: 44px;
height: 44px;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
svg {
display: block;
}
&:hover {
background: $hover-bg;
color: $text-primary;
}
&:active {
transform: scale(0.95);
}
&:focus-visible {
outline: 2px solid $active-color;
outline-offset: 2px;
}
}
}
}
@keyframes popoverSlideIn {
from {
opacity: 0;
transform: translateX(-50%) translateY(8px);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
@media (max-width: 600px) {
.reader-navbar {
padding: 0 8px;
height: 44px;
}
.location-popover {
min-width: 320px;
left: 16px;
right: 16px;
transform: none;
@keyframes popoverSlideIn {
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
}
}
@@ -0,0 +1,167 @@
import {Component, EventEmitter, HostListener, inject, Input, Output} from '@angular/core';
import {TranslocoDirective} from '@jsverse/transloco';
import {ReaderViewManagerService} from '../../core/view-manager.service';
import {ReaderIconComponent} from '../../shared/icon.component';
interface TocItem {
label: string;
href: string;
subitems: any;
id: number;
}
interface PageItem {
label: string;
href: string;
subitems: any;
id: number;
}
interface RelocateEventDetail {
fraction: number;
section: { current: number; total: number };
location: { current: number; next: number; total: number };
time: { section: number; total: number };
tocItem: TocItem;
pageItem: PageItem;
cfi: string;
range: any;
}
@Component({
selector: 'app-reader-navbar',
standalone: true,
imports: [TranslocoDirective, ReaderIconComponent],
templateUrl: './footer.component.html',
styleUrls: ['./footer.component.scss']
})
export class ReaderNavbarComponent {
@Input() progressData: RelocateEventDetail | null = null;
@Input() forceVisible = false;
@Input() set sectionFractions(value: number[]) {
this._sectionFractions = value.filter(f => f > 0.001 && f < 0.999);
}
private _sectionFractions: number[] = [];
get displaySectionFractions(): number[] {
return this._sectionFractions;
}
@Output() progressChange = new EventEmitter<number>();
private managerService = inject(ReaderViewManagerService);
showLocationPopover = false;
@HostListener('document:click', ['$event'])
onDocumentClick(event: MouseEvent) {
const target = event.target as HTMLElement;
const clickedInside = target.closest('.location-popover') || target.closest('.location-btn');
if (!clickedInside && this.showLocationPopover) {
this.showLocationPopover = false;
}
}
@HostListener('window:blur')
onWindowBlur() {
setTimeout(() => {
if (this.showLocationPopover) {
this.showLocationPopover = false;
}
}, 200);
}
toggleLocationPopover() {
this.showLocationPopover = !this.showLocationPopover;
}
get currentFraction(): number {
return this.progressData?.fraction ?? 0;
}
get currentPercentage(): number {
return Math.round(this.currentFraction * 100);
}
get timeTotal(): string {
return this.formatDuration((this.progressData?.time.total ?? 0) * 60);
}
get timeSection(): string {
return this.formatDuration((this.progressData?.time.section ?? 0) * 60);
}
get sectionCurrent(): number {
return this.progressData?.section.current ?? 0;
}
get sectionTotal(): number {
return this.progressData?.section.total ?? 0;
}
get currentChapter(): string {
return this.progressData?.tocItem?.label ?? '';
}
get currentPage(): string {
return this.progressData?.pageItem?.label ?? '';
}
get navbarVisible(): boolean {
return this.forceVisible;
}
get canGoPrevious(): boolean {
const s = this.progressData?.section;
return !!s && s.current > 0;
}
get canGoNext(): boolean {
const s = this.progressData?.section;
return !!s && s.current < s.total - 1;
}
onProgressChange(event: Event) {
const target = event.target as HTMLInputElement;
const fraction = parseFloat(target.value) / 100;
this.progressChange.emit(fraction);
}
onGoToPercentage(value: string): void {
const percentage = parseFloat(value);
if (isNaN(percentage) || percentage < 0 || percentage > 100) return;
const fraction = percentage / 100;
this.progressChange.emit(fraction);
}
onFirstSection() {
this.managerService.goToSection(0).subscribe();
}
onPreviousSection(): void {
const s = this.progressData?.section;
if (!s || s.current <= 0) return;
this.managerService.goToSection(s.current - 1).subscribe();
}
onNextSection(): void {
const s = this.progressData?.section;
if (!s || s.current >= s.total - 1) return;
this.managerService.goToSection(s.current + 1).subscribe();
}
onLastSection(): void {
const s = this.progressData?.section;
if (!s || s.total <= 0) return;
this.managerService.goToSection(s.total - 1).subscribe();
}
private formatDuration(seconds: number): string {
if (seconds < 60) return `${Math.round(seconds)} sec`;
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes} min`;
const hours = Math.floor(minutes / 60);
const remainingMinutes = minutes % 60;
return remainingMinutes > 0
? `${hours} hr ${remainingMinutes} min`
: `${hours} hr`;
}
}
@@ -0,0 +1,55 @@
<ng-container *transloco="let t; prefix: 'readerEbook.header'">
<div class="reader-header" [class.visible]="forceVisible()" [style.background]="theme().bg" [style.color]="theme().fg">
<div class="header-left">
<button class="icon-btn" (click)="onShowChapters()" [title]="t('chapters')">
<app-reader-icon name="menu" [size]="20"></app-reader-icon>
</button>
<button class="icon-btn" (click)="onCreateBookmark()" [title]="isCurrentCfiBookmarked() ? t('removeBookmark') : t('addBookmark')" [class.active]="isCurrentCfiBookmarked()">
<app-reader-icon name="bookmark"></app-reader-icon>
</button>
<button class="icon-btn" (click)="onOpenSearch()" [title]="t('search')">
<app-reader-icon name="search"></app-reader-icon>
</button>
</div>
<span class="chapter-title">{{ bookTitle() }}</span>
<div class="header-right">
<button class="icon-btn desktop-only" (click)="onOpenNotes()" [title]="t('notes')">
<app-reader-icon name="note"></app-reader-icon>
</button>
<button class="icon-btn desktop-only" (click)="onToggleFullscreen()" [title]="isFullscreen() ? t('exitFullscreen') : t('fullscreen')">
<app-reader-icon [name]="isFullscreen() ? 'fullscreen-exit' : 'fullscreen'" [size]="20"></app-reader-icon>
</button>
<button class="icon-btn desktop-only" (click)="onShowHelp()" [title]="t('keyboardShortcuts')">
<app-reader-icon name="help" [size]="20"></app-reader-icon>
</button>
<div class="overflow-menu mobile-only">
<button class="icon-btn" (click)="overflowOpen = !overflowOpen; $event.stopPropagation()" [title]="t('more')">
<app-reader-icon name="dots-vertical" [size]="20"></app-reader-icon>
</button>
@if (overflowOpen) {
<div class="overflow-backdrop" (click)="overflowOpen = false"></div>
<div class="overflow-dropdown" [style.background]="theme().bg" [style.color]="theme().fg">
<button class="overflow-item" (click)="onOpenNotes(); overflowOpen = false">
<app-reader-icon name="note" [size]="18"></app-reader-icon>
<span>{{ t('notes') }}</span>
</button>
<button class="overflow-item" (click)="onToggleFullscreen(); overflowOpen = false">
<app-reader-icon [name]="isFullscreen() ? 'fullscreen-exit' : 'fullscreen'" [size]="18"></app-reader-icon>
<span>{{ isFullscreen() ? t('exitFullscreen') : t('fullscreen') }}</span>
</button>
<button class="overflow-item" (click)="onShowHelp(); overflowOpen = false">
<app-reader-icon name="help" [size]="18"></app-reader-icon>
<span>{{ t('keyboardShortcuts') }}</span>
</button>
</div>
}
</div>
<button class="icon-btn" (click)="onShowControls()" [title]="t('settings')">
<app-reader-icon name="settings"></app-reader-icon>
</button>
<button class="icon-btn close-btn" (click)="onClose(); $event.stopPropagation()" [title]="t('closeReader')">
<app-reader-icon name="close"></app-reader-icon>
</button>
</div>
</div>
</ng-container>
@@ -0,0 +1,146 @@
.reader-header {
position: absolute;
top: 0;
left: 0;
right: 0;
height: 36px;
padding: 0 10px;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 14px;
z-index: 1000;
background: inherit;
border-bottom: 1px solid rgba(0,0,0,0.13);
box-shadow: 0 2px 8px 0 rgba(0,0,0,0.13);
opacity: 0;
pointer-events: none;
transform: translateY(-100%);
transition: opacity 0.25s ease-out, transform 0.25s ease-out;
&.visible {
opacity: 1;
pointer-events: auto;
transform: translateY(0);
}
.header-left,
.header-right {
display: flex;
align-items: center;
z-index: 1;
}
.icon-btn {
background: none;
border: none;
color: inherit;
cursor: pointer;
padding: 8px;
border-radius: 4px;
transition: color 0.15s, opacity 0.15s;
display: flex;
align-items: center;
justify-content: center;
margin-right: 4px;
opacity: 0.85;
&:hover {
opacity: 1;
}
&:last-child {
margin-right: 0;
}
&.active {
color: #ef4444;
opacity: 1;
}
.pi {
font-size: 16px;
}
}
.chapter-title {
flex: 1;
min-width: 0;
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;
min-height: 1.2em;
padding: 0 8px;
}
.mobile-only {
display: none;
}
.overflow-menu {
position: relative;
}
.overflow-backdrop {
position: fixed;
inset: 0;
z-index: 999;
}
.overflow-dropdown {
position: absolute;
top: 100%;
right: 0;
margin-top: 4px;
border: 1px solid rgba(0, 0, 0, 0.15);
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
z-index: 1000;
min-width: 180px;
padding: 4px;
}
.overflow-item {
display: flex;
align-items: center;
gap: 10px;
width: 100%;
padding: 8px 12px;
background: none;
border: none;
color: inherit;
font-size: 13px;
cursor: pointer;
border-radius: 6px;
white-space: nowrap;
&:hover {
background: rgba(128, 128, 128, 0.15);
}
}
}
@media (max-width: 600px) {
.reader-header {
padding: 0 2px;
.icon-btn {
padding: 10px;
margin-right: 2px;
}
.desktop-only {
display: none;
}
.mobile-only {
display: block;
}
}
}
@@ -0,0 +1,60 @@
import {Component, inject} from '@angular/core';
import {TranslocoDirective} from '@jsverse/transloco';
import {ReaderHeaderService} from './header.service';
import {ReaderIconComponent} from '../../shared/icon.component';
import {Router} from '@angular/router';
@Component({
selector: 'app-reader-header',
standalone: true,
imports: [TranslocoDirective, ReaderIconComponent],
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class ReaderHeaderComponent {
private readonly headerService = inject(ReaderHeaderService);
private readonly router = inject(Router);
readonly forceVisible = this.headerService.forceVisible;
readonly isCurrentCfiBookmarked = this.headerService.isCurrentCfiBookmarked;
readonly isFullscreen = this.headerService.isFullscreen;
readonly bookTitle = this.headerService.bookTitle;
readonly theme = this.headerService.theme;
overflowOpen = false;
onShowChapters(): void {
this.headerService.openSidebar();
}
onOpenNotes(): void {
this.headerService.openLeftSidebar('notes');
}
onOpenSearch(): void {
this.headerService.openLeftSidebar('search');
}
onCreateBookmark(): void {
this.headerService.createBookmark();
}
onShowControls(): void {
this.headerService.openControls();
}
onToggleFullscreen(): void {
this.headerService.toggleFullscreen();
}
onShowHelp(): void {
this.headerService.showShortcutsHelp();
}
onClose(): void {
if (window.history.length <= 2) {
this.router.navigate(['/dashboard']);
} else {
this.headerService.close();
}
}
}
@@ -0,0 +1,126 @@
import {computed, inject, Injectable, signal} from '@angular/core';
import {Location} from '@angular/common';
import {Subject} from 'rxjs';
import {ReaderStateService} from '../../state/reader-state.service';
import {ReaderSidebarService} from '../sidebar/sidebar.service';
import {ReaderLeftSidebarService} from '../panel/panel.service';
import {BookService} from '../../../../book/service/book.service';
import {EbookViewerSetting} from '../../../../book/model/book.model';
@Injectable()
export class ReaderHeaderService {
private stateService = inject(ReaderStateService);
private sidebarService = inject(ReaderSidebarService);
private leftSidebarService = inject(ReaderLeftSidebarService);
private bookService = inject(BookService);
private location = inject(Location);
private bookId!: number;
private readonly _bookTitle = signal('');
readonly bookTitle = this._bookTitle.asReadonly();
private readonly _forceVisible = signal(false);
readonly forceVisible = this._forceVisible.asReadonly();
private readonly _isCurrentCfiBookmarked = signal(false);
readonly isCurrentCfiBookmarked = this._isCurrentCfiBookmarked.asReadonly();
private _showControls = new Subject<void>();
private _showMetadata = new Subject<void>();
private _toggleFullscreen = new Subject<void>();
private _showShortcutsHelp = new Subject<void>();
private readonly _isFullscreen = signal(false);
readonly isFullscreen = this._isFullscreen.asReadonly();
showControls$ = this._showControls.asObservable();
showMetadata$ = this._showMetadata.asObservable();
toggleFullscreen$ = this._toggleFullscreen.asObservable();
showShortcutsHelp$ = this._showShortcutsHelp.asObservable();
readonly theme = computed(() => this.stateService.state().theme);
initialize(bookId: number, title: string): void {
this.bookId = bookId;
this._bookTitle.set(title);
}
setForceVisible(visible: boolean): void {
this._forceVisible.set(visible);
}
setCurrentCfiBookmarked(bookmarked: boolean): void {
this._isCurrentCfiBookmarked.set(bookmarked);
}
openSidebar(): void {
this.sidebarService.open();
}
openLeftSidebar(tab?: 'search' | 'notes'): void {
this.leftSidebarService.open(tab);
}
createBookmark(): void {
this.sidebarService.toggleBookmark();
}
openControls(): void {
this._showControls.next();
}
openMetadata(): void {
this._showMetadata.next();
}
toggleFullscreen(): void {
this._toggleFullscreen.next();
}
setFullscreen(isFullscreen: boolean): void {
this._isFullscreen.set(isFullscreen);
}
showShortcutsHelp(): void {
this._showShortcutsHelp.next();
}
close(): void {
this.location.back();
}
toggleDarkMode(): void {
this.stateService.toggleDarkMode();
this.syncSettingsToBackend();
}
increaseFontSize(): void {
this.stateService.updateFontSize(1);
this.syncSettingsToBackend();
}
private syncSettingsToBackend(): void {
const state = this.stateService.state();
const setting: EbookViewerSetting = {
lineHeight: state.lineHeight,
justify: state.justify,
hyphenate: state.hyphenate,
maxColumnCount: state.maxColumnCount,
gap: state.gap,
fontSize: state.fontSize,
theme: typeof state.theme === 'object' && 'name' in state.theme
? state.theme.name
: (state.theme as any),
maxInlineSize: state.maxInlineSize,
maxBlockSize: state.maxBlockSize,
fontFamily: state.fontFamily,
isDark: state.isDark,
flow: state.flow,
};
this.bookService.updateViewerSetting({ebookSettings: setting}, this.bookId).subscribe();
}
reset(): void {
this._forceVisible.set(false);
this._isCurrentCfiBookmarked.set(false);
this._isFullscreen.set(false);
this._bookTitle.set('');
}
}
@@ -0,0 +1,51 @@
<ng-container *transloco="let t; prefix: 'readerEbook.quickSettings'">
<div class="quick-settings-overlay" (click)="onOverlayClick()">
<div class="quick-settings-panel" (click)="$event.stopPropagation()">
<div class="pointer"></div>
<div class="panel-body">
<!-- Dark Mode -->
<div class="control">
<label>{{ t('darkMode') }}</label>
<div class="control-right">
<span class="mode-icon sun" [class.active]="!isDarkMode">&#9728;&#65039;</span>
<button class="switch" [class.active]="isDarkMode" (click)="toggleDarkMode()">
<span class="slider"></span>
</button>
<span class="mode-icon moon" [class.active]="isDarkMode">&#127769;</span>
</div>
</div>
<!-- Font Size -->
<div class="control">
<label>{{ t('fontSize') }}</label>
<div class="control-right">
<div class="stepper">
<button (click)="decreaseFontSize()">&#8722;</button>
<span>{{ state.fontSize }}%</span>
<button (click)="increaseFontSize()">+</button>
</div>
</div>
</div>
<!-- Line Spacing -->
<div class="control">
<label>{{ t('lineSpacing') }}</label>
<div class="control-right">
<div class="stepper">
<button (click)="decreaseLineHeight()">&#8722;</button>
<span>{{ state.lineHeight | number:'1.1-1' }}</span>
<button (click)="increaseLineHeight()">+</button>
</div>
</div>
</div>
</div>
<div class="panel-footer">
<button class="more-settings-btn" (click)="onOpenFullSettings()">
<app-reader-icon name="settings" [size]="16"></app-reader-icon>
<span>{{ t('moreSettings') }}</span>
</button>
</div>
</div>
</div>
</ng-container>
@@ -0,0 +1,240 @@
// Variables matching sidebar/dialog styling
$panel-bg: #1a1a1a;
$text-primary: rgba(255, 255, 255, 0.95);
$text-secondary: rgba(255, 255, 255, 0.6);
$text-muted: rgba(255, 255, 255, 0.4);
$border-color: rgba(255, 255, 255, 0.08);
$hover-bg: rgba(255, 255, 255, 0.08);
$active-color: #818cf8;
$active-bg: rgba(129, 140, 248, 0.15);
$transition-fast: 150ms ease;
$transition-normal: 200ms ease;
.quick-settings-overlay {
position: fixed;
inset: 0;
z-index: 12000;
background: rgba(0, 0, 0, 0.3);
animation: fadeIn $transition-normal;
cursor: pointer;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.quick-settings-panel {
position: absolute;
top: 52px;
right: 60px;
width: 280px;
background: $panel-bg;
border: 1px solid $border-color;
border-radius: 12px;
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.5);
animation: slideDown 200ms cubic-bezier(0.4, 0, 0.2, 1);
overflow: visible;
cursor: default;
}
@keyframes slideDown {
from {
transform: translateY(-8px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
// Pointer arrow
.pointer {
position: absolute;
top: -8px;
right: 18px;
width: 16px;
height: 16px;
background: $panel-bg;
border-left: 1px solid $border-color;
border-top: 1px solid $border-color;
transform: rotate(45deg);
border-radius: 3px 0 0 0;
}
.panel-body {
padding: 16px;
}
.control {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 0;
&:not(:last-child) {
border-bottom: 1px solid $border-color;
}
> label {
color: $text-primary;
font-size: 13px;
font-weight: 500;
flex-shrink: 0;
}
}
.control-right {
display: flex;
align-items: center;
gap: 8px;
}
// Mode icons for dark/light mode
.mode-icon {
font-size: 14px;
opacity: 0.3;
transition: all 300ms ease;
user-select: none;
&.active {
opacity: 1;
transform: scale(1.1);
}
&.sun {
filter: grayscale(100%);
&.active {
filter: grayscale(0%);
}
}
&.moon {
filter: grayscale(100%);
&.active {
filter: grayscale(0%);
}
}
}
// Toggle switch
.switch {
position: relative;
width: 40px;
height: 22px;
background: rgba(255, 255, 255, 0.15);
border: none;
border-radius: 11px;
cursor: pointer;
transition: background 300ms ease;
padding: 0;
&.active {
background: $active-color;
.slider {
transform: translateX(18px);
}
}
.slider {
position: absolute;
top: 2px;
left: 2px;
width: 18px;
height: 18px;
background: #ffffff;
border-radius: 50%;
transition: transform 300ms ease;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
&:hover {
background: rgba(255, 255, 255, 0.2);
&.active {
background: #9aa3fa;
}
}
}
// Stepper control
.stepper {
display: flex;
align-items: center;
gap: 2px;
background: rgba(255, 255, 255, 0.03);
padding: 2px;
border-radius: 6px;
border: 1px solid $border-color;
button {
width: 26px;
height: 26px;
background: rgba(255, 255, 255, 0.05);
color: $text-secondary;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
display: flex;
align-items: center;
justify-content: center;
transition: all $transition-fast;
font-weight: 300;
&:hover {
background: $hover-bg;
color: $text-primary;
}
&:active {
transform: scale(0.95);
}
}
span {
min-width: 50px;
text-align: center;
color: $text-primary;
font-size: 12px;
font-weight: 500;
font-variant-numeric: tabular-nums;
}
}
.panel-footer {
padding: 12px 16px;
border-top: 1px solid $border-color;
background: rgba(0, 0, 0, 0.15);
border-radius: 0 0 12px 12px;
}
.more-settings-btn {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
width: 100%;
padding: 10px 16px;
background: rgba(255, 255, 255, 0.05);
border: 1px solid $border-color;
border-radius: 8px;
color: $text-primary;
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: all $transition-fast;
&:hover {
background: $hover-bg;
border-color: rgba(255, 255, 255, 0.15);
}
&:active {
transform: scale(0.98);
}
}
@@ -0,0 +1,83 @@
import {Component, EventEmitter, Input, Output} from '@angular/core';
import {DecimalPipe} from '@angular/common';
import {TranslocoDirective} from '@jsverse/transloco';
import {ReaderStateService} from '../../state/reader-state.service';
import {ReaderIconComponent} from '../../shared/icon.component';
import {BookService} from '../../../../book/service/book.service';
import {EbookViewerSetting} from '../../../../book/model/book.model';
@Component({
selector: 'app-reader-quick-settings',
standalone: true,
imports: [DecimalPipe, TranslocoDirective, ReaderIconComponent],
templateUrl: './quick-settings.component.html',
styleUrls: ['./quick-settings.component.scss']
})
export class ReaderQuickSettingsComponent {
@Input() stateService!: ReaderStateService;
@Input() bookId!: number;
@Output() close = new EventEmitter<void>();
@Output() openFullSettings = new EventEmitter<void>();
constructor(private bookService: BookService) {}
get state() {
return this.stateService.state();
}
get isDarkMode(): boolean {
return this.state.isDark;
}
private syncSettingsToBackend(): void {
const setting: EbookViewerSetting = {
lineHeight: this.state.lineHeight,
justify: this.state.justify,
hyphenate: this.state.hyphenate,
maxColumnCount: this.state.maxColumnCount,
gap: this.state.gap,
fontSize: this.state.fontSize,
theme: typeof this.state.theme === 'object' && 'name' in this.state.theme ? this.state.theme.name : (this.state.theme as any),
maxInlineSize: this.state.maxInlineSize,
maxBlockSize: this.state.maxBlockSize,
fontFamily: this.state.fontFamily,
isDark: this.state.isDark,
flow: this.state.flow,
};
this.bookService.updateViewerSetting({ebookSettings: setting}, this.bookId).subscribe();
}
toggleDarkMode(): void {
this.stateService.toggleDarkMode();
this.syncSettingsToBackend();
}
increaseFontSize(): void {
this.stateService.updateFontSize(1);
this.syncSettingsToBackend();
}
decreaseFontSize(): void {
this.stateService.updateFontSize(-1);
this.syncSettingsToBackend();
}
increaseLineHeight(): void {
this.stateService.updateLineHeight(0.1);
this.syncSettingsToBackend();
}
decreaseLineHeight(): void {
this.stateService.updateLineHeight(-0.1);
this.syncSettingsToBackend();
}
onOpenFullSettings(): void {
this.close.emit();
this.openFullSettings.emit();
}
onOverlayClick(): void {
this.close.emit();
}
}
@@ -0,0 +1,178 @@
<ng-container *transloco="let t; prefix: 'readerEbook.panel'">
@if (isOpen()) {
<div class="sidebar-overlay" (click)="onOverlayClick()" [class.closing]="closing()">
<aside class="sidebar" (click)="$event.stopPropagation()" [class.closing]="closing()">
<!-- Header -->
<header class="sidebar-header">
<h2 class="sidebar-title">
@if (activeTab() === 'search') {
{{ t('searchTitle') }}
} @else {
{{ t('notesTitle') }}
}
</h2>
</header>
<!-- Tab navigation -->
<nav class="tabs">
<button
class="tab"
[class.active]="activeTab() === 'search'"
(click)="setActiveTab('search')">
<app-reader-icon name="search" class="tab-icon"></app-reader-icon>
<span>{{ t('searchTab') }}</span>
@if (searchState().results.length > 0) {
<span class="badge">{{ searchState().results.length }}</span>
}
</button>
<button
class="tab"
[class.active]="activeTab() === 'notes'"
(click)="setActiveTab('notes')">
<app-reader-icon name="note" class="tab-icon"></app-reader-icon>
<span>{{ t('notesTab') }}</span>
@if (notes().length > 0) {
<span class="badge">{{ notes().length }}</span>
}
</button>
</nav>
<!-- Tab content -->
<div class="content">
@switch (activeTab()) {
@case ('search') {
<div class="search-container">
<div class="search-input-wrapper">
<app-reader-icon name="search" class="search-icon" [size]="16"></app-reader-icon>
<input
type="text"
class="search-input"
[placeholder]="t('searchPlaceholder')"
[(ngModel)]="searchQuery"
(ngModelChange)="onSearchInput($event)"
autofocus
/>
@if (searchQuery) {
<button class="clear-btn" (click)="clearSearch()" [attr.aria-label]="t('clearSearch')">
<app-reader-icon name="close" [size]="14"></app-reader-icon>
</button>
}
</div>
@if (searchState().isSearching) {
<div class="search-progress">
<div class="progress-bar">
<div class="progress-fill" [style.width.%]="searchState().progress * 100"></div>
</div>
<div class="progress-info">
<span class="progress-text">{{ t('searching') }} {{ (searchState().progress * 100) | number:'1.0-0' }}%</span>
<button class="cancel-search-btn" (click)="onCancelSearch()" [title]="t('cancelSearch')">
<app-reader-icon name="close" [size]="14"></app-reader-icon>
</button>
</div>
</div>
}
@if (searchState().results.length > 0) {
<div class="search-results-header">
<span>{{ searchState().results.length === 1 ? t('resultsFound', { count: searchState().results.length }) : t('resultsFoundPlural', { count: searchState().results.length }) }}</span>
</div>
<ul class="item-list search-results">
@for (result of searchState().results; track result.cfi) {
<li class="list-item search-result-item" (click)="onSearchResultClick(result.cfi)">
<div class="item-content">
<span class="search-excerpt">
<span class="excerpt-context">{{ result.excerpt.pre }}</span>
<mark class="excerpt-match">{{ result.excerpt.match }}</mark>
<span class="excerpt-context">{{ result.excerpt.post }}</span>
</span>
@if (result.sectionLabel) {
<span class="item-chapter">{{ result.sectionLabel }}</span>
}
</div>
</li>
}
</ul>
} @else if (!searchState().isSearching && searchQuery) {
<div class="empty-state">
<app-reader-icon name="search" class="empty-icon" [size]="48" [strokeWidth]="1.5"></app-reader-icon>
<p>{{ t('noResultsFound') }}</p>
<span class="empty-hint">{{ t('tryDifferentKeywords') }}</span>
</div>
} @else if (!searchQuery) {
<div class="empty-state">
<app-reader-icon name="search" class="empty-icon" [size]="48" [strokeWidth]="1.5"></app-reader-icon>
<p>{{ t('searchThisBook') }}</p>
<span class="empty-hint">{{ t('enterTextToFind') }}</span>
</div>
}
</div>
}
@case ('notes') {
<div class="notes-container">
@if (notes().length > 0) {
<div class="notes-search-wrapper">
<app-reader-icon name="search" class="search-icon" [size]="16"></app-reader-icon>
<input
type="text"
class="search-input"
[placeholder]="t('searchNotes')"
[ngModel]="notesSearchQuery()"
(ngModelChange)="onNotesSearchInput($event)"
/>
@if (notesSearchQuery()) {
<button class="clear-btn" (click)="clearNotesSearch()" [attr.aria-label]="t('clearSearch')">
<app-reader-icon name="close" [size]="14"></app-reader-icon>
</button>
}
</div>
}
@if (filteredNotes().length > 0) {
<ul class="item-list">
@for (note of filteredNotes(); track note.id) {
<li class="list-item note-item" (click)="onNoteClick(note.cfi)">
<div class="note-bar" [style.background-color]="note.color"></div>
<div class="item-content">
<span class="note-text">{{ note.noteContent }}</span>
@if (note.selectedText) {
<span class="note-selected-text">"{{ note.selectedText }}"</span>
}
@if (note.chapterTitle) {
<span class="item-chapter">{{ note.chapterTitle }}</span>
}
<span class="item-meta">{{ note.createdAt | date: 'MMM d, y' }}</span>
</div>
<div class="action-buttons">
<button class="edit-btn" (click)="onEditNote($event, note)" [attr.aria-label]="t('editNote')">
<app-reader-icon name="edit" [size]="16"></app-reader-icon>
</button>
<button class="delete-btn" (click)="onDeleteNote($event, note.id)" [attr.aria-label]="t('deleteNote')">
<app-reader-icon name="trash" [size]="16"></app-reader-icon>
</button>
</div>
</li>
}
</ul>
} @else if (notes().length > 0 && notesSearchQuery()) {
<div class="empty-state">
<app-reader-icon name="search" class="empty-icon" [size]="48" [strokeWidth]="1.5"></app-reader-icon>
<p>{{ t('noMatchingNotes') }}</p>
<span class="empty-hint">{{ t('tryDifferentSearchTerms') }}</span>
</div>
} @else {
<div class="empty-state">
<app-reader-icon name="note" class="empty-icon" [size]="48" [strokeWidth]="1.5"></app-reader-icon>
<p>{{ t('noNotesYet') }}</p>
<span class="empty-hint">{{ t('noNotesHint') }}</span>
</div>
}
</div>
}
}
</div>
</aside>
</div>
}
</ng-container>
@@ -0,0 +1,550 @@
// Variables
$sidebar-width: 320px;
$sidebar-bg: #1a1a1a;
$text-primary: rgba(255, 255, 255, 0.95);
$text-secondary: rgba(255, 255, 255, 0.6);
$text-muted: rgba(255, 255, 255, 0.4);
$border-color: rgba(255, 255, 255, 0.08);
$hover-bg: rgba(255, 255, 255, 0.06);
$active-bg: rgba(99, 102, 241, 0.15);
$active-color: #818cf8;
$transition-fast: 150ms ease;
$transition-normal: 200ms ease;
// Overlay
.sidebar-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.4);
backdrop-filter: blur(1px);
z-index: 12000;
animation: fadeIn $transition-normal;
&.closing {
animation: fadeOut $transition-normal forwards;
}
}
// Sidebar container - positioned on the RIGHT
.sidebar {
position: fixed;
top: 0;
right: 0;
bottom: 0;
width: $sidebar-width;
background: $sidebar-bg;
display: flex;
flex-direction: column;
color: $text-primary;
box-shadow: -4px 0 24px rgba(0, 0, 0, 0.3);
animation: slideInRight 250ms cubic-bezier(0.4, 0, 0.2, 1);
z-index: 12001;
&.closing {
animation: slideOutRight 200ms cubic-bezier(0.4, 0, 0.2, 1) forwards;
}
}
// Header
.sidebar-header {
display: flex;
align-items: center;
padding: 20px 16px;
border-bottom: 1px solid $border-color;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.03) 0%, transparent 100%);
}
.sidebar-title {
font-size: 16px;
font-weight: 600;
margin: 0;
color: $text-primary;
}
// Tabs
.tabs {
display: flex;
border-bottom: 1px solid $border-color;
background: rgba(0, 0, 0, 0.2);
}
.tab {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
padding: 12px 8px;
background: none;
border: none;
color: $text-secondary;
font-size: 11px;
font-weight: 500;
cursor: pointer;
transition: color $transition-fast, background $transition-fast;
position: relative;
&:hover {
color: $text-primary;
background: $hover-bg;
}
&.active {
color: $active-color;
&::after {
content: '';
position: absolute;
bottom: 0;
left: 16px;
right: 16px;
height: 2px;
background: $active-color;
border-radius: 1px 1px 0 0;
}
}
}
.tab-icon {
width: 18px;
height: 18px;
}
.badge {
position: absolute;
top: 6px;
right: calc(50% - 20px);
min-width: 16px;
height: 16px;
padding: 0 4px;
background: $active-color;
color: white;
font-size: 10px;
font-weight: 600;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
}
// Content area
.content {
flex: 1;
overflow-y: auto;
overscroll-behavior: contain;
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.15);
border-radius: 3px;
&:hover {
background: rgba(255, 255, 255, 0.25);
}
}
}
// Item list
.item-list {
list-style: none;
margin: 0;
padding: 8px 0;
}
.list-item {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 16px;
cursor: pointer;
transition: background $transition-fast;
&:hover {
background: $hover-bg;
.delete-btn {
opacity: 1;
}
}
}
.item-content {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 4px;
}
// Notes
.notes-container {
display: flex;
flex-direction: column;
height: 100%;
}
.notes-search-wrapper {
display: flex;
align-items: center;
gap: 10px;
padding: 12px 16px;
background: rgba(0, 0, 0, 0.2);
border-bottom: 1px solid $border-color;
.search-icon {
color: $text-muted;
flex-shrink: 0;
}
.search-input {
flex: 1;
background: none;
border: none;
color: $text-primary;
font-size: 14px;
outline: none;
&::placeholder {
color: $text-muted;
}
}
.clear-btn {
width: 24px;
height: 24px;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(255, 255, 255, 0.1);
border: none;
border-radius: 50%;
color: $text-secondary;
cursor: pointer;
transition: background $transition-fast, color $transition-fast;
flex-shrink: 0;
&:hover {
background: rgba(255, 255, 255, 0.15);
color: $text-primary;
}
}
}
.note-item {
align-items: flex-start;
&:hover .action-buttons {
opacity: 1;
}
}
.note-bar {
width: 3px;
align-self: stretch;
border-radius: 2px;
flex-shrink: 0;
}
.note-text {
font-size: 13px;
color: $text-primary;
line-height: 1.4;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
}
.note-selected-text {
font-size: 12px;
font-style: italic;
color: $text-secondary;
line-height: 1.4;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
}
.action-buttons {
display: flex;
flex-direction: column;
gap: 4px;
opacity: 0;
transition: opacity $transition-fast;
}
.edit-btn {
width: 28px;
height: 28px;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
background: none;
border: none;
border-radius: 6px;
color: $text-muted;
cursor: pointer;
transition: background $transition-fast, color $transition-fast;
flex-shrink: 0;
svg {
width: 16px;
height: 16px;
}
&:hover {
background: rgba(99, 102, 241, 0.15);
color: $active-color;
}
}
.item-chapter {
font-size: 11px;
color: $text-secondary;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.item-meta {
font-size: 11px;
color: $text-muted;
}
.delete-btn {
width: 28px;
height: 28px;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
background: none;
border: none;
border-radius: 6px;
color: $text-muted;
cursor: pointer;
opacity: 0;
transition: opacity $transition-fast, background $transition-fast, color $transition-fast;
flex-shrink: 0;
svg {
width: 16px;
height: 16px;
}
&:hover {
background: rgba(239, 68, 68, 0.15);
color: #ef4444;
}
}
// Empty state
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 48px 24px;
text-align: center;
color: $text-secondary;
}
.empty-icon {
width: 48px;
height: 48px;
margin-bottom: 16px;
opacity: 0.4;
}
.empty-state p {
margin: 0 0 8px;
font-size: 14px;
font-weight: 500;
}
.empty-hint {
font-size: 12px;
color: $text-muted;
}
// Search
.search-container {
display: flex;
flex-direction: column;
height: 100%;
}
.search-input-wrapper {
display: flex;
align-items: center;
gap: 10px;
padding: 12px 16px;
background: rgba(0, 0, 0, 0.2);
border-bottom: 1px solid $border-color;
.search-icon {
color: $text-muted;
flex-shrink: 0;
}
.search-input {
flex: 1;
background: none;
border: none;
color: $text-primary;
font-size: 14px;
outline: none;
&::placeholder {
color: $text-muted;
}
}
.clear-btn {
width: 24px;
height: 24px;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(255, 255, 255, 0.1);
border: none;
border-radius: 50%;
color: $text-secondary;
cursor: pointer;
transition: background $transition-fast, color $transition-fast;
flex-shrink: 0;
&:hover {
background: rgba(255, 255, 255, 0.15);
color: $text-primary;
}
}
}
.search-progress {
padding: 12px 16px;
display: flex;
flex-direction: column;
gap: 8px;
.progress-bar {
height: 3px;
background: rgba(255, 255, 255, 0.1);
border-radius: 2px;
overflow: hidden;
.progress-fill {
height: 100%;
background: $active-color;
border-radius: 2px;
transition: width 200ms ease-out;
}
}
.progress-info {
display: flex;
align-items: center;
justify-content: space-between;
}
.progress-text {
font-size: 11px;
color: $text-muted;
}
.cancel-search-btn {
width: 22px;
height: 22px;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(255, 255, 255, 0.08);
border: none;
border-radius: 50%;
color: $text-muted;
cursor: pointer;
transition: background $transition-fast, color $transition-fast;
flex-shrink: 0;
&:hover {
background: rgba(239, 68, 68, 0.15);
color: #ef4444;
}
}
}
.search-results-header {
padding: 10px 16px;
font-size: 11px;
font-weight: 600;
color: $text-secondary;
text-transform: uppercase;
letter-spacing: 0.5px;
border-bottom: 1px solid $border-color;
}
.search-results {
flex: 1;
overflow-y: auto;
}
.search-result-item {
.item-content {
gap: 6px;
}
}
.search-excerpt {
font-size: 13px;
color: $text-secondary;
line-height: 1.5;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
.excerpt-context {
color: $text-secondary;
}
.excerpt-match {
background: rgba(255, 255, 0, 0.25);
color: $text-primary;
font-weight: 500;
padding: 1px 2px;
border-radius: 2px;
}
}
// Animations
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes fadeOut {
from { opacity: 1; }
to { opacity: 0; }
}
@keyframes slideInRight {
from { transform: translateX(100%); }
to { transform: translateX(0); }
}
@keyframes slideOutRight {
from { transform: translateX(0); }
to { transform: translateX(100%); }
}
@@ -0,0 +1,135 @@
import {Component, DestroyRef, effect, inject, signal} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {Subject} from 'rxjs';
import {takeUntil, debounceTime, distinctUntilChanged, filter} from 'rxjs/operators';
import {TranslocoDirective} from '@jsverse/transloco';
import {ReaderLeftSidebarService, LeftSidebarTab} from './panel.service';
import {BookNoteV2} from '../../../../../shared/service/book-note-v2.service';
import {ReaderIconComponent} from '../../shared/icon.component';
@Component({
selector: 'app-reader-left-sidebar',
standalone: true,
templateUrl: './panel.component.html',
styleUrls: ['./panel.component.scss'],
imports: [CommonModule, FormsModule, TranslocoDirective, ReaderIconComponent]
})
export class ReaderLeftSidebarComponent {
private readonly leftSidebarService = inject(ReaderLeftSidebarService);
private readonly destroyRef = inject(DestroyRef);
private readonly destroy$ = new Subject<void>();
private closeAnimationTimeout: ReturnType<typeof setTimeout> | null = null;
readonly activeTab = this.leftSidebarService.activeTab;
readonly notes = this.leftSidebarService.notes;
readonly notesSearchQuery = this.leftSidebarService.notesSearchQuery;
readonly searchState = this.leftSidebarService.searchState;
readonly filteredNotes = this.leftSidebarService.filteredNotes;
readonly isOpen = signal(false);
readonly closing = signal(false);
searchQuery = '';
private readonly searchInput$ = new Subject<string>();
constructor() {
effect(() => {
if (this.leftSidebarService.isOpen()) {
this.clearCloseAnimation();
this.isOpen.set(true);
this.closing.set(false);
return;
}
if (this.isOpen()) {
this.closeWithAnimation();
}
});
effect(() => {
const state = this.leftSidebarService.searchState();
if (state.query !== this.searchQuery) {
this.searchQuery = state.query;
}
});
this.searchInput$
.pipe(
debounceTime(500),
distinctUntilChanged(),
filter(query => query.length >= 3 || query.length === 0),
takeUntil(this.destroy$)
)
.subscribe(query => this.leftSidebarService.search(query));
this.destroyRef.onDestroy(() => {
this.clearCloseAnimation();
this.destroy$.next();
this.destroy$.complete();
});
}
private closeWithAnimation(): void {
this.closing.set(true);
this.closeAnimationTimeout = setTimeout(() => {
this.isOpen.set(false);
this.closing.set(false);
this.closeAnimationTimeout = null;
}, 250);
}
private clearCloseAnimation(): void {
if (this.closeAnimationTimeout) {
clearTimeout(this.closeAnimationTimeout);
this.closeAnimationTimeout = null;
}
}
onOverlayClick(): void {
this.leftSidebarService.close();
}
setActiveTab(tab: LeftSidebarTab): void {
this.leftSidebarService.setActiveTab(tab);
}
onNoteClick(cfi: string): void {
this.leftSidebarService.navigateToNote(cfi);
}
onEditNote(event: MouseEvent, note: BookNoteV2): void {
event.stopPropagation();
this.leftSidebarService.editNote(note);
}
onDeleteNote(event: MouseEvent, noteId: number): void {
event.stopPropagation();
this.leftSidebarService.deleteNote(noteId);
}
onNotesSearchInput(query: string): void {
this.leftSidebarService.setNotesSearchQuery(query);
}
clearNotesSearch(): void {
this.leftSidebarService.setNotesSearchQuery('');
}
onSearchInput(query: string): void {
this.searchInput$.next(query);
}
onSearchResultClick(cfi: string): void {
this.leftSidebarService.navigateToSearchResult(cfi);
}
clearSearch(): void {
this.searchQuery = '';
this.leftSidebarService.clearSearch();
}
onCancelSearch(): void {
this.searchQuery = '';
this.leftSidebarService.clearSearch();
}
}
@@ -0,0 +1,213 @@
import {computed, inject, Injectable, signal} from '@angular/core';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {BookNoteV2, BookNoteV2Service} from '../../../../../shared/service/book-note-v2.service';
import {ReaderViewManagerService} from '../../core/view-manager.service';
import {SearchResult, SearchState} from '../sidebar/sidebar.service';
export type LeftSidebarTab = 'search' | 'notes';
@Injectable()
export class ReaderLeftSidebarService {
private viewManager = inject(ReaderViewManagerService);
private bookNoteV2Service = inject(BookNoteV2Service);
private destroy$ = new Subject<void>();
private bookId!: number;
private readonly _isOpen = signal(false);
readonly isOpen = this._isOpen.asReadonly();
private readonly _activeTab = signal<LeftSidebarTab>('search');
readonly activeTab = this._activeTab.asReadonly();
private readonly _notes = signal<BookNoteV2[]>([]);
readonly notes = this._notes.asReadonly();
private readonly _notesSearchQuery = signal('');
readonly notesSearchQuery = this._notesSearchQuery.asReadonly();
readonly filteredNotes = computed(() => {
const query = this._notesSearchQuery().toLowerCase().trim();
const notes = this._notes();
if (!query) {
return notes;
}
return notes.filter(note =>
note.noteContent.toLowerCase().includes(query) ||
note.selectedText?.toLowerCase().includes(query) ||
note.chapterTitle?.toLowerCase().includes(query)
);
});
private readonly _searchState = signal<SearchState>({
query: '',
results: [],
isSearching: false,
progress: 0
});
readonly searchState = this._searchState.asReadonly();
private searchAbortController: AbortController | null = null;
private _editNote = new Subject<BookNoteV2>();
editNote$ = this._editNote.asObservable();
initialize(bookId: number, destroy$: Subject<void>): void {
this.bookId = bookId;
this.destroy$ = destroy$;
this.loadNotes();
}
private loadNotes(): void {
this.bookNoteV2Service.getNotesForBook(this.bookId)
.pipe(takeUntil(this.destroy$))
.subscribe(notes => this._notes.set(notes));
}
refreshNotes(): void {
this.loadNotes();
}
open(tab?: LeftSidebarTab): void {
if (tab) {
this._activeTab.set(tab);
}
this._isOpen.set(true);
}
close(): void {
this._isOpen.set(false);
}
toggle(tab?: LeftSidebarTab): void {
if (this._isOpen() && (!tab || this._activeTab() === tab)) {
this.close();
} else {
this.open(tab);
}
}
setActiveTab(tab: LeftSidebarTab): void {
this._activeTab.set(tab);
}
openWithSearch(query: string): void {
this._activeTab.set('search');
this._isOpen.set(true);
setTimeout(() => this.search(query), 100);
}
navigateToNote(cfi: string): void {
this.viewManager.goTo(cfi)
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.close());
}
deleteNote(noteId: number): void {
this.bookNoteV2Service.deleteNote(noteId)
.pipe(takeUntil(this.destroy$))
.subscribe(() => {
this._notes.update(notes => notes.filter(note => note.id !== noteId));
});
}
editNote(note: BookNoteV2): void {
this.close();
this._editNote.next(note);
}
setNotesSearchQuery(query: string): void {
this._notesSearchQuery.set(query);
}
async search(query: string): Promise<void> {
if (!query.trim()) {
this.clearSearch();
return;
}
if (this.searchAbortController) {
this.searchAbortController.abort();
}
this.searchAbortController = new AbortController();
this._searchState.set({
query,
results: [],
isSearching: true,
progress: 0
});
try {
const results: SearchResult[] = [];
const searchGenerator = this.viewManager.search({ query });
for await (const result of searchGenerator) {
if (this.searchAbortController?.signal.aborted) break;
if (typeof result === 'string' && result === 'done') {
break;
}
if ('progress' in result) {
this._searchState.update(current => ({
...current,
progress: result.progress
}));
}
if ('subitems' in result && result.subitems) {
const sectionResults = result.subitems.map((item: any) => ({
cfi: item.cfi,
excerpt: item.excerpt,
sectionLabel: result.label
}));
results.push(...sectionResults);
this._searchState.update(current => ({
...current,
results: [...results]
}));
}
}
this._searchState.set({
query,
results,
isSearching: false,
progress: 1
});
} catch (error) {
this._searchState.update(current => ({...current, isSearching: false}));
}
}
clearSearch(): void {
if (this.searchAbortController) {
this.searchAbortController.abort();
this.searchAbortController = null;
}
this.viewManager.clearSearch();
this._searchState.set({
query: '',
results: [],
isSearching: false,
progress: 0
});
}
navigateToSearchResult(cfi: string): void {
this.viewManager.goTo(cfi)
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.close());
}
reset(): void {
this._isOpen.set(false);
this._activeTab.set('search');
this._notes.set([]);
this._notesSearchQuery.set('');
this.clearSearch();
}
}
@@ -0,0 +1,152 @@
<ng-container *transloco="let t; prefix: 'readerEbook.sidebar'">
@if (isOpen()) {
<div class="sidebar-overlay" (click)="onOverlayClick()" [class.closing]="closing()">
<aside class="sidebar" (click)="$event.stopPropagation()" [class.closing]="closing()">
<!-- Header with book info -->
<header class="sidebar-header">
@if (bookInfo().coverUrl) {
<img
[src]="bookInfo().coverUrl"
[alt]="t('bookCoverAlt')"
class="book-cover"
(click)="onCoverClick()"
role="button"
tabindex="0"
(keydown.enter)="onCoverClick()"
/>
}
<div class="book-meta">
<h2 class="book-title">{{ bookInfo().title }}</h2>
@if (bookInfo().authors) {
<p class="book-authors">{{ bookInfo().authors }}</p>
}
</div>
</header>
<!-- Tab navigation -->
<nav class="tabs">
<button
class="tab"
[class.active]="activeTab() === 'chapters'"
(click)="setActiveTab('chapters')">
<app-reader-icon name="book" class="tab-icon"></app-reader-icon>
<span>{{ t('contentsTab') }}</span>
</button>
<button
class="tab"
[class.active]="activeTab() === 'bookmarks'"
(click)="setActiveTab('bookmarks')">
<app-reader-icon name="bookmark" class="tab-icon"></app-reader-icon>
<span>{{ t('bookmarksTab') }}</span>
@if (bookmarks().length > 0) {
<span class="badge">{{ bookmarks().length }}</span>
}
</button>
<button
class="tab"
[class.active]="activeTab() === 'highlights'"
(click)="setActiveTab('highlights')">
<app-reader-icon name="edit" class="tab-icon"></app-reader-icon>
<span>{{ t('highlightsTab') }}</span>
@if (annotations().length > 0) {
<span class="badge">{{ annotations().length }}</span>
}
</button>
</nav>
<!-- Tab content -->
<div class="content">
@switch (activeTab()) {
@case ('chapters') {
<ul class="chapter-list" role="tree">
@for (chapter of chapters(); track chapter.href) {
<ng-container *ngTemplateOutlet="chapterItem; context: { $implicit: chapter, depth: 0 }"/>
}
</ul>
<ng-template #chapterItem let-chapter let-depth="depth">
<li role="treeitem">
<button
class="chapter-row"
[class.active]="isChapterActive(chapter.href)"
[class.expandable]="chapter.subitems?.length"
[style.--depth]="depth"
(click)="onChapterClick(chapter)">
<span class="chapter-label">{{ chapter.label }}</span>
@if (chapter.subitems?.length) {
<app-reader-icon
name="chevron-right"
class="expand-icon"
[class.expanded]="isChapterExpanded(chapter.href)"
[size]="16">
</app-reader-icon>
}
</button>
@if (chapter.subitems?.length && isChapterExpanded(chapter.href)) {
<ul class="subchapter-list" role="group">
@for (sub of chapter.subitems; track sub.href) {
<ng-container *ngTemplateOutlet="chapterItem; context: { $implicit: sub, depth: depth + 1 }"/>
}
</ul>
}
</li>
</ng-template>
}
@case ('bookmarks') {
@if (bookmarks().length > 0) {
<ul class="item-list">
@for (bookmark of bookmarks(); track bookmark.id) {
<li class="list-item" (click)="onBookmarkClick(bookmark.cfi!)">
<div class="item-content">
<span class="item-title">{{ bookmark.title }}</span>
<span class="item-meta">{{ bookmark.createdAt | date: 'MMM d, y' }}</span>
</div>
<button class="delete-btn" (click)="onDeleteBookmark($event, bookmark.id)" [attr.aria-label]="t('deleteBookmark')">
<app-reader-icon name="trash" [size]="16"></app-reader-icon>
</button>
</li>
}
</ul>
} @else {
<div class="empty-state">
<app-reader-icon name="bookmark" class="empty-icon" [size]="48" [strokeWidth]="1.5"></app-reader-icon>
<p>{{ t('noBookmarksYet') }}</p>
<span class="empty-hint">{{ t('noBookmarksHint') }}</span>
</div>
}
}
@case ('highlights') {
@if (annotations().length > 0) {
<ul class="item-list">
@for (annotation of annotations(); track annotation.id) {
<li class="list-item highlight-item" (click)="onAnnotationClick(annotation.cfi)">
<div class="highlight-bar" [style.background-color]="annotation.color"></div>
<div class="item-content">
<span class="highlight-text">"{{ annotation.text }}"</span>
@if (annotation.chapterTitle) {
<span class="item-chapter">{{ annotation.chapterTitle }}</span>
}
<span class="item-meta">{{ annotation.createdAt | date: 'MMM d, y' }}</span>
</div>
<button class="delete-btn" (click)="onDeleteAnnotation($event, annotation.id)" [attr.aria-label]="t('deleteHighlight')">
<app-reader-icon name="trash" [size]="16"></app-reader-icon>
</button>
</li>
}
</ul>
} @else {
<div class="empty-state">
<app-reader-icon name="edit" class="empty-icon" [size]="48" [strokeWidth]="1.5"></app-reader-icon>
<p>{{ t('noHighlightsYet') }}</p>
<span class="empty-hint">{{ t('noHighlightsHint') }}</span>
</div>
}
}
}
</div>
</aside>
</div>
}
</ng-container>
@@ -0,0 +1,552 @@
// Variables
$sidebar-width: 300px;
$sidebar-bg: #1a1a1a;
$text-primary: rgba(255, 255, 255, 0.95);
$text-secondary: rgba(255, 255, 255, 0.6);
$text-muted: rgba(255, 255, 255, 0.4);
$border-color: rgba(255, 255, 255, 0.08);
$hover-bg: rgba(255, 255, 255, 0.06);
$active-bg: rgba(99, 102, 241, 0.15);
$active-color: #818cf8;
$transition-fast: 150ms ease;
$transition-normal: 200ms ease;
// Overlay
.sidebar-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.4);
backdrop-filter: blur(2px);
z-index: 12000;
animation: fadeIn $transition-normal;
&.closing {
animation: fadeOut $transition-normal forwards;
}
}
// Sidebar container
.sidebar {
position: fixed;
top: 0;
left: 0;
bottom: 0;
width: $sidebar-width;
background: $sidebar-bg;
display: flex;
flex-direction: column;
color: $text-primary;
box-shadow: 4px 0 24px rgba(0, 0, 0, 0.3);
animation: slideIn 250ms cubic-bezier(0.4, 0, 0.2, 1);
z-index: 12001;
&.closing {
animation: slideOut 200ms cubic-bezier(0.4, 0, 0.2, 1) forwards;
}
}
// Header
.sidebar-header {
display: flex;
gap: 14px;
padding: 20px 16px;
border-bottom: 1px solid $border-color;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.03) 0%, transparent 100%);
}
.book-cover {
width: 60px;
height: 90px;
object-fit: cover;
border-radius: 4px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
flex-shrink: 0;
cursor: pointer;
transition: transform $transition-fast, box-shadow $transition-fast;
&:hover {
transform: scale(1.03);
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.4);
}
&:focus-visible {
outline: 2px solid $active-color;
outline-offset: 2px;
}
}
.book-meta {
display: flex;
flex-direction: column;
justify-content: center;
min-width: 0;
gap: 6px;
}
.book-title {
font-size: 14px;
font-weight: 600;
line-height: 1.3;
margin: 0;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
}
.book-authors {
font-size: 12px;
color: $text-secondary;
margin: 0;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 1;
overflow: hidden;
}
// Tabs
.tabs {
display: flex;
border-bottom: 1px solid $border-color;
background: rgba(0, 0, 0, 0.2);
}
.tab {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
gap: 4px;
padding: 12px 8px;
background: none;
border: none;
color: $text-secondary;
font-size: 11px;
font-weight: 500;
cursor: pointer;
transition: color $transition-fast, background $transition-fast;
position: relative;
&:hover {
color: $text-primary;
background: $hover-bg;
}
&.active {
color: $active-color;
&::after {
content: '';
position: absolute;
bottom: 0;
left: 16px;
right: 16px;
height: 2px;
background: $active-color;
border-radius: 1px 1px 0 0;
}
}
}
.tab-icon {
width: 18px;
height: 18px;
}
.badge {
position: absolute;
top: 6px;
right: calc(50% - 20px);
min-width: 16px;
height: 16px;
padding: 0 4px;
background: $active-color;
color: white;
font-size: 10px;
font-weight: 600;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
}
// Content area
.content {
flex: 1;
overflow-y: auto;
overscroll-behavior: contain;
&::-webkit-scrollbar {
width: 6px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.15);
border-radius: 3px;
&:hover {
background: rgba(255, 255, 255, 0.25);
}
}
}
// Chapter list
.chapter-list,
.subchapter-list {
list-style: none;
margin: 0;
padding: 8px 0;
}
.subchapter-list {
padding: 0;
}
.chapter-row {
display: flex;
align-items: center;
width: 100%;
padding: 10px 16px;
padding-left: calc(16px + var(--depth, 0) * 16px);
background: none;
border: none;
color: $text-primary;
font-size: 13px;
text-align: left;
cursor: pointer;
transition: background $transition-fast;
&:hover {
background: $hover-bg;
}
&.active {
background: $active-bg;
color: $active-color;
font-weight: 500;
}
&.expandable {
font-weight: 500;
}
}
.chapter-label {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.expand-icon {
width: 16px;
height: 16px;
flex-shrink: 0;
margin-left: 8px;
color: $text-muted;
transition: transform $transition-fast;
&.expanded {
transform: rotate(90deg);
}
}
// Item list (bookmarks & highlights)
.item-list {
list-style: none;
margin: 0;
padding: 8px 0;
}
.list-item {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 16px;
cursor: pointer;
transition: background $transition-fast;
&:hover {
background: $hover-bg;
.delete-btn {
opacity: 1;
}
}
}
.highlight-item {
align-items: flex-start;
}
.highlight-bar {
width: 3px;
align-self: stretch;
border-radius: 2px;
flex-shrink: 0;
}
.item-content {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 4px;
}
.item-title {
font-size: 13px;
font-weight: 500;
color: $text-primary;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.highlight-text {
font-size: 13px;
font-style: italic;
color: $text-primary;
line-height: 1.4;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
}
.item-chapter {
font-size: 11px;
color: $text-secondary;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.item-meta {
font-size: 11px;
color: $text-muted;
}
.action-buttons {
display: flex;
flex-direction: column;
gap: 4px;
opacity: 0;
transition: opacity $transition-fast;
flex-shrink: 0;
}
.list-item:hover .action-buttons {
opacity: 1;
}
.edit-btn,
.delete-btn {
width: 28px;
height: 28px;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
background: none;
border: none;
border-radius: 6px;
color: $text-muted;
cursor: pointer;
transition: background $transition-fast, color $transition-fast;
flex-shrink: 0;
svg {
width: 16px;
height: 16px;
}
}
.edit-btn:hover {
background: rgba(99, 102, 241, 0.15);
color: $active-color;
}
.delete-btn:hover {
background: rgba(239, 68, 68, 0.15);
color: #ef4444;
}
// Empty state
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 48px 24px;
text-align: center;
color: $text-secondary;
}
.empty-icon {
width: 48px;
height: 48px;
margin-bottom: 16px;
opacity: 0.4;
}
.empty-state p {
margin: 0 0 8px;
font-size: 14px;
font-weight: 500;
}
.empty-hint {
font-size: 12px;
color: $text-muted;
}
// Search
.search-container {
display: flex;
flex-direction: column;
height: 100%;
}
.search-input-wrapper {
display: flex;
align-items: center;
gap: 10px;
padding: 12px 16px;
background: rgba(0, 0, 0, 0.2);
border-bottom: 1px solid $border-color;
.search-icon {
color: $text-muted;
flex-shrink: 0;
}
.search-input {
flex: 1;
background: none;
border: none;
color: $text-primary;
font-size: 14px;
outline: none;
&::placeholder {
color: $text-muted;
}
}
.clear-btn {
width: 24px;
height: 24px;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(255, 255, 255, 0.1);
border: none;
border-radius: 50%;
color: $text-secondary;
cursor: pointer;
transition: background $transition-fast, color $transition-fast;
flex-shrink: 0;
&:hover {
background: rgba(255, 255, 255, 0.15);
color: $text-primary;
}
}
}
.search-progress {
padding: 12px 16px;
display: flex;
flex-direction: column;
gap: 8px;
.progress-bar {
height: 3px;
background: rgba(255, 255, 255, 0.1);
border-radius: 2px;
overflow: hidden;
.progress-fill {
height: 100%;
background: $active-color;
border-radius: 2px;
transition: width 200ms ease-out;
}
}
.progress-text {
font-size: 11px;
color: $text-muted;
text-align: center;
}
}
.search-results-header {
padding: 10px 16px;
font-size: 11px;
font-weight: 600;
color: $text-secondary;
text-transform: uppercase;
letter-spacing: 0.5px;
border-bottom: 1px solid $border-color;
}
.search-results {
flex: 1;
overflow-y: auto;
}
.search-result-item {
.item-content {
gap: 6px;
}
}
.search-excerpt {
font-size: 13px;
color: $text-secondary;
line-height: 1.5;
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
.excerpt-context {
color: $text-secondary;
}
.excerpt-match {
background: rgba(255, 255, 0, 0.25);
color: $text-primary;
font-weight: 500;
padding: 1px 2px;
border-radius: 2px;
}
}
// Animations
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes fadeOut {
from { opacity: 1; }
to { opacity: 0; }
}
@keyframes slideIn {
from { transform: translateX(-100%); }
to { transform: translateX(0); }
}
@keyframes slideOut {
from { transform: translateX(0); }
to { transform: translateX(-100%); }
}
@@ -0,0 +1,108 @@
import {Component, DestroyRef, effect, inject, signal} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormsModule} from '@angular/forms';
import {TranslocoDirective} from '@jsverse/transloco';
import {TocItem} from 'epubjs';
import {ReaderSidebarService, SidebarTab} from './sidebar.service';
import {ReaderIconComponent} from '../../shared/icon.component';
@Component({
selector: 'app-reader-sidebar',
standalone: true,
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.scss'],
imports: [CommonModule, FormsModule, TranslocoDirective, ReaderIconComponent]
})
export class ReaderSidebarComponent {
private readonly sidebarService = inject(ReaderSidebarService);
private readonly destroyRef = inject(DestroyRef);
private closeAnimationTimeout: ReturnType<typeof setTimeout> | null = null;
readonly activeTab = this.sidebarService.activeTab;
readonly bookInfo = this.sidebarService.bookInfo;
readonly chapters = this.sidebarService.chapters;
readonly bookmarks = this.sidebarService.bookmarks;
readonly annotations = this.sidebarService.annotations;
readonly isOpen = signal(false);
readonly closing = signal(false);
constructor() {
effect(() => {
if (this.sidebarService.isOpen()) {
this.clearCloseAnimation();
this.isOpen.set(true);
this.closing.set(false);
return;
}
if (this.isOpen()) {
this.closeWithAnimation();
}
});
this.destroyRef.onDestroy(() => this.clearCloseAnimation());
}
private closeWithAnimation(): void {
this.closing.set(true);
this.closeAnimationTimeout = setTimeout(() => {
this.isOpen.set(false);
this.closing.set(false);
this.closeAnimationTimeout = null;
}, 250);
}
private clearCloseAnimation(): void {
if (this.closeAnimationTimeout) {
clearTimeout(this.closeAnimationTimeout);
this.closeAnimationTimeout = null;
}
}
onOverlayClick(): void {
this.sidebarService.close();
}
setActiveTab(tab: SidebarTab): void {
this.sidebarService.setActiveTab(tab);
}
onChapterClick(chapter: TocItem): void {
if (chapter.subitems?.length) {
this.sidebarService.toggleChapterExpand(chapter.href);
} else {
this.sidebarService.navigateToChapter(chapter.href);
}
}
isChapterExpanded(href: string): boolean {
return this.sidebarService.isChapterExpanded(href);
}
isChapterActive(href: string): boolean {
return this.sidebarService.isChapterActive(href);
}
onBookmarkClick(cfi: string): void {
this.sidebarService.navigateToBookmark(cfi);
}
onDeleteBookmark(event: MouseEvent, bookmarkId: number): void {
event.stopPropagation();
this.sidebarService.deleteBookmark(bookmarkId);
}
onAnnotationClick(cfi: string): void {
this.sidebarService.navigateToAnnotation(cfi);
}
onDeleteAnnotation(event: MouseEvent, annotationId: number): void {
event.stopPropagation();
this.sidebarService.deleteAnnotation(annotationId);
}
onCoverClick(): void {
this.sidebarService.openMetadata();
}
}
@@ -0,0 +1,305 @@
import {inject, Injectable, Injector, signal} from '@angular/core';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {TocItem} from 'epubjs';
import {BookMark, BookMarkService} from '../../../../../shared/service/book-mark.service';
import {Annotation} from '../../../../../shared/service/annotation.service';
import {UrlHelperService} from '../../../../../shared/service/url-helper.service';
import {ReaderViewManagerService} from '../../core/view-manager.service';
import {ReaderProgressService} from '../../state/progress.service';
import {ReaderBookmarkService} from '../../features/bookmarks/bookmark.service';
import {ReaderAnnotationHttpService} from '../../features/annotations/annotation.service';
import {ReaderSelectionService} from '../../features/selection/selection.service';
import {Book} from '../../../../book/model/book.model';
export interface SidebarBookInfo {
id: number | null;
title: string;
authors: string;
coverUrl: string | null;
}
export type SidebarTab = 'chapters' | 'bookmarks' | 'highlights';
export interface SearchResult {
cfi: string;
excerpt: {
pre: string;
match: string;
post: string;
};
sectionLabel?: string;
}
export interface SearchState {
query: string;
results: SearchResult[];
isSearching: boolean;
progress: number;
}
@Injectable()
export class ReaderSidebarService {
private injector = inject(Injector);
private urlHelper = inject(UrlHelperService);
private viewManager = inject(ReaderViewManagerService);
private progressService = inject(ReaderProgressService);
private bookmarkService = inject(ReaderBookmarkService);
private bookMarkHttpService = inject(BookMarkService);
private annotationService = inject(ReaderAnnotationHttpService);
private destroy$ = new Subject<void>();
private bookId!: number;
private selectionService: ReaderSelectionService | null = null;
private readonly _isOpen = signal(false);
readonly isOpen = this._isOpen.asReadonly();
private readonly _activeTab = signal<SidebarTab>('chapters');
readonly activeTab = this._activeTab.asReadonly();
private readonly _bookInfo = signal<SidebarBookInfo>({
id: null,
title: '',
authors: '',
coverUrl: null
});
readonly bookInfo = this._bookInfo.asReadonly();
private readonly _chapters = signal<TocItem[]>([]);
readonly chapters = this._chapters.asReadonly();
private readonly _bookmarks = signal<BookMark[]>([]);
readonly bookmarks = this._bookmarks.asReadonly();
private readonly _annotations = signal<Annotation[]>([]);
readonly annotations = this._annotations.asReadonly();
private _expandedChapters = new Set<string>();
private _showMetadata = new Subject<void>();
showMetadata$ = this._showMetadata.asObservable();
get currentChapterHref(): string | null {
return this.progressService.currentChapterHref;
}
initialize(bookId: number, book: Book, destroy$: Subject<void>): void {
this.bookId = bookId;
this.destroy$ = destroy$;
this._bookInfo.set({
id: book.id,
title: book.metadata?.title || '',
authors: (book.metadata?.authors || []).join(', '),
coverUrl: this.urlHelper.getThumbnailUrl(book.id, book.metadata?.coverUpdatedOn)
});
this._chapters.set(this.viewManager.getChapters());
this.loadBookmarks();
this.loadAnnotations();
this.subscribeToAnnotationChanges();
}
private subscribeToAnnotationChanges(): void {
if (!this.selectionService) {
this.selectionService = this.injector.get(ReaderSelectionService);
}
this.selectionService.annotationsChanged$
.pipe(takeUntil(this.destroy$))
.subscribe(annotations => {
this._annotations.set(annotations);
});
}
private loadAnnotations(): void {
this.annotationService.getAnnotations(this.bookId)
.pipe(takeUntil(this.destroy$))
.subscribe(annotations => {
this._annotations.set(annotations);
if (!this.selectionService) {
this.selectionService = this.injector.get(ReaderSelectionService);
}
this.selectionService.setAnnotations(annotations);
if (annotations.length > 0) {
const viewAnnotations = this.annotationService.toViewAnnotations(annotations);
this.viewManager.addAnnotations(viewAnnotations);
}
});
}
setAnnotations(annotations: Annotation[]): void {
this._annotations.set(annotations);
}
updateChapters(): void {
this._chapters.set(this.viewManager.getChapters());
}
open(tab?: SidebarTab): void {
if (tab) {
this._activeTab.set(tab);
}
this._isOpen.set(true);
this.autoExpandCurrentChapter();
}
close(): void {
this._isOpen.set(false);
}
toggle(tab?: SidebarTab): void {
if (this._isOpen() && (!tab || this._activeTab() === tab)) {
this.close();
} else {
this.open(tab);
}
}
setActiveTab(tab: SidebarTab): void {
this._activeTab.set(tab);
}
navigateToChapter(href: string): void {
this.viewManager.goTo(href)
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.close());
}
toggleChapterExpand(href: string): void {
if (this._expandedChapters.has(href)) {
this._expandedChapters.delete(href);
} else {
this._expandedChapters.add(href);
}
}
isChapterExpanded(href: string): boolean {
return this._expandedChapters.has(href);
}
isChapterActive(href: string): boolean {
const currentHref = this.currentChapterHref;
if (!currentHref) return false;
const normalizedItemHref = href.split('#')[0].replace(/^\//, '');
const normalizedCurrentHref = currentHref.split('#')[0].replace(/^\//, '');
return normalizedItemHref === normalizedCurrentHref || href === currentHref;
}
private autoExpandCurrentChapter(): void {
const currentHref = this.currentChapterHref;
if (!currentHref) return;
const chapters = this._chapters();
const expandParents = (items: TocItem[], parents: string[] = []): boolean => {
for (const item of items) {
const currentParents = [...parents, item.href];
const normalizedItemHref = item.href.split('#')[0].replace(/^\//, '');
const normalizedCurrentHref = currentHref.split('#')[0].replace(/^\//, '');
if (normalizedItemHref === normalizedCurrentHref || item.href === currentHref) {
parents.forEach(parentHref => this._expandedChapters.add(parentHref));
return true;
}
if (item.subitems?.length) {
if (expandParents(item.subitems, currentParents)) {
return true;
}
}
}
return false;
};
expandParents(chapters);
}
private loadBookmarks(): void {
this.bookMarkHttpService.getBookmarksForBook(this.bookId)
.pipe(takeUntil(this.destroy$))
.subscribe(bookmarks => this._bookmarks.set(bookmarks));
}
navigateToBookmark(cfi: string): void {
this.viewManager.goTo(cfi)
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.close());
}
createBookmark(): void {
this.bookmarkService.createBookmarkAtCurrentPosition(this.bookId)
.pipe(takeUntil(this.destroy$))
.subscribe(success => {
if (success) {
this.loadBookmarks();
}
});
}
toggleBookmark(): void {
const currentCfi = this.progressService.currentCfi;
if (!currentCfi) return;
const existingBookmark = this._bookmarks().find(bookmark => bookmark.cfi === currentCfi);
if (existingBookmark) {
this.deleteBookmark(existingBookmark.id!);
} else {
this.createBookmark();
}
}
deleteBookmark(bookmarkId: number): void {
this.bookMarkHttpService.deleteBookmark(bookmarkId)
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.loadBookmarks());
}
navigateToAnnotation(cfi: string): void {
this.viewManager.goTo(cfi)
.pipe(takeUntil(this.destroy$))
.subscribe(() => this.close());
}
deleteAnnotation(annotationId: number): void {
const annotations = this._annotations();
const annotation = annotations.find(a => a.id === annotationId);
if (!annotation) return;
this.annotationService.deleteAnnotation(annotationId)
.pipe(takeUntil(this.destroy$))
.subscribe(success => {
if (success) {
this.viewManager.deleteAnnotation(annotation.cfi)
.pipe(takeUntil(this.destroy$))
.subscribe();
const updatedAnnotations = annotations.filter(a => a.id !== annotationId);
this._annotations.set(updatedAnnotations);
if (this.selectionService) {
this.selectionService.setAnnotations(updatedAnnotations);
}
}
});
}
openMetadata(): void {
this.close();
this._showMetadata.next();
}
reset(): void {
this._isOpen.set(false);
this._activeTab.set('chapters');
this._bookInfo.set({id: null, title: '', authors: '', coverUrl: null});
this._chapters.set([]);
this._bookmarks.set([]);
this._annotations.set([]);
this._expandedChapters.clear();
}
}
@@ -0,0 +1,130 @@
export interface PageInfo {
percentCompleted: number;
sectionTimeText: string;
}
export interface ThemeInfo {
fg: string;
bg: string;
}
export class PageDecorator {
private static readonly DEFAULT_FONT_SIZE = '0.875rem';
static updateHeadersAndFooters(renderer: any, chapterName: string, pageInfo?: PageInfo, theme?: ThemeInfo, timeRemainingLabel?: string): void {
if (!renderer) {
return;
}
const columnCount = renderer.heads?.length || 0;
const isSingleColumn = columnCount === 1;
this.updateHeaders(renderer, chapterName, isSingleColumn, theme);
this.updateFooters(renderer, pageInfo, isSingleColumn, theme, timeRemainingLabel);
}
private static updateHeaders(renderer: any, chapterName: string, isSingleColumn: boolean, theme?: ThemeInfo): void {
if (!renderer.heads || !Array.isArray(renderer.heads) || renderer.heads.length === 0) {
return;
}
const headerStyle = this.buildStyle(theme);
renderer.heads.forEach((headElement: HTMLElement, index: number) => {
if (headElement) {
headElement.style.visibility = 'visible';
const headerContent = this.createHeaderContent(chapterName, isSingleColumn, index, headerStyle);
headElement.replaceChildren(headerContent);
}
});
}
private static updateFooters(renderer: any, pageInfo: PageInfo | undefined, isSingleColumn: boolean, theme?: ThemeInfo, timeRemainingLabel?: string): void {
if (!renderer.feet || !Array.isArray(renderer.feet) || renderer.feet.length === 0 || !pageInfo) {
return;
}
const footerStyle = this.buildStyle(theme);
renderer.feet.forEach((footElement: HTMLElement, index: number) => {
if (footElement) {
const footerContent = this.createFooterContent(pageInfo, isSingleColumn, index, renderer.feet.length, footerStyle, timeRemainingLabel);
footElement.replaceChildren(footerContent);
}
});
}
private static buildStyle(theme?: ThemeInfo): string {
const baseStyle = `width: 100%; display: flex; justify-content: space-between; align-items: center; font-size: ${this.DEFAULT_FONT_SIZE}; font-family: inherit;`;
if (theme) {
return `${baseStyle} color: ${theme.fg};`;
}
return baseStyle;
}
private static createHeaderContent(chapterName: string, isSingleColumn: boolean, index: number, style: string): HTMLElement {
const headerContent = document.createElement('div');
headerContent.style.cssText = style;
if (isSingleColumn) {
const spacer = document.createElement('span');
const chapterSpan = document.createElement('span');
chapterSpan.textContent = chapterName || '';
chapterSpan.style.textAlign = 'right';
headerContent.style.justifyContent = 'left';
headerContent.appendChild(spacer);
headerContent.appendChild(chapterSpan);
} else {
if (index === 0) {
const chapterSpan = document.createElement('span');
chapterSpan.textContent = chapterName || '';
chapterSpan.style.textAlign = 'left';
headerContent.appendChild(chapterSpan);
}
}
return headerContent;
}
private static createFooterContent(pageInfo: PageInfo, isSingleColumn: boolean, index: number, totalColumns: number, style: string, timeRemainingLabel?: string): HTMLElement {
const footerContent = document.createElement('div');
footerContent.style.cssText = style;
const text = timeRemainingLabel ?? ('Time remaining in section: ' + (pageInfo.sectionTimeText ?? '0s'));
if (isSingleColumn) {
const timeSpan = document.createElement('span');
timeSpan.textContent = text;
timeSpan.style.textAlign = 'left';
const progressSpan = document.createElement('span');
progressSpan.textContent = `${pageInfo.percentCompleted}%`;
progressSpan.style.textAlign = 'right';
footerContent.appendChild(timeSpan);
footerContent.appendChild(progressSpan);
} else {
if (index === 0) {
const timeSpan = document.createElement('span');
timeSpan.textContent = text;
timeSpan.style.textAlign = 'left';
footerContent.appendChild(timeSpan);
const spacer = document.createElement('span');
footerContent.appendChild(spacer);
} else if (index === totalColumns - 1) {
const spacer = document.createElement('span');
footerContent.appendChild(spacer);
const progressSpan = document.createElement('span');
progressSpan.textContent = `${pageInfo.percentCompleted}%`;
progressSpan.style.textAlign = 'right';
footerContent.appendChild(progressSpan);
}
}
return footerContent;
}
}
@@ -0,0 +1,266 @@
import {ChangeDetectionStrategy, Component, Input} from '@angular/core';
import {CommonModule} from '@angular/common';
export type ReaderIconName =
| 'menu'
| 'close'
| 'chevron-left'
| 'chevron-right'
| 'chevron-down'
| 'chevron-first'
| 'chevron-last'
| 'chevron-double-left'
| 'chevron-double-right'
| 'dots-vertical'
| 'bookmark'
| 'settings'
| 'book'
| 'edit'
| 'copy'
| 'trash'
| 'search'
| 'note'
| 'plus'
| 'minus'
| 'fit-page'
| 'fit-width'
| 'fit-height'
| 'actual-size'
| 'auto-fit'
| 'fullscreen'
| 'fullscreen-exit'
| 'play'
| 'pause'
| 'help'
| 'long-strip'
| 'direction-ltr'
| 'direction-rtl'
| 'magnifier';
interface IconPath {
d: string;
type?: 'path' | 'polyline' | 'line' | 'rect' | 'circle';
}
const ICONS: Record<ReaderIconName, IconPath[]> = {
// Navigation icons
'menu': [
{d: 'M3,6 L21,6', type: 'line'},
{d: 'M3,12 L21,12', type: 'line'},
{d: 'M3,18 L21,18', type: 'line'}
],
'close': [
{d: 'M18,6 L6,18', type: 'line'},
{d: 'M6,6 L18,18', type: 'line'}
],
'chevron-left': [
{d: '15,18 9,12 15,6', type: 'polyline'}
],
'chevron-right': [
{d: '9,18 15,12 9,6', type: 'polyline'}
],
'chevron-down': [
{d: '6,9 12,15 18,9', type: 'polyline'}
],
'chevron-first': [
{d: '11,17 6,12 11,7', type: 'polyline'},
{d: '18,17 13,12 18,7', type: 'polyline'}
],
'chevron-last': [
{d: '13,17 18,12 13,7', type: 'polyline'},
{d: '6,17 11,12 6,7', type: 'polyline'}
],
'chevron-double-left': [
{d: '11,17 6,12 11,7', type: 'polyline'},
{d: '18,17 13,12 18,7', type: 'polyline'}
],
'chevron-double-right': [
{d: '13,17 18,12 13,7', type: 'polyline'},
{d: '6,17 11,12 6,7', type: 'polyline'}
],
'dots-vertical': [
{d: 'M12,12 m-1,0 a1,1 0 1,0 2,0 a1,1 0 1,0 -2,0', type: 'path'},
{d: 'M12,5 m-1,0 a1,1 0 1,0 2,0 a1,1 0 1,0 -2,0', type: 'path'},
{d: 'M12,19 m-1,0 a1,1 0 1,0 2,0 a1,1 0 1,0 -2,0', type: 'path'}
],
// Action icons
'bookmark': [
{d: 'M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z'}
],
'settings': [
{d: 'M12 12m-3 0a3 3 0 1 0 6 0a3 3 0 1 0-6 0', type: 'path'},
{d: 'M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z'}
],
'book': [
{d: 'M4 19.5A2.5 2.5 0 0 1 6.5 17H20'},
{d: 'M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z'}
],
'edit': [
{d: 'M12 20h9'},
{d: 'M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z'}
],
'copy': [
{d: 'M9,9 L22,9 L22,22 L9,22 Z M9,9 Q9,9 9,9', type: 'path'},
{d: 'M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1'}
],
'trash': [
{d: 'M3 6h18'},
{d: 'M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6'},
{d: 'M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2'}
],
'search': [
{d: 'M11 11m-8 0a8 8 0 1 0 16 0a8 8 0 1 0-16 0', type: 'path'},
{d: 'M21 21l-4.35-4.35'}
],
'note': [
{d: 'M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z'},
{d: '14,2 14,8 20,8', type: 'polyline'},
{d: 'M16 13H8'},
{d: 'M16 17H8'},
{d: 'M10 9H8'}
],
'plus': [
{d: 'M12,5 L12,19', type: 'line'},
{d: 'M5,12 L19,12', type: 'line'}
],
'minus': [
{d: 'M5,12 L19,12', type: 'line'}
],
// Fit mode icons
'fit-page': [
{d: 'M3 3h18v18H3V3z'},
{d: 'M7 7h10v10H7V7z'}
],
'fit-width': [
{d: 'M21,12 L17,8', type: 'line'},
{d: 'M21,12 L17,16', type: 'line'},
{d: 'M3,12 L7,8', type: 'line'},
{d: 'M3,12 L7,16', type: 'line'},
{d: 'M3,12 L21,12', type: 'line'}
],
'fit-height': [
{d: 'M12,3 L8,7', type: 'line'},
{d: 'M12,3 L16,7', type: 'line'},
{d: 'M12,21 L8,17', type: 'line'},
{d: 'M12,21 L16,17', type: 'line'},
{d: 'M12,3 L12,21', type: 'line'}
],
'actual-size': [
{d: 'M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z'},
{d: 'M9,8 L9,16', type: 'line'},
{d: 'M12,12 L12,16', type: 'line'},
{d: 'M15,8 L15,16', type: 'line'}
],
'auto-fit': [
{d: 'M12 3v3m0 12v3M3 12h3m12 0h3'},
{d: 'M12 12m-4 0a4 4 0 1 0 8 0a4 4 0 1 0-8 0', type: 'path'}
],
'fullscreen': [
{d: 'M8 3H5a2 2 0 0 0-2 2v3'},
{d: 'M21 8V5a2 2 0 0 0-2-2h-3'},
{d: 'M3 16v3a2 2 0 0 0 2 2h3'},
{d: 'M16 21h3a2 2 0 0 0 2-2v-3'}
],
'fullscreen-exit': [
{d: 'M8 3v3a2 2 0 0 1-2 2H3'},
{d: 'M21 8h-3a2 2 0 0 1-2-2V3'},
{d: 'M3 16h3a2 2 0 0 1 2 2v3'},
{d: 'M16 21v-3a2 2 0 0 1 2-2h3'}
],
'play': [
{d: 'M5 3l14 9-14 9V3z'}
],
'pause': [
{d: 'M6,4 L6,20', type: 'line'},
{d: 'M18,4 L18,20', type: 'line'}
],
'help': [
{d: 'M12 12m-10 0a10 10 0 1 0 20 0a10 10 0 1 0-20 0', type: 'path'},
{d: 'M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3'},
{d: 'M12 17h.01'}
],
'long-strip': [
{d: 'M4 3h16v6H4z'},
{d: 'M4 9h16v6H4z'},
{d: 'M4 15h16v6H4z'}
],
'direction-ltr': [
{d: 'M5,12 L19,12', type: 'line'},
{d: 'M15,8 L19,12 L15,16', type: 'polyline'}
],
'direction-rtl': [
{d: 'M19,12 L5,12', type: 'line'},
{d: 'M9,8 L5,12 L9,16', type: 'polyline'}
],
'magnifier': [
{d: 'M10 10m-7 0a7 7 0 1 0 14 0a7 7 0 1 0-14 0', type: 'path'},
{d: 'M21 21l-5-5'},
{d: 'M7,10 L13,10', type: 'line'},
{d: 'M10,7 L10,13', type: 'line'}
]
};
@Component({
selector: 'app-reader-icon',
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [CommonModule],
template: `
<svg
[attr.width]="size"
[attr.height]="size"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
[attr.stroke-width]="strokeWidth"
stroke-linecap="round"
stroke-linejoin="round"
[class]="className">
@for (path of paths; track $index) {
@switch (path.type) {
@case ('line') {
<line
[attr.x1]="getLineCoords(path.d, 0)"
[attr.y1]="getLineCoords(path.d, 1)"
[attr.x2]="getLineCoords(path.d, 2)"
[attr.y2]="getLineCoords(path.d, 3)"/>
}
@case ('polyline') {
<polyline [attr.points]="path.d"/>
}
@default {
<path [attr.d]="path.d"/>
}
}
}
</svg>
`,
styles: [`
:host {
display: inline-flex;
align-items: center;
justify-content: center;
}
svg {
display: block;
}
`]
})
export class ReaderIconComponent {
@Input() name!: ReaderIconName;
@Input() size: number | string = 18;
@Input() strokeWidth: number | string = 2;
@Input() className = '';
get paths(): IconPath[] {
return ICONS[this.name] || [];
}
getLineCoords(d: string, index: number): string {
const coords = d.replace(/[ML]/g, ' ').trim().split(/[\s,]+/);
return coords[index] || '0';
}
}
@@ -0,0 +1,73 @@
<ng-container *transloco="let t; prefix: 'readerEbook.selectionPopup'">
@if (visible) {
<div class="popup-backdrop" (click)="onDismiss($event)"></div>
<div class="text-selection-popup"
[class.show-below]="showBelow"
[style.left.px]="position.x"
[style.top.px]="position.y">
<button class="action-btn" (click)="onSelect()" [title]="t('copyText')">
<app-reader-icon name="copy" [size]="16"></app-reader-icon>
</button>
<div class="divider"></div>
<button class="action-btn" (click)="onSearch()" [title]="t('searchInBook')">
<app-reader-icon name="search" [size]="16"></app-reader-icon>
</button>
<div class="divider"></div>
<div class="annotation-container">
<button class="action-btn" [class.active]="showAnnotationOptions" (click)="toggleAnnotationOptions()" [title]="t('annotate')">
<app-reader-icon name="edit" [size]="16"></app-reader-icon>
<app-reader-icon name="chevron-down" class="chevron" [class.open]="showAnnotationOptions" [size]="10"></app-reader-icon>
</button>
@if (showAnnotationOptions) {
<div class="annotation-options" [class.above]="!showBelow" [class.below]="showBelow">
<div class="style-buttons">
@for (style of styles; track style.value) {
<button
class="style-btn"
[class.selected]="selectedStyle === style.value"
[class.highlight-style]="style.value === 'highlight'"
[class.underline-style]="style.value === 'underline'"
[class.squiggly-style]="style.value === 'squiggly'"
[class.strikethrough-style]="style.value === 'strikethrough'"
[title]="style.label"
(click)="selectStyle(style.value)">
<span class="style-text">{{ style.icon }}</span>
</button>
}
</div>
<div class="color-buttons">
@for (color of colors; track color.value) {
<button
class="color-btn"
[style.--color]="color.value"
[class.selected]="selectedColor === color.value"
[title]="color.label"
(click)="selectColor(color.value)">
</button>
}
</div>
</div>
}
</div>
<div class="divider"></div>
<button class="action-btn" (click)="onNote()" [title]="t('addNote')">
<app-reader-icon name="note" [size]="16"></app-reader-icon>
</button>
@if (overlappingAnnotationId) {
<div class="divider"></div>
<button class="action-btn delete-btn" (click)="onDelete()" [title]="t('deleteAnnotation')">
<app-reader-icon name="trash" [size]="16"></app-reader-icon>
</button>
}
</div>
}
</ng-container>
@@ -0,0 +1,233 @@
.popup-backdrop {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 99998;
background: transparent;
}
.text-selection-popup {
position: fixed;
display: flex;
align-items: center;
gap: 4px;
padding: 6px 8px;
background: linear-gradient(180deg, #2d3139 0%, #252830 100%);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 8px;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3), 0 0 1px rgba(0, 0, 0, 0.2);
z-index: 99999;
transform: translateX(-50%);
animation: popupFadeIn 0.15s ease-out;
&.show-below {
animation: popupFadeInBelow 0.15s ease-out;
}
}
@keyframes popupFadeIn {
from {
opacity: 0;
transform: translateX(-50%) translateY(4px);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
@keyframes popupFadeInBelow {
from {
opacity: 0;
transform: translateX(-50%) translateY(-4px);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
.action-btn {
display: flex;
align-items: center;
justify-content: center;
gap: 2px;
width: 32px;
height: 32px;
padding: 0;
border: none;
border-radius: 6px;
background: transparent;
color: rgba(255, 255, 255, 0.8);
cursor: pointer;
transition: all 0.15s ease;
&:hover {
background: rgba(255, 255, 255, 0.1);
color: #fff;
}
&.active {
background: rgba(255, 255, 255, 0.12);
color: #fff;
}
svg {
flex-shrink: 0;
}
.chevron {
margin-left: -2px;
transition: transform 0.2s ease;
&.open {
transform: rotate(180deg);
}
}
}
.delete-btn {
&:hover {
background: rgba(239, 68, 68, 0.15);
color: #ef4444;
}
}
.divider {
width: 1px;
height: 20px;
background: rgba(255, 255, 255, 0.1);
margin: 0 2px;
}
.annotation-container {
position: relative;
}
.annotation-options {
position: absolute;
left: 50%;
transform: translateX(-50%);
padding: 8px;
background: linear-gradient(180deg, #2d3139 0%, #252830 100%);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 8px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
z-index: 100000;
display: flex;
flex-direction: column;
gap: 8px;
&.above {
bottom: calc(100% + 8px);
animation: slideUp 0.15s ease-out;
}
&.below {
top: calc(100% + 8px);
animation: slideDown 0.15s ease-out;
}
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateX(-50%) translateY(6px);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
@keyframes slideDown {
from {
opacity: 0;
transform: translateX(-50%) translateY(-6px);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
.style-buttons {
display: flex;
gap: 4px;
}
.style-btn {
width: 32px;
height: 28px;
padding: 0;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 4px;
background: rgba(255, 255, 255, 0.03);
color: rgba(255, 255, 255, 0.7);
font-size: 13px;
font-weight: 600;
cursor: pointer;
transition: all 0.15s ease;
.style-text {
display: block;
}
&.highlight-style .style-text {
background: linear-gradient(180deg, rgba(255, 255, 0, 0.4) 60%, transparent 60%);
}
&.underline-style .style-text {
text-decoration: underline;
text-decoration-thickness: 2px;
}
&.squiggly-style .style-text {
text-decoration: underline wavy;
}
&.strikethrough-style .style-text {
text-decoration: line-through;
}
&:hover {
border-color: rgba(255, 255, 255, 0.2);
background: rgba(255, 255, 255, 0.08);
color: #fff;
}
&.selected {
border-color: #3b82f6;
background: rgba(59, 130, 246, 0.15);
color: #fff;
}
}
.color-buttons {
display: flex;
gap: 6px;
justify-content: center;
}
.color-btn {
width: 22px;
height: 22px;
padding: 0;
border: 2px solid transparent;
border-radius: 50%;
background: var(--color);
cursor: pointer;
transition: all 0.15s ease;
&:hover {
transform: scale(1.1);
}
&.selected {
border-color: #fff;
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.5);
}
}
@@ -0,0 +1,148 @@
import {Component, EventEmitter, Input, Output} from '@angular/core';
import {CommonModule} from '@angular/common';
import {TranslocoDirective} from '@jsverse/transloco';
import {ReaderIconComponent} from './icon.component';
export type AnnotationStyle = 'highlight' | 'underline' | 'strikethrough' | 'squiggly';
export interface TextSelectionAction {
type: 'select' | 'annotate' | 'delete' | 'dismiss' | 'preview' | 'search' | 'note';
color?: string;
style?: AnnotationStyle;
annotationId?: number;
searchText?: string;
}
@Component({
selector: 'app-text-selection-popup',
standalone: true,
imports: [CommonModule, TranslocoDirective, ReaderIconComponent],
templateUrl: './selection-popup.component.html',
styleUrls: ['./selection-popup.component.scss']
})
export class TextSelectionPopupComponent {
@Input() set visible(value: boolean) {
this._visible = value;
if (value) {
this.showAnnotationOptions = false;
this.hasPreview = false;
}
}
get visible(): boolean {
return this._visible;
}
private _visible = false;
@Input() position = {x: 0, y: 0};
@Input() showBelow = false;
@Input() overlappingAnnotationId: number | null = null;
@Input() selectedText = '';
@Output() action = new EventEmitter<TextSelectionAction>();
showAnnotationOptions = false;
selectedColor = '#FACC15';
selectedStyle: AnnotationStyle = 'highlight';
private hasPreview = false;
highlightColors = [
{value: '#FACC15', label: 'Yellow'},
{value: '#4ADE80', label: 'Green'},
{value: '#38BDF8', label: 'Blue'},
{value: '#F472B6', label: 'Pink'},
{value: '#FB923C', label: 'Orange'}
];
lineColors = [
{value: '#B8860B', label: 'Dark Gold'},
{value: '#228B22', label: 'Forest Green'},
{value: '#1E90FF', label: 'Dodger Blue'},
{value: '#DC143C', label: 'Crimson'},
{value: '#FF8C00', label: 'Dark Orange'}
];
get colors() {
return this.selectedStyle === 'highlight' ? this.highlightColors : this.lineColors;
}
styles: { value: AnnotationStyle; label: string; icon: string }[] = [
{value: 'highlight', label: 'Highlight', icon: 'H'},
{value: 'underline', label: 'Underline', icon: 'U'},
{value: 'squiggly', label: 'Squiggly', icon: '~'},
{value: 'strikethrough', label: 'Strikethrough', icon: 'S'}
];
onSelect(): void {
this.action.emit({type: 'select'});
this.showAnnotationOptions = false;
this.hasPreview = false;
}
toggleAnnotationOptions(): void {
this.showAnnotationOptions = !this.showAnnotationOptions;
if (this.showAnnotationOptions) {
this.emitPreview();
}
}
selectColor(color: string): void {
this.selectedColor = color;
this.emitPreview();
}
selectStyle(style: AnnotationStyle): void {
const wasHighlight = this.selectedStyle === 'highlight';
const isHighlight = style === 'highlight';
this.selectedStyle = style;
if (wasHighlight !== isHighlight) {
this.selectedColor = isHighlight ? this.highlightColors[0].value : this.lineColors[0].value;
}
this.emitPreview();
}
private emitPreview(): void {
this.hasPreview = true;
this.action.emit({
type: 'preview',
color: this.selectedColor,
style: this.selectedStyle
});
}
onDelete(): void {
if (this.overlappingAnnotationId) {
this.action.emit({type: 'delete', annotationId: this.overlappingAnnotationId});
}
}
onSearch(): void {
this.action.emit({type: 'search', searchText: this.selectedText});
this.showAnnotationOptions = false;
this.hasPreview = false;
}
onNote(): void {
this.action.emit({type: 'note'});
this.showAnnotationOptions = false;
this.hasPreview = false;
}
onDismiss(event: MouseEvent): void {
event.stopPropagation();
event.preventDefault();
if (this.hasPreview) {
this.action.emit({
type: 'annotate',
color: this.selectedColor,
style: this.selectedStyle
});
} else {
this.action.emit({type: 'dismiss'});
}
this.showAnnotationOptions = false;
this.hasPreview = false;
}
}
@@ -0,0 +1,109 @@
export interface HeaderFooterVisibilityState {
headerVisible: boolean;
footerVisible: boolean;
}
export class ReaderHeaderFooterVisibilityManager {
private isPinned = false;
private mouseY: number;
private readonly HEADER_HEIGHT = 20;
private readonly FOOTER_HEIGHT = 40;
private readonly HEADER_TRIGGER_ZONE = 20;
private readonly FOOTER_TRIGGER_ZONE = 30;
private headerVisible = false;
private footerVisible = false;
private onStateChangeCallback?: (state: HeaderFooterVisibilityState) => void;
constructor(private windowHeight: number) {
this.mouseY = windowHeight / 2;
}
onStateChange(callback: (state: HeaderFooterVisibilityState) => void): void {
this.onStateChangeCallback = callback;
}
updateWindowHeight(height: number): void {
this.windowHeight = height;
}
handleMouseMove(mouseY: number): void {
this.mouseY = mouseY;
this.updateVisibility();
}
handleMouseLeave(): void {
if (!this.isPinned) {
this.setHeaderVisible(false);
this.setFooterVisible(false);
this.notifyStateChange();
}
}
handleHeaderZoneEnter(): void {
if (!this.isPinned) {
this.setHeaderVisible(true);
this.notifyStateChange();
}
}
handleFooterZoneEnter(): void {
if (!this.isPinned) {
this.setFooterVisible(true);
this.notifyStateChange();
}
}
togglePinned(): void {
this.isPinned = !this.isPinned;
this.updateVisibility();
}
getVisibilityState(): HeaderFooterVisibilityState {
return {
headerVisible: this.headerVisible,
footerVisible: this.footerVisible
};
}
private updateVisibility(): void {
if (
this.mouseY <= this.HEADER_TRIGGER_ZONE ||
(this.mouseY <= this.HEADER_HEIGHT && this.headerVisible) ||
this.isPinned
) {
this.setHeaderVisible(true);
} else if (this.mouseY > this.HEADER_HEIGHT) {
this.setHeaderVisible(this.isPinned);
}
const footerTop = this.windowHeight - this.FOOTER_HEIGHT;
if (
this.mouseY >= this.windowHeight - this.FOOTER_TRIGGER_ZONE ||
(this.mouseY >= footerTop && this.footerVisible) ||
this.isPinned
) {
this.setFooterVisible(true);
} else if (this.mouseY < footerTop) {
this.setFooterVisible(this.isPinned);
}
this.notifyStateChange();
}
private setHeaderVisible(visible: boolean): void {
this.headerVisible = visible;
}
private setFooterVisible(visible: boolean): void {
this.footerVisible = visible;
}
private notifyStateChange(): void {
if (this.onStateChangeCallback) {
this.onStateChangeCallback(this.getVisibilityState());
}
}
}
@@ -0,0 +1,179 @@
import {inject, Injectable} from '@angular/core';
import {Subject} from 'rxjs';
import {TranslocoService} from '@jsverse/transloco';
import {BookPatchService} from '../../../book/service/book-patch.service';
import {ReadingSessionService} from '../../../../shared/service/reading-session.service';
import {PageInfo, ThemeInfo} from '../core/view-manager.service';
import {ReaderViewManagerService} from '../core/view-manager.service';
import {ReaderStateService} from './reader-state.service';
import {ReaderAnnotationHttpService} from '../features/annotations/annotation.service';
import {ReaderBookmarkService} from '../features/bookmarks/bookmark.service';
import {BookType} from '../../../book/model/book.model';
export interface ProgressState {
cfi: string | null;
href: string | null;
chapterName: string | null;
chapterHref: string | null;
fraction: number;
pageInfo: PageInfo | undefined;
progressData: any;
}
@Injectable()
export class ReaderProgressService {
private bookPatchService = inject(BookPatchService);
private readingSessionService = inject(ReadingSessionService);
private readonly t = inject(TranslocoService);
private viewManager = inject(ReaderViewManagerService);
private stateService = inject(ReaderStateService);
private annotationService = inject(ReaderAnnotationHttpService);
private bookmarkService = inject(ReaderBookmarkService);
private bookId!: number;
private bookType!: BookType;
private bookFileId?: number;
private hasStartedSession = false;
private _currentCfi: string | null = null;
private _currentChapterName: string | null = null;
private _currentChapterHref: string | null = null;
private _currentPageInfo: PageInfo | undefined;
private _currentProgressData: any = null;
private progressSubject = new Subject<ProgressState>();
public progress$ = this.progressSubject.asObservable();
get currentCfi(): string | null {
return this._currentCfi;
}
get currentChapterName(): string | null {
return this._currentChapterName;
}
get currentChapterHref(): string | null {
return this._currentChapterHref;
}
get currentProgressData(): any {
return this._currentProgressData;
}
get currentPageInfo(): PageInfo | undefined {
return this._currentPageInfo;
}
initialize(bookId: number, bookType: BookType, bookFileId?: number): void {
this.bookId = bookId;
this.bookType = bookType;
this.bookFileId = bookFileId;
this.hasStartedSession = false;
}
handleRelocateEvent(detail: any): void {
this._currentProgressData = detail;
const cfi = detail?.cfi ?? null;
const href = detail?.pageItem?.href ?? detail?.tocItem?.href ?? null;
const percentage = typeof detail?.fraction === 'number' ? detail.fraction * 100 : null;
if (!this.hasStartedSession && cfi && percentage !== null) {
this.hasStartedSession = true;
this.readingSessionService.startSession(this.bookId, this.bookType, cfi, percentage);
}
if (cfi && percentage !== null) {
this.bookPatchService.saveEpubProgress(this.bookId, cfi, href, percentage, this.bookFileId);
this.readingSessionService.updateProgress(cfi, percentage);
}
const chapterLabel = detail?.tocItem?.label;
if (chapterLabel && chapterLabel !== this._currentChapterName) {
this._currentChapterName = chapterLabel;
this.annotationService.updateCurrentChapter(chapterLabel);
}
if (href && href !== this._currentChapterHref) {
this._currentChapterHref = href;
}
if (detail?.section) {
const percentCompleted = Math.round((detail.fraction * 100) * 10) / 10;
const totalMinutes = detail.time?.section ?? 0;
const hours = Math.floor(totalMinutes / 60);
const minutes = Math.floor(totalMinutes % 60);
const seconds = Math.round((totalMinutes - Math.floor(totalMinutes)) * 60);
const parts: string[] = [];
if (hours) parts.push(`${hours}h`);
if (minutes) parts.push(`${minutes}m`);
if (seconds || parts.length === 0) parts.push(`${seconds}s`);
this._currentPageInfo = {
percentCompleted,
sectionTimeText: parts.join(' ')
};
}
if (this.stateService.state().flow === 'paginated') {
this.updateHeadersAndFooters();
}
if (cfi) {
this._currentCfi = cfi;
this.bookmarkService.updateCurrentPosition(cfi, chapterLabel);
}
this.progressSubject.next({
cfi: this._currentCfi,
href,
chapterName: this._currentChapterName,
chapterHref: this._currentChapterHref,
fraction: detail?.fraction ?? 0,
pageInfo: this._currentPageInfo,
progressData: this._currentProgressData
});
}
updateHeadersAndFooters(): void {
const renderer = this.viewManager.getRenderer();
if (!renderer) return;
const readerState = this.stateService.state();
const theme: ThemeInfo = {
fg: readerState.theme.fg || readerState.theme.light.fg,
bg: readerState.theme.bg || readerState.theme.light.bg
};
const timeLabel = this.t.translate('readerEbook.headerFooterUtil.timeRemainingInSection', {
time: this._currentPageInfo?.sectionTimeText ?? '0s'
});
this.viewManager.updateHeadersAndFooters(
this._currentChapterName || '',
this._currentPageInfo,
theme,
timeLabel
);
}
endSession(): void {
if (this.readingSessionService.isSessionActive()) {
const progress = typeof this._currentProgressData?.fraction === 'number'
? Math.round(this._currentProgressData.fraction * 100 * 100) / 100
: undefined;
this.readingSessionService.endSession(this._currentCfi || undefined, progress);
}
}
reset(): void {
this._currentCfi = null;
this._currentChapterName = null;
this._currentChapterHref = null;
this._currentPageInfo = undefined;
this._currentProgressData = null;
this.hasStartedSession = false;
}
}
@@ -0,0 +1,234 @@
import {inject, Injectable, signal} from '@angular/core';
import {forkJoin, Observable} from 'rxjs';
import {map, tap} from 'rxjs/operators';
import {Theme, themes} from './themes.constant';
import {BookService} from '../../../book/service/book.service';
import {UserService} from '../../../settings/user-management/user.service';
import {EpubCustomFontService} from '../features/fonts/custom-font.service';
export interface ReaderState {
lineHeight: number;
justify: boolean;
hyphenate: boolean;
maxColumnCount: number;
gap: number;
fontSize: number;
theme: Theme;
maxInlineSize: number;
maxBlockSize: number;
fontFamily: string | null;
isDark: boolean;
flow: 'paginated' | 'scrolled';
}
@Injectable({
providedIn: 'root'
})
export class ReaderStateService {
private epubCustomFontService = inject(EpubCustomFontService);
private readonly BASE_FONTS = [
{name: 'Publisher\'s', value: null},
{name: 'Serif', value: 'serif'},
{name: 'Sans-Serif', value: 'sans-serif'},
{name: 'Monospace', value: 'monospace'},
{name: 'Cursive', value: 'cursive'},
];
private readonly defaultState: ReaderState = {
lineHeight: 1.5,
justify: true,
hyphenate: true,
maxColumnCount: 2,
gap: 0.05,
fontSize: 16,
theme: {
...themes[0],
fg: themes[0].dark.fg,
bg: themes[0].dark.bg,
link: themes[0].dark.link,
},
maxInlineSize: 720,
maxBlockSize: 1440,
fontFamily: null,
isDark: true,
flow: 'paginated',
};
private readonly _state = signal<ReaderState>(this.defaultState);
readonly state = this._state.asReadonly();
readonly themes = themes;
private readonly _fonts = signal<Array<{ name: string; value: string | null }>>(this.BASE_FONTS);
readonly fonts = this._fonts.asReadonly();
constructor(private bookService: BookService, private userService: UserService) {
this.loadCustomFontsIntoList();
}
private loadCustomFontsIntoList(): void {
const customFonts = this.epubCustomFontService.getCustomFonts();
const customFontOptions = customFonts.map(font => ({
name: font.fontName.replace(/\.(ttf|otf|woff|woff2)$/i, ''),
value: `custom:${font.id}`
}));
const updatedFonts = [
...this._fonts(),
...customFontOptions
];
this._fonts.set(updatedFonts);
}
refreshCustomFonts(): void {
this._fonts.set([...this.BASE_FONTS]);
this.loadCustomFontsIntoList();
}
initializeState(bookId: number, bookFileId: number): Observable<void> {
return forkJoin([
this.userService.getMyself(),
this.bookService.getBookSetting(bookId, bookFileId)
]).pipe(
tap(([myself, bookSetting]) => {
const settingScope = myself.userSettings.perBookSetting.epub;
const globalSettings = myself.userSettings.ebookReaderSetting;
const individualSetting = bookSetting?.ebookSettings;
const settings = settingScope === 'Global' ? globalSettings : (individualSetting || globalSettings);
const newState: Partial<ReaderState> = {};
if (settings.fontSize != null) newState.fontSize = settings.fontSize;
if (settings.lineHeight != null) newState.lineHeight = settings.lineHeight;
if (settings.fontFamily != null) {
if (settings.fontFamily.startsWith('custom:')) {
newState.fontFamily = settings.fontFamily;
} else {
const numericId = parseInt(settings.fontFamily, 10);
if (!isNaN(numericId) && numericId.toString() === settings.fontFamily) {
newState.fontFamily = `custom:${numericId}`;
} else {
newState.fontFamily = settings.fontFamily;
}
}
} else if ((settings as any).customFontId != null) {
newState.fontFamily = `custom:${(settings as any).customFontId}`;
}
if (settings.gap != null) newState.gap = Math.min(settings.gap, 0.5);
if (settings.hyphenate != null) newState.hyphenate = settings.hyphenate;
if (settings.justify != null) newState.justify = settings.justify;
if (settings.maxColumnCount != null) newState.maxColumnCount = settings.maxColumnCount;
if (settings.maxInlineSize != null) newState.maxInlineSize = settings.maxInlineSize;
if (settings.maxBlockSize != null) newState.maxBlockSize = settings.maxBlockSize;
if (settings.isDark != null) newState.isDark = settings.isDark;
if (settings.flow) newState.flow = settings.flow;
if (settings.theme) {
const theme = this.themes.find(t => t.name === settings.theme);
if (theme) {
newState.theme = {
...theme,
fg: settings.isDark ? theme.dark.fg : theme.light.fg,
bg: settings.isDark ? theme.dark.bg : theme.light.bg,
link: settings.isDark ? theme.dark.link : theme.light.link,
};
}
}
if (Object.keys(newState).length > 0) {
this.updateState(newState);
}
}),
map(() => void 0)
);
}
updateLineHeight(delta: number): void {
const current = this._state().lineHeight;
const newValue = Math.max(0.8, Math.min(3, current + delta));
this.updateState({lineHeight: newValue});
}
updateMaxColumnCount(delta: number): void {
const current = this._state().maxColumnCount;
const newValue = Math.max(1, Math.min(10, current + delta));
this.updateState({maxColumnCount: newValue});
}
updateGap(delta: number): void {
const current = this._state().gap;
const newValue = Math.max(0, Math.min(0.5, current + delta));
this.updateState({gap: newValue});
}
toggleJustify(): void {
this.updateState({justify: !this._state().justify});
}
toggleHyphenate(): void {
this.updateState({hyphenate: !this._state().hyphenate});
}
updateFontSize(delta: number): void {
const newFontSize = Math.max(10, Math.min(32, this._state().fontSize + delta));
this.updateState({fontSize: newFontSize});
}
setTheme(theme: Theme): void {
this.updateState({theme});
}
setFontFamily(font: string | null): void {
if (font === null) {
this.updateState({fontFamily: null});
} else if (!font.includes(':') && !isNaN(parseInt(font, 10)) && parseInt(font, 10).toString() === font) {
this.updateState({fontFamily: `custom:${font}`});
} else {
this.updateState({fontFamily: font});
}
}
updateMaxInlineSize(delta: number): void {
const newValue = Math.max(400, Math.min(1600, this._state().maxInlineSize + delta));
this.updateState({maxInlineSize: newValue});
}
updateMaxBlockSize(delta: number): void {
const newValue = Math.max(600, Math.min(2400, this._state().maxBlockSize + delta));
this.updateState({maxBlockSize: newValue});
}
toggleDarkMode() {
const currentState = this._state();
const currentTheme = currentState.theme;
const newIsDark = !currentState.isDark;
const newTheme = {
...currentTheme,
fg: newIsDark ? currentTheme.dark.fg : currentTheme.light.fg,
bg: newIsDark ? currentTheme.dark.bg : currentTheme.light.bg,
link: newIsDark ? currentTheme.dark.link : currentTheme.light.link,
};
this.updateState({theme: newTheme, isDark: newIsDark});
}
setThemeByName(themeName: string) {
const theme = this.themes.find(t => t.name === themeName);
if (theme) {
const currentState = this._state();
const newTheme = {
...theme,
fg: currentState.isDark ? theme.dark.fg : theme.light.fg,
bg: currentState.isDark ? theme.dark.bg : theme.light.bg,
link: currentState.isDark ? theme.dark.link : theme.light.link,
};
this.setTheme(newTheme);
}
}
setFlow(flow: 'paginated' | 'scrolled'): void {
this.updateState({flow});
}
private updateState(partial: Partial<ReaderState>): void {
this._state.update(current => ({...current, ...partial}));
}
}
@@ -0,0 +1,83 @@
export interface ThemeMode {
fg: string;
bg: string;
link: string;
}
export interface Theme {
name: string;
label: string;
light: ThemeMode;
dark: ThemeMode;
fg?: string;
bg?: string;
link?: string;
}
export const themes: Theme[] = [
{
name: 'default', label: 'Default',
light: {fg: '#000000', bg: '#ffffff', link: '#0066cc'},
dark: {fg: '#e0e0e0', bg: '#222222', link: '#77bbee'},
},
{
name: 'gray', label: 'Gray',
light: {fg: '#222222', bg: '#e0e0e0', link: '#4488cc'},
dark: {fg: '#c6c6c6', bg: '#444444', link: '#88ccee'},
},
{
name: 'sepia', label: 'Sepia',
light: {fg: '#5b4636', bg: '#f1e8d0', link: '#008b8b'},
dark: {fg: '#ffd595', bg: '#342e25', link: '#48d1cc'},
},
{
name: 'crimson', label: 'Crimson',
light: {fg: '#212529', bg: '#ffffff', link: '#dd0031'},
dark: {fg: '#dee2e6', bg: '#343a40', link: '#ff4081'},
},
{
name: 'meadow', label: 'Meadow',
light: {fg: '#232c16', bg: '#d7dbbd', link: '#177b4d'},
dark: {fg: '#d8deba', bg: '#333627', link: '#a6d608'},
},
{
name: 'rosewood', label: 'Rosewood',
light: {fg: '#4e1609', bg: '#f0d1d5', link: '#de3838'},
dark: {fg: '#e5c4c8', bg: '#462f32', link: '#ff646e'},
},
{
name: 'azure', label: 'Azure',
light: {fg: '#262d48', bg: '#cedef5', link: '#2d53e5'},
dark: {fg: '#babee1', bg: '#282e47', link: '#ff646e'},
},
{
name: 'dawnlight', label: 'Dawnlight',
light: {fg: '#586e75', bg: '#fdf6e3', link: '#268bd2'},
dark: {fg: '#93a1a1', bg: '#002b36', link: '#268bd2'},
},
{
name: 'ember', label: 'Ember',
light: {fg: '#3c3836', bg: '#fbf1c7', link: '#076678'},
dark: {fg: '#ebdbb2', bg: '#282828', link: '#83a598'},
},
{
name: 'aurora', label: 'Aurora',
light: {fg: '#2e3440', bg: '#eceff4', link: '#5e81ac'},
dark: {fg: '#d8dee9', bg: '#2e3440', link: '#88c0d0'},
},
{
name: 'ocean', label: 'Ocean',
light: {fg: '#0a4d4d', bg: '#e0f7fa', link: '#00838f'},
dark: {fg: '#b2dfdb', bg: '#263238', link: '#4dd0e1'},
},
{
name: 'mist', label: 'Mist',
light: {fg: '#4a148c', bg: '#f3e5f5', link: '#7b1fa2'},
dark: {fg: '#c7b6dd', bg: '#3a3150', link: '#b39ddb'},
},
{
name: 'amoled', label: 'AMOLED',
light: {fg: '#000000', bg: '#ffffff', link: '#0066cc'},
dark: {fg: '#ffffff', bg: '#000000', link: '#77bbee'},
},
];
@@ -0,0 +1,79 @@
@if (isLoading) {
<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>
<ng-template #additionalButtons>
<div id="toolbarViewer">
<div id="toolbarViewerLeft">
<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>
<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">
@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>
} @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>
}
</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>
</div>
</div>
</ng-template>
}
@@ -0,0 +1,46 @@
.loading-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
position: relative;
background: #1a1a1a;
}
::ng-deep .toolbar-btn,
::ng-deep .close-reader-btn {
display: flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border: none;
border-radius: 6px;
background: transparent;
color: #2a2a2a;
cursor: pointer;
margin-left: 4px;
margin-right: 2px;
transition: background-color 0.2s ease, color 0.2s ease;
&:hover {
background: rgba(0, 0, 0, 0.1);
}
svg {
flex-shrink: 0;
}
}
::ng-deep .pdf-dark .toolbar-btn,
::ng-deep .pdf-dark .close-reader-btn {
color: #e8e8e8;
&:hover {
background: rgba(255, 255, 255, 0.15);
}
}
::ng-deep .close-reader-btn:hover {
color: #ff6b6b;
}
@@ -0,0 +1,227 @@
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 {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';
@Component({
selector: 'app-pdf-reader',
standalone: true,
imports: [NgxExtendedPdfViewerModule, ProgressSpinner, TranslocoPipe],
templateUrl: './pdf-reader.component.html',
styleUrl: './pdf-reader.component.scss',
})
export class PdfReaderComponent implements OnInit, OnDestroy {
constructor() {
pdfDefaultOptions.rangeChunkSize = 512 * 1024;
pdfDefaultOptions.disableAutoFetch = true;
}
isLoading = true;
totalPages: number = 0;
isDarkTheme = true;
canPrint = false;
rotation: 0 | 90 | 180 | 270 = 0;
authorization = '';
page!: number;
spread!: 'off' | 'even' | 'odd';
zoom!: ZoomType;
bookData!: string;
bookId!: number;
bookFileId?: number;
private altBookType?: string;
private appSettingsSubscription!: Subscription;
private annotationSaveSubject = new Subject<void>();
private annotationSaveSubscription!: Subscription;
private annotationsLoaded = false;
private bookService = inject(BookService);
private userService = inject(UserService);
private authService = inject(AuthService);
private messageService = inject(MessageService);
private route = inject(ActivatedRoute);
private pageTitle = inject(PageTitleService);
private readingSessionService = inject(ReadingSessionService);
private location = inject(Location);
private pdfViewerService = inject(NgxExtendedPdfViewerService);
private pdfAnnotationService = inject(PdfAnnotationService);
private readonly t = inject(TranslocoService);
ngOnInit(): void {
this.annotationSaveSubscription = this.annotationSaveSubject
.pipe(debounceTime(1500))
.subscribe(() => this.persistAnnotations());
this.route.paramMap.pipe(
switchMap((params) => {
this.isLoading = true;
this.bookId = +params.get('bookId')!;
this.altBookType = this.route.snapshot.queryParamMap.get('bookType') ?? undefined;
return from(this.bookService.ensureBookDetail(this.bookId, false)).pipe(
switchMap((book) => {
if (this.altBookType) {
const altFile = book.alternativeFormats?.find(f => f.bookType === this.altBookType);
this.bookFileId = altFile?.id;
} else {
this.bookFileId = book.primaryFile?.id;
}
return forkJoin([
this.bookService.getBookSetting(this.bookId, this.bookFileId!),
this.userService.getMyself()
]).pipe(map(([bookSetting, myself]) => ({book, bookSetting, myself})));
})
);
})
).subscribe({
next: ({book, bookSetting, myself}) => {
const pdfMeta = book;
const pdfPrefs = bookSetting;
this.pageTitle.setBookPageTitle(pdfMeta);
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;
}
});
}
onPageChange(page: number): void {
if (page !== this.page) {
this.page = page;
this.updateProgress();
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0;
this.readingSessionService.updateProgress(this.page.toString(), percentage);
}
}
onZoomChange(zoom: ZoomType): void {
if (zoom !== this.zoom) {
this.zoom = zoom;
this.updateViewerSetting();
}
}
onSpreadChange(spread: 'off' | 'even' | 'odd'): void {
if (spread !== this.spread) {
this.spread = spread;
this.updateViewerSetting();
}
}
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, this.bookFileId).subscribe();
}
onPdfPagesLoaded(event: { pagesCount: number }): void {
this.totalPages = event.pagesCount;
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0;
this.readingSessionService.startSession(this.bookId, "PDF", this.page.toString(), percentage);
this.readingSessionService.updateProgress(this.page.toString(), percentage);
this.loadAnnotations();
}
onAnnotationEditorEvent(): void {
if (this.annotationsLoaded) {
this.annotationSaveSubject.next();
}
}
ngOnDestroy(): void {
if (this.readingSessionService.isSessionActive()) {
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0;
this.readingSessionService.endSession(this.page.toString(), percentage);
}
this.annotationSaveSubscription?.unsubscribe();
this.persistAnnotations();
if (this.appSettingsSubscription) {
this.appSettingsSubscription.unsubscribe();
}
this.updateProgress();
}
closeReader = (): void => {
if (this.readingSessionService.isSessionActive()) {
const percentage = this.totalPages > 0 ? Math.round((this.page / this.totalPages) * 1000) / 10 : 0;
this.readingSessionService.endSession(this.page.toString(), percentage);
}
this.location.back();
}
private loadAnnotations(): void {
this.pdfAnnotationService.getAnnotations(this.bookId).subscribe({
next: (response) => {
if (response?.data) {
const annotations = JSON.parse(response.data);
for (const annotation of annotations) {
this.pdfViewerService.addEditorAnnotation(annotation);
}
}
this.annotationsLoaded = true;
},
error: () => {
this.annotationsLoaded = true;
}
});
}
private persistAnnotations(): void {
if (!this.annotationsLoaded || !this.bookId) {
return;
}
const serialized = this.pdfViewerService.getSerializedAnnotations();
if (serialized && serialized.length > 0) {
const cleaned = serialized.map(({id, ...rest}: any) => rest);
const data = JSON.stringify(cleaned);
this.pdfAnnotationService.saveAnnotations(this.bookId, data).subscribe();
}
}
}