feat: Add custom font support for EPUB reader (#2120)

* feat: Add custom font support for EPUB reader

This commit introduces the ability to manage and use custom fonts in the EPUB reader. Key changes include:

**Backend:**
- Added `CustomFontService` for handling custom font operations.
- Introduced `CustomFontController` for API endpoints.
- Created `CustomFontEntity` and `CustomFontRepository` for database interactions.
- Added `CustomFontMapper` and `CustomFontDto` for data transformation.
- Updated `SecurityConfig` to include JWT filter for custom fonts.
- Enhanced `GlobalExceptionHandler` to handle custom font-related exceptions.
- Added database migrations:
  - `V83__Create_Custom_Font_Table.sql` for creating the custom font table.
  - `V84__Add_Custom_Font_To_Epub_Preferences.sql` for integrating custom fonts with EPUB preferences.

**Frontend:**
- Added `CustomFontsComponent` and `FontUploadDialogComponent` for managing custom fonts in the settings UI.
- Updated `EpubReaderPreferencesComponent` to include custom font options.
- Introduced `CustomFontService` and `CustomFontModel` for frontend logic and data handling.
- Enhanced `SettingsComponent` to integrate custom font management.

**Other Changes:**
- Updated `EpubViewerPreferences` and `EpubViewerPreferencesEntity` to support custom fonts.
- Modified existing components and services to accommodate the new feature.

This feature enhances the user experience by allowing personalized font choices for EPUB reading.

* fix: custom font does not apply after page layout changed

* fix: duplicate API call when change EPUB global settings

* fix: some code review items, extract shared filter logic and improve UX

- Extract AbstractQueryParameterJwtFilter base class to reduce code duplication
  between CoverJwtFilter and CustomFontJwtFilter
- Remove cssIdentifier and fontUrl fields from CustomFont model (no longer needed)
- Add font name sanitization to prevent XSS and ensure data integrity
- Improve error handling in CustomFontService with proper APIException usage
- Replace RuntimeException handler with specific IllegalStateException and
  UnsupportedOperationException handlers in GlobalExceptionHandler
- Add skeleton loading states for font previews and font dropdowns
- Improve font loading state management in epub-reader component
- Create shared custom-font.util.ts for dropdown population logic
- Use reactive font$ subscription for real-time font updates in preferences
- Make DB migrations idempotent with IF NOT EXISTS clauses
- Optimize font file validation to read only header bytes instead of entire file

* chore: re-version migration scripts

* Fix: Kobo sync missing book covers (v1.16.4) (#2147)

Co-authored-by: acx10 <acx10@users.noreply.github.com>

* Fix: correctly update book cover hash on metadata refresh (#2149)

Co-authored-by: acx10 <acx10@users.noreply.github.com>

* Introduce Vitest as the frontend Angular testing framework for Booklore (#2150)

Co-authored-by: acx10 <acx10@users.noreply.github.com>

* Add Vitest frontend tests to CI with JUnit reporting and coverage (#2151)

Co-authored-by: acx10 <acx10@users.noreply.github.com>

* Update PR template to capture frontend test details

* Add instructions for running Angular frontend tests

---------

Co-authored-by: ACX <8075870+acx10@users.noreply.github.com>
Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
Darkraise
2026-01-05 14:45:29 -07:00
committed by GitHub
co-authored by acx10 ACX
parent 9861e23333
commit 926b87872e
35 changed files with 3192 additions and 94 deletions
@@ -201,6 +201,7 @@ export interface EpubViewerSetting {
lineHeight: number;
letterSpacing: number;
spread: string;
customFontId?: number | null;
}
export interface CbxViewerSetting {
@@ -166,7 +166,8 @@
[(ngModel)]="selectedFontType"
(onChange)="changeFontType()"
[style]="{ width: '100%' }"
placeholder="Select font">
[loading]="!customFontsReady"
placeholder="Loading fonts...">
</p-select>
</div>
<div class="setting-row">
@@ -1,7 +1,7 @@
import {Component, ElementRef, inject, NgZone, OnDestroy, OnInit, ViewChild} from '@angular/core';
import ePub from 'epubjs';
import {Drawer} from 'primeng/drawer';
import {forkJoin, Subscription} from 'rxjs';
import {firstValueFrom, forkJoin, Subscription} from 'rxjs';
import {Button} from 'primeng/button';
import {InputText} from 'primeng/inputtext';
import {CommonModule, Location} from '@angular/common';
@@ -25,6 +25,9 @@ import {IconField} from 'primeng/iconfield';
import {InputIcon} from 'primeng/inputicon';
import {BookmarkEditDialogComponent} from './bookmark-edit-dialog.component';
import {BookmarkViewDialogComponent} from './bookmark-view-dialog.component';
import {CustomFontService} from '../../../../shared/service/custom-font.service';
import {CustomFont} from '../../../../shared/model/custom-font.model';
import {addCustomFontsToDropdown} from '../../../../shared/util/custom-font.util';
@Component({
selector: 'app-epub-reader',
@@ -85,6 +88,9 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
selectedSpread?: string = 'double';
lineHeight?: number;
letterSpacing?: number;
selectedCustomFontId?: number | null = null;
customFonts: CustomFont[] = [];
customFontsReady = false;
fontTypes: any[] = [
{label: "Publisher's Default", value: null},
@@ -122,14 +128,30 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
private pageTitle = inject(PageTitleService);
private bookMarkService = inject(BookMarkService);
private readingSessionService = inject(ReadingSessionService);
private customFontService = inject(CustomFontService);
epub!: Book;
ngOnInit(): void {
this.routeSubscription = this.route.paramMap.subscribe((params) => {
this.routeSubscription = this.route.paramMap.subscribe(async (params) => {
this.isLoading = true;
const bookId = +params.get('bookId')!;
// Load custom fonts FIRST and wait for them
try {
const fonts = await firstValueFrom(this.customFontService.getUserFonts());
this.customFonts = fonts;
// Wait for all fonts to load into the browser
await this.customFontService.loadAllFonts(fonts);
// Add custom fonts to dropdown
addCustomFontsToDropdown(fonts, this.fontTypes, 'select');
} catch (err) {
console.error('Failed to load custom fonts:', err);
} finally {
// Mark fonts as ready even if loading fails (allows UI to proceed)
this.customFontsReady = true;
}
const myself$ = this.userService.getMyself();
const epub$ = this.bookService.getBookByIdFromAPI(bookId, false);
const epubData$ = this.bookService.getFileContent(bookId);
@@ -159,6 +181,7 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
const resolvedLineHeight = settingScope === 'Global' ? globalSettings.lineHeight : individualSetting?.lineHeight;
const resolvedLetterSpacing = settingScope === 'Global' ? globalSettings.letterSpacing : individualSetting?.letterSpacing;
const resolvedSpread = settingScope === 'Global' ? globalSettings.spread || 'double' : individualSetting?.spread || 'double';
const resolvedCustomFontId = settingScope === 'Global' ? globalSettings.customFontId : individualSetting?.customFontId;
if (resolvedTheme != null) this.selectedTheme = resolvedTheme;
if (resolvedFontFamily != null) this.selectedFontType = resolvedFontFamily;
@@ -168,6 +191,12 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
if (resolvedFlow != null) this.selectedFlow = resolvedFlow;
if (resolvedSpread != null) this.selectedSpread = resolvedSpread;
// Set font type from settings (including custom font format)
// Don't set selectedCustomFontId yet - let applyEpubTheme() set it after verification
if (resolvedCustomFontId != null) {
this.selectedFontType = `custom:${resolvedCustomFontId}`;
}
this.initBook();
this.initRendition();
};
@@ -267,15 +296,103 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
}
}
changeFontType(): void {
if (this.rendition) {
if (this.selectedFontType) {
this.rendition.themes.font(this.selectedFontType);
} else {
this.rendition.themes.font('');
}
this.updateViewerSetting();
async changeFontType(): Promise<void> {
const result = await this.applyEpubTheme();
// Update state based on result
if (!result.success) {
// Font loading failed, clear the selection
this.selectedFontType = null;
this.selectedCustomFontId = null;
} else if (result.customFontId !== undefined) {
// Custom font loaded successfully or cleared
this.selectedCustomFontId = result.customFontId;
}
this.updateViewerSetting();
}
private async applyEpubTheme(): Promise<{ success: boolean, customFontId?: number | null }> {
if (!this.rendition) return { success: false };
// Determine font family - handle custom fonts
let fontFamily = this.selectedFontType;
let customFontToInject: CustomFont | null = null;
let customFontId: number | null = null;
if (this.selectedFontType?.startsWith('custom:')) {
const fontId = parseInt(this.selectedFontType.split(':')[1]);
const customFont = this.customFonts.find(f => f.id === fontId);
if (customFont) {
try {
await this.customFontService.loadFontFace(customFont);
if (this.customFontService.isFontLoaded(customFont.fontName)) {
fontFamily = customFont.fontName;
customFontId = fontId;
customFontToInject = customFont;
} else {
// Font didn't load properly
return { success: false };
}
} catch (error) {
// Font loading failed
console.error('Failed to load custom font:', error);
this.messageService.add({
severity: 'warn',
summary: 'Custom fonts not loaded',
detail: 'Your custom fonts could not be loaded. The reader will use default fonts instead.',
});
return { success: false };
}
}
} else {
customFontId = null;
}
// Inject or clear @font-face rules
if (customFontToInject) {
const fontUrl = this.customFontService.getFontUrl(customFontToInject.id);
const fontUrlWithToken = this.customFontService.appendToken(fontUrl);
this.rendition.themes.default({
'@font-face': [{
'font-family': `"${customFontToInject.fontName}"`,
'src': `url(${fontUrlWithToken})`,
'font-weight': 'normal',
'font-style': 'normal'
}]
});
} else {
this.rendition.themes.default({});
}
// Apply font using EPUB.js font() method
if (fontFamily) {
this.rendition.themes.font(customFontToInject ? `"${fontFamily}"` : fontFamily);
} else {
this.rendition.themes.font('');
}
// Apply theme with other settings
const baseTheme = EpubThemeUtil.themesMap.get(this.selectedTheme ?? 'black') || {};
const combinedTheme = {
...baseTheme,
body: {
...baseTheme.body,
...(this.lineHeight != null ? {'line-height': this.lineHeight} : {}),
...(this.letterSpacing != null ? {'letter-spacing': `${this.letterSpacing}em`} : {}),
},
'*': {
...baseTheme['*'],
...(this.lineHeight != null ? {'line-height': this.lineHeight} : {}),
...(this.letterSpacing != null ? {'letter-spacing': `${this.letterSpacing}em`} : {}),
},
};
this.rendition.themes.override('font-size', `${this.fontSize}%`);
this.rendition.themes.register('custom', combinedTheme);
this.rendition.themes.select('custom');
return { success: true, customFontId };
}
increaseFontSize(): void {
@@ -298,6 +415,7 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
if (this.selectedSpread === 'single' || this.selectedSpread === 'double') epubSettings.spread = this.selectedSpread;
if (this.lineHeight) epubSettings.lineHeight = this.lineHeight;
if (this.letterSpacing) epubSettings.letterSpacing = this.letterSpacing;
if (this.selectedCustomFontId != null) epubSettings.customFontId = this.selectedCustomFontId;
const bookSetting: BookSetting = {
epubSettings: epubSettings
@@ -651,7 +769,6 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
...baseTheme,
body: {
...(baseTheme.body || {}),
...(this.selectedFontType ? {'font-family': this.selectedFontType} : {}),
...(this.lineHeight != null ? {'line-height': this.lineHeight} : {}),
...(this.letterSpacing != null ? {'letter-spacing': `${this.letterSpacing}em`} : {}),
},
@@ -670,7 +787,18 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
? this.rendition.display(targetCfi)
: (this.epub?.epubProgress?.cfi ? this.rendition.display(this.epub.epubProgress.cfi) : this.rendition.display());
displayPromise.then(() => {
displayPromise.then(async () => {
// Apply custom font after rendition is displayed
const result = await this.applyEpubTheme();
// If font loading failed during initialization, clear the selection
if (!result.success) {
this.selectedFontType = null;
this.selectedCustomFontId = null;
} else if (result.customFontId !== undefined) {
this.selectedCustomFontId = result.customFontId;
}
this.updateCurrentChapter(this.rendition.currentLocation());
this.setupKeyListener();
this.trackProgress();
@@ -0,0 +1,126 @@
<div class="main-container enclosing-container">
<div class="settings-header">
<div class="header-content">
<div class="header-text">
<h2 class="settings-title">
<i class="pi pi-palette"></i>
Custom Fonts
</h2>
<p class="settings-description">
Upload and manage your own fonts for a personalized reading experience in the EPUB reader.
You have {{ customFonts.length }} of {{ maxFonts }} custom fonts.
</p>
</div>
<p-button
label="Add New Font"
icon="pi pi-plus"
(click)="openUploadDialog()"
[disabled]="customFonts.length >= maxFonts"
></p-button>
</div>
</div>
<div class="settings-content">
@if (customFonts.length === 0 && !isLoading) {
<div class="preferences-section">
<div class="empty-state">
<div class="empty-icon-wrapper">
<i class="pi pi-palette empty-icon"></i>
</div>
<h3 class="empty-title">No Custom Fonts Yet</h3>
<p class="empty-description">
Upload your favorite fonts to personalize your reading experience.<br>
Click the "Add New Font" button above to get started.
</p>
<p class="empty-hint">
<i class="pi pi-info-circle"></i>
Supported formats: <strong>TTF</strong>, <strong>OTF</strong>, <strong>WOFF</strong>, <strong>WOFF2</strong>
</p>
</div>
</div>
} @else {
<div class="preferences-section">
<div class="section-header">
<h3 class="section-title">
<i class="pi pi-book"></i>
Your Font Library
<span class="font-count">({{ customFonts.length }})</span>
</h3>
<p class="section-description">
Manage your uploaded custom fonts. Each font can be selected in the EPUB reader settings.
</p>
</div>
<div class="fonts-grid">
@for (font of customFonts; track font.id) {
<div class="settings-card font-card">
<div class="font-card-header">
<div class="font-title-group">
<h4 class="font-name">{{ font.fontName }}</h4>
<span class="format-tag">{{ font.format }}</span>
</div>
<p-button
icon="pi pi-trash"
severity="danger"
[text]="true"
[rounded]="true"
size="small"
(click)="deleteFont(font)"
pTooltip="Delete font"
tooltipPosition="left"
></p-button>
</div>
<div class="font-preview-area">
<label class="preview-label">
<i class="pi pi-eye"></i>
Preview
</label>
@if (!fontsLoadedInBrowser) {
<div class="font-preview-skeleton">
<p-skeleton width="100%" height="1rem" styleClass="mb-3"></p-skeleton>
<p-skeleton width="100%" height="1rem" styleClass="mb-3"></p-skeleton>
<p-skeleton width="85%" height="1rem" styleClass="mb-3"></p-skeleton>
<p-skeleton width="60%" height="1rem" styleClass="mb-3"></p-skeleton>
<p-skeleton width="85%" height="1rem" styleClass="mb-3"></p-skeleton>
<p-skeleton width="95%" height="0.875rem"></p-skeleton>
</div>
} @else {
<div class="font-preview" [style.font-family]="font.fontName">
<p class="preview-paragraph">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
<p class="preview-paragraph-small">
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</p>
<div class="preview-characters">
<span>ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789</span>
</div>
</div>
}
</div>
<div class="font-metadata">
<div class="metadata-row">
<span class="meta-label"><i class="pi pi-file"></i>File</span>
<span class="meta-value">{{ font.originalFileName }}</span>
</div>
<div class="metadata-row">
<span class="meta-label"><i class="pi pi-database"></i>Size</span>
<span class="meta-value">{{ formatFileSize(font.fileSize) }}</span>
</div>
<div class="metadata-row">
<span class="meta-label"><i class="pi pi-calendar"></i>Uploaded</span>
<span class="meta-value">{{ font.uploadedAt | date: 'mediumDate' }}</span>
</div>
</div>
</div>
}
</div>
</div>
}
</div>
</div>
<p-confirmDialog></p-confirmDialog>
@@ -0,0 +1,384 @@
.main-container {
width: 100%;
padding: 1rem;
height: calc(100dvh - 10.5rem);
overflow-y: auto;
border-width: 1px;
border-radius: 0.5rem;
@media (min-width: 768px) {
height: calc(100dvh - 11.65rem);
}
}
.enclosing-container {
border-color: var(--p-content-border-color);
background: var(--p-content-background);
}
.settings-header {
margin-top: 1rem;
margin-bottom: 2rem;
.header-content {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 2rem;
@media (max-width: 768px) {
flex-direction: column;
gap: 1rem;
}
}
.header-text {
flex: 1;
}
}
.settings-title {
display: flex;
align-items: center;
gap: 0.75rem;
font-size: 1.25rem;
font-weight: 700;
color: var(--p-text-color);
margin: 0 0 0.75rem 0;
.pi {
color: var(--p-primary-color);
font-size: 1.25rem;
}
}
.settings-description {
color: var(--p-text-muted-color);
font-size: 0.875rem;
line-height: 1.5;
margin-bottom: 0;
}
.settings-content {
display: flex;
flex-direction: column;
gap: 2rem;
}
.preferences-section {
@media (min-width: 768px) {
padding: 0 1rem;
}
}
.section-header {
margin-bottom: 1rem;
}
.section-title {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 1.125rem;
font-weight: 600;
color: var(--p-text-color);
margin: 0 0 0.5rem 0;
.pi {
color: var(--p-primary-color);
}
.font-count {
color: var(--p-text-muted-color);
font-size: 1rem;
font-weight: 500;
}
}
.section-description {
color: var(--p-text-muted-color);
font-size: 0.875rem;
line-height: 1.5;
margin: 0;
}
.settings-card {
border: 1px solid var(--p-content-border-color);
border-radius: 8px;
background: var(--p-content-background);
padding: 1.5rem;
display: flex;
flex-direction: column;
gap: 1rem;
}
// ==================== Empty State ====================
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
padding: 3rem 1.5rem;
min-height: 300px;
.empty-icon-wrapper {
display: flex;
align-items: center;
justify-content: center;
width: 80px;
height: 80px;
background: color-mix(in srgb, var(--p-primary-color) 10%, transparent);
border-radius: 50%;
margin-bottom: 1.5rem;
border: 3px dashed var(--p-primary-color);
.empty-icon {
font-size: 2.5rem;
color: var(--p-primary-color);
opacity: 0.7;
}
}
.empty-title {
margin: 0 0 0.75rem 0;
font-size: 1.25rem;
font-weight: 600;
color: var(--p-text-color);
}
.empty-description {
margin: 0 0 1rem 0;
font-size: 0.9375rem;
color: var(--p-text-muted-color);
max-width: 500px;
line-height: 1.6;
}
.empty-hint {
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
margin: 0;
padding: 0.75rem 1.25rem;
background: color-mix(in srgb, var(--p-primary-color) 5%, transparent);
border: 1px solid color-mix(in srgb, var(--p-primary-color) 20%, transparent);
border-radius: 6px;
font-size: 0.8125rem;
color: var(--p-text-muted-color);
max-width: 500px;
i {
color: var(--p-primary-color);
font-size: 0.875rem;
flex-shrink: 0;
}
strong {
color: var(--p-text-color);
font-weight: 600;
}
}
@media (max-width: 768px) {
padding: 2rem 1rem;
min-height: 250px;
.empty-icon-wrapper {
width: 70px;
height: 70px;
margin-bottom: 1rem;
.empty-icon {
font-size: 2rem;
}
}
.empty-title {
font-size: 1.125rem;
}
.empty-description {
font-size: 0.875rem;
max-width: 100%;
}
.empty-hint {
font-size: 0.75rem;
padding: 0.625rem 1rem;
max-width: 100%;
flex-direction: column;
text-align: center;
gap: 0.375rem;
}
}
}
// ==================== Fonts Grid ====================
.fonts-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
gap: 1.5rem;
@media (max-width: 768px) {
grid-template-columns: 1fr;
}
}
// ==================== Font Card ====================
.font-card {
padding: 0;
gap: 0;
.font-card-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 1rem;
padding: 1rem 1rem 0.75rem;
border-bottom: 1px solid var(--p-content-border-color);
.font-title-group {
flex: 1;
display: flex;
align-items: center;
gap: 0.75rem;
flex-wrap: wrap;
.font-name {
margin: 0;
font-size: 1rem;
font-weight: 600;
color: var(--p-text-color);
}
.format-tag {
display: inline-block;
padding: 0.1875rem 0.5rem;
border-radius: 4px;
background: transparent;
border: 1px solid var(--p-primary-color);
color: var(--p-primary-color);
font-size: 0.6875rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.025em;
}
}
}
.font-preview-area {
padding: 1rem;
border-bottom: 1px solid var(--p-content-border-color);
.preview-label {
display: flex;
align-items: center;
gap: 0.375rem;
font-size: 0.75rem;
font-weight: 600;
color: var(--p-text-muted-color);
text-transform: uppercase;
letter-spacing: 0.025em;
margin-bottom: 0.75rem;
i {
font-size: 0.75rem;
}
}
.font-preview {
padding: 1rem;
border: 1px solid var(--p-content-border-color);
border-radius: 6px;
background: color-mix(in srgb, var(--p-surface-ground) 30%, var(--p-content-background));
display: flex;
flex-direction: column;
gap: 0.75rem;
.preview-paragraph {
color: var(--p-text-color);
font-size: 0.9375rem;
line-height: 1.7;
margin: 0;
text-align: justify;
font-weight: 400;
}
.preview-paragraph-small {
color: var(--p-text-color);
font-size: 0.8125rem;
line-height: 1.6;
margin: 0;
text-align: justify;
font-weight: 400;
}
.preview-characters {
display: flex;
flex-direction: column;
gap: 0.25rem;
padding-top: 0.5rem;
margin-top: 0.25rem;
border-top: 1px solid var(--p-content-border-color);
span {
font-size: 0.6875rem;
color: var(--p-text-muted-color);
letter-spacing: 0.025em;
font-weight: 400;
}
}
}
.font-preview-skeleton {
padding: 1rem;
border: 1px solid var(--p-content-border-color);
border-radius: 6px;
background: color-mix(in srgb, var(--p-surface-ground) 30%, var(--p-content-background));
display: flex;
flex-direction: column;
gap: 0.75rem;
}
}
.font-metadata {
padding: 1rem;
background: color-mix(in srgb, var(--p-surface-ground) 20%, var(--p-content-background));
.metadata-row {
display: flex;
justify-content: space-between;
align-items: center;
gap: 1rem;
padding: 0.375rem 0;
&:not(:last-child) {
border-bottom: 1px solid var(--p-content-border-color);
}
.meta-label {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.8125rem;
color: var(--p-text-muted-color);
font-weight: 500;
i {
color: var(--p-primary-color);
font-size: 0.75rem;
}
}
.meta-value {
font-size: 0.8125rem;
color: var(--p-text-color);
font-weight: 500;
text-align: right;
word-break: break-word;
}
}
}
}
@@ -0,0 +1,133 @@
import {Component, OnInit} from '@angular/core';
import {CommonModule} from '@angular/common';
import {Button} from 'primeng/button';
import {MessageService} from 'primeng/api';
import {CustomFontService} from '../../../shared/service/custom-font.service';
import {CustomFont, formatFileSize} from '../../../shared/model/custom-font.model';
import {ConfirmDialog} from 'primeng/confirmdialog';
import {ConfirmationService} from 'primeng/api';
import {Tooltip} from 'primeng/tooltip';
import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog';
import {FontUploadDialogComponent} from './font-upload-dialog/font-upload-dialog.component';
import {Skeleton} from 'primeng/skeleton';
@Component({
selector: 'app-custom-fonts',
standalone: true,
imports: [CommonModule, Button, ConfirmDialog, Tooltip, Skeleton],
templateUrl: './custom-fonts.component.html',
styleUrls: ['./custom-fonts.component.scss'],
providers: [ConfirmationService, DialogService]
})
export class CustomFontsComponent implements OnInit {
customFonts: CustomFont[] = [];
isLoading = true;
fontsLoadedInBrowser = false;
uploadDialogRef: DynamicDialogRef | null = null;
readonly maxFonts = 10;
constructor(
private customFontService: CustomFontService,
private messageService: MessageService,
private confirmationService: ConfirmationService,
private dialogService: DialogService
) {}
ngOnInit(): void {
this.loadFonts();
}
async loadFonts(): Promise<void> {
this.fontsLoadedInBrowser = false;
try {
const fonts = await new Promise<CustomFont[]>((resolve, reject) => {
this.customFontService.getUserFonts().subscribe({
next: resolve,
error: reject
});
});
this.customFonts = fonts;
this.isLoading = false;
await this.customFontService.loadAllFonts(fonts);
this.fontsLoadedInBrowser = true;
} catch (error) {
console.error('Failed to load fonts:', error);
this.messageService.add({
severity: 'error',
summary: 'Error',
detail: 'Failed to load custom fonts'
});
this.isLoading = false;
this.fontsLoadedInBrowser = true;
}
}
openUploadDialog(): void {
if (this.customFonts.length >= this.maxFonts) {
this.messageService.add({
severity: 'error',
summary: 'Quota Exceeded',
detail: `Maximum ${this.maxFonts} fonts allowed per user`
});
return;
}
this.uploadDialogRef = this.dialogService.open(FontUploadDialogComponent, {
showHeader: false,
styleClass: 'dynamic-dialog-minimal',
modal: true,
dismissableMask: false,
closable: false,
width: '700px',
breakpoints: {
'768px': '95vw'
}
});
if (this.uploadDialogRef) {
this.uploadDialogRef.onClose.subscribe((font: CustomFont | null) => {
if (font) {
this.customFonts.push(font);
}
this.uploadDialogRef = null;
});
}
}
deleteFont(font: CustomFont): void {
this.confirmationService.confirm({
message: `Are you sure you want to delete the font "${font.fontName}"?`,
header: 'Delete Font',
icon: 'pi pi-exclamation-triangle',
accept: () => {
this.customFontService.deleteFont(font.id).subscribe({
next: () => {
this.customFonts = this.customFonts.filter(f => f.id !== font.id);
this.messageService.add({
severity: 'success',
summary: 'Success',
detail: `Font "${font.fontName}" deleted successfully`
});
},
error: (error) => {
console.error('Failed to delete font:', error);
this.messageService.add({
severity: 'error',
summary: 'Delete Failed',
detail: 'Failed to delete font'
});
}
});
}
});
}
formatFileSize(bytes: number): string {
return formatFileSize(bytes);
}
}
@@ -0,0 +1,131 @@
<div class="font-upload-dialog">
<div class="panel-header">
<div class="header-icon-wrapper">
<i class="pi pi-upload header-icon"></i>
</div>
<div class="header-text">
<h2 class="panel-title">Add New Font</h2>
<p class="panel-description">
Upload a custom font for your EPUB reader
</p>
</div>
<p-button
icon="pi pi-times"
(click)="cancel()"
severity="secondary"
[text]="true"
[rounded]="true"
[disabled]="isUploading"
class="close-button"/>
</div>
<div class="upload-container">
<div class="file-upload-section">
<div class="section-header">
<span class="section-title">
<i class="pi pi-file"></i>
Select Font File
</span>
</div>
@if (!selectedFile) {
<div class="upload-zone"
[class.drag-over]="isDragOver"
(click)="onUploadZoneClick()"
(drop)="onDrop($event)"
(dragover)="onDragOver($event)"
(dragleave)="onDragLeave($event)">
<input
#fileInput
type="file"
accept=".ttf,.otf,.woff,.woff2"
[disabled]="isUploading"
(change)="onFileInputChange($event)"
style="display: none;"
/>
<div class="empty-state">
<div class="empty-icon-wrapper">
<i class="pi pi-cloud-upload empty-icon"></i>
</div>
<h3 class="empty-title">Drag and Drop Font File</h3>
<p class="empty-description">
Supported formats: <strong>TTF</strong>, <strong>OTF</strong>, <strong>WOFF</strong>, <strong>WOFF2</strong>
<br/>
Maximum file size: 5 MB
</p>
</div>
</div>
} @else {
<div class="file-selected">
<div class="file-info-card">
<i class="pi pi-file"></i>
<div class="file-details">
<span class="file-name">{{ selectedFile.name }}</span>
<span class="file-meta">{{ formatFileSize(selectedFile.size) }} • {{ selectedFile.name.split('.').pop()?.toUpperCase() }}</span>
</div>
</div>
@if (previewFontFamily) {
<div class="preview-section">
<label class="preview-label">
<i class="pi pi-eye"></i>
Font Preview
</label>
<div class="font-preview" [style.font-family]="previewFontFamily">
<p class="preview-paragraph">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</p>
<p class="preview-paragraph-small">
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<div class="preview-characters">
<span>ABCDEFGHIJKLMNOPQRSTUVWXYZ</span>
<span>abcdefghijklmnopqrstuvwxyz</span>
<span>0123456789 !@#$%^&*()</span>
</div>
</div>
</div>
}
<div class="setting-item">
<div class="setting-info">
<label for="fontName" class="setting-label">Font Display Name</label>
<p class="setting-description">
This name will appear in the font selector when reading EPUB books.
</p>
</div>
<div class="setting-control">
<input
pInputText
id="fontName"
[(ngModel)]="uploadedFontName"
placeholder="e.g., Bookerly, Open Sans, Merriweather"
[disabled]="isUploading"
class="font-name-input"
/>
</div>
</div>
</div>
}
</div>
<div class="dialog-footer">
<p-button
label="Cancel"
icon="pi pi-times"
severity="secondary"
[outlined]="true"
(click)="cancel()"
[disabled]="isUploading"
></p-button>
<p-button
label="Upload Font"
icon="pi pi-upload"
(click)="uploadFont()"
[disabled]="isUploading || !selectedFile || !uploadedFontName.trim()"
[loading]="isUploading"
></p-button>
</div>
</div>
@@ -0,0 +1,443 @@
.font-upload-dialog {
width: 700px;
max-width: 700px;
display: flex;
flex-direction: column;
@media (max-width: 768px) {
width: 100%;
max-width: 100%;
}
}
.panel-header {
position: relative;
display: flex;
align-items: center;
gap: 1rem;
padding: 1.5rem 1.5rem 1.25rem 1.5rem;
border-radius: 10px 10px 0 0;
border: 1px solid var(--border-color);
border-bottom: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
.header-icon-wrapper {
display: flex;
align-items: center;
justify-content: center;
width: 48px;
height: 48px;
background: var(--primary-color);
border-radius: 10px;
.header-icon {
font-size: 1.5rem;
color: var(--primary-contrast-color);
}
}
.header-text {
flex: 1;
.panel-title {
margin: 0 0 0.25rem 0;
font-size: 1.25rem;
font-weight: 600;
color: var(--text-color);
}
.panel-description {
margin: 0;
font-size: 0.875rem;
color: var(--text-secondary-color);
}
}
.close-button {
position: absolute;
top: 0.75rem;
right: 0.75rem;
}
@media (max-width: 480px) {
padding: 1rem;
.header-icon-wrapper {
width: 40px;
height: 40px;
.header-icon {
font-size: 1.25rem;
}
}
.header-text {
.panel-title {
font-size: 1.125rem;
}
.panel-description {
font-size: 0.8rem;
}
}
.close-button {
top: 0.5rem;
right: 0.5rem;
::ng-deep .p-button {
width: 2rem;
height: 2rem;
}
}
}
}
.upload-container {
display: flex;
flex-direction: column;
gap: 1rem;
padding: 1.75rem;
background: var(--card-background);
border: 1px solid var(--border-color);
border-radius: 0 0 10px 10px;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
@media (max-width: 480px) {
padding: 1rem;
gap: 1rem;
}
}
.file-upload-section {
display: flex;
flex-direction: column;
.section-header {
display: flex;
align-items: center;
justify-content: center;
padding: 0.625rem 0.875rem;
background: var(--overlay-background);
border-radius: 6px;
.section-title {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: 0.9rem;
font-weight: 600;
color: var(--text-color);
i {
color: var(--primary-color);
font-size: 1rem;
}
}
@media (max-width: 480px) {
padding: 0.5rem 0.625rem;
.section-title {
font-size: 0.85rem;
}
}
}
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
padding: 1.5rem 1rem;
.empty-icon-wrapper {
display: flex;
align-items: center;
justify-content: center;
width: 80px;
height: 80px;
background: var(--overlay-background);
border-radius: 50%;
margin-bottom: 1rem;
border: 3px dashed var(--border-color);
.empty-icon {
font-size: 2.5rem;
color: var(--text-secondary-color);
opacity: 0.6;
}
}
.empty-title {
margin: 0 0 0.5rem 0;
font-size: 1.125rem;
font-weight: 600;
color: var(--text-color);
}
.empty-description {
margin: 0;
font-size: 0.875rem;
color: var(--text-secondary-color);
max-width: 450px;
line-height: 1.5;
strong {
color: var(--text-color);
}
}
@media (max-width: 480px) {
padding: 1.5rem 0.75rem;
min-height: 180px;
.empty-icon-wrapper {
width: 70px;
height: 70px;
margin-bottom: 0.75rem;
.empty-icon {
font-size: 2rem;
}
}
.empty-title {
font-size: 1rem;
}
.empty-description {
font-size: 0.8rem;
max-width: 100%;
}
}
}
}
// ==================== Upload Zone ====================
.upload-zone {
padding: 2rem;
text-align: center;
border: 2px dashed var(--border-color);
border-radius: 8px;
background: var(--ground-background);
transition: all 0.3s ease;
cursor: pointer;
&:hover:not(.disabled) {
border-color: var(--primary-color);
background: color-mix(
in srgb,
var(--primary-color) 3%,
var(--ground-background)
);
}
&.drag-over {
border-color: var(--primary-color);
background: color-mix(
in srgb,
var(--primary-color) 8%,
var(--ground-background)
);
.empty-icon-wrapper {
border-color: var(--primary-color);
.empty-icon {
color: var(--primary-color);
transform: scale(1.1);
}
}
}
&.disabled {
cursor: not-allowed;
opacity: 0.6;
}
}
// ==================== File Selected ====================
.file-selected {
display: flex;
flex-direction: column;
gap: 1.5rem;
width: 100%;
max-width: 100%;
overflow: hidden;
}
.file-info-card {
display: flex;
align-items: center;
gap: 1rem;
padding: 1rem;
border: 1px solid var(--border-color);
border-radius: 6px;
background: var(--overlay-background);
width: 100%;
max-width: 100%;
overflow: hidden;
i {
font-size: 2rem;
color: var(--primary-color);
flex-shrink: 0;
}
.file-details {
flex: 1;
display: flex;
flex-direction: column;
gap: 0.25rem;
min-width: 0;
overflow: hidden;
.file-name {
font-weight: 600;
color: var(--text-color);
font-size: 0.9375rem;
word-break: break-word;
overflow-wrap: break-word;
}
.file-meta {
font-size: 0.8125rem;
color: var(--text-secondary-color);
}
}
}
.preview-section {
display: flex;
flex-direction: column;
gap: 0.75rem;
width: 100%;
max-width: 100%;
overflow: hidden;
.preview-label {
display: flex;
align-items: center;
gap: 0.375rem;
font-size: 0.75rem;
font-weight: 600;
color: var(--text-secondary-color);
text-transform: uppercase;
letter-spacing: 0.025em;
i {
font-size: 0.75rem;
color: var(--primary-color);
}
}
.font-preview {
padding: 1.5rem;
border: 1px solid var(--border-color);
border-radius: 6px;
background: var(--overlay-background);
display: flex;
flex-direction: column;
gap: 1rem;
max-height: 300px;
overflow-y: auto;
width: 100%;
max-width: 100%;
box-sizing: border-box;
.preview-paragraph {
color: var(--text-color);
font-size: 1rem;
line-height: 1.7;
margin: 0;
text-align: justify;
font-weight: 400;
}
.preview-paragraph-small {
color: var(--text-color);
font-size: 0.875rem;
line-height: 1.6;
margin: 0;
text-align: justify;
font-weight: 400;
}
.preview-characters {
display: flex;
flex-direction: column;
gap: 0.375rem;
padding-top: 0.75rem;
margin-top: 0.5rem;
border-top: 1px solid var(--border-color);
span {
font-size: 0.75rem;
color: var(--text-secondary-color);
letter-spacing: 0.025em;
font-weight: 400;
}
}
}
}
.setting-item {
display: flex;
flex-direction: column;
gap: 0.75rem;
padding: 0;
width: 100%;
max-width: 100%;
}
.setting-info {
width: 100%;
.setting-label {
display: block;
font-weight: 600;
color: var(--text-color);
font-size: 1rem;
margin-bottom: 0.5rem;
}
.setting-description {
color: var(--text-secondary-color);
font-size: 0.875rem;
line-height: 1.5;
margin: 0;
}
}
.setting-control {
display: flex;
flex-direction: column;
gap: 0.75rem;
width: 100%;
.font-name-input {
width: 100%;
}
}
// ==================== Dialog Footer ====================
.dialog-footer {
display: flex;
gap: 0.75rem;
justify-content: flex-end;
padding: 1rem 1.5rem 1.5rem;
border-top: 1px solid var(--border-color);
width: 100%;
max-width: 100%;
box-sizing: border-box;
@media (max-width: 768px) {
flex-direction: column;
::ng-deep .p-button {
width: 100%;
}
}
}
@@ -0,0 +1,244 @@
import {Component, ViewChild, ElementRef, OnDestroy} from '@angular/core';
import {CommonModule} from '@angular/common';
import {Button} from 'primeng/button';
import {MessageService} from 'primeng/api';
import {CustomFontService} from '../../../../shared/service/custom-font.service';
import {formatFileSize} from '../../../../shared/model/custom-font.model';
import {InputText} from 'primeng/inputtext';
import {FormsModule} from '@angular/forms';
import {DynamicDialogRef} from 'primeng/dynamicdialog';
@Component({
selector: 'app-font-upload-dialog',
standalone: true,
imports: [CommonModule, Button, InputText, FormsModule],
templateUrl: './font-upload-dialog.component.html',
styleUrls: ['./font-upload-dialog.component.scss']
})
export class FontUploadDialogComponent implements OnDestroy {
@ViewChild('fileInput') fileInput!: ElementRef<HTMLInputElement>;
isUploading = false;
uploadedFontName = '';
selectedFile: File | null = null;
isDragOver = false;
previewFontFamily: string | null = null;
isLoadingPreview = false;
currentPreviewToken: number | null = null;
readonly maxFileSize = 5242880;
readonly maxFonts = 10;
readonly acceptedFormats = ['.ttf', '.otf', '.woff', '.woff2'];
constructor(
private customFontService: CustomFontService,
private messageService: MessageService,
private dialogRef: DynamicDialogRef
) {}
onUploadZoneClick(): void {
if (this.isUploading) {
return;
}
this.fileInput.nativeElement.click();
}
onFileInputChange(event: Event): void {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
if (!this.validateFile(file)) {
input.value = '';
return;
}
this.processFile(file);
input.value = '';
}
async loadFontPreview(file: File): Promise<void> {
this.cleanupPreviewFont();
const previewToken = Date.now();
this.currentPreviewToken = previewToken;
if (this.isLoadingPreview) {
console.log('Cancelling previous preview load');
}
this.isLoadingPreview = true;
try {
const previewFontName = `preview-font-${previewToken}`;
const arrayBuffer = await file.arrayBuffer();
if (this.currentPreviewToken !== previewToken) {
console.log('Preview operation cancelled - newer preview started');
return;
}
const fontFace = new FontFace(previewFontName, arrayBuffer);
await fontFace.load();
if (this.currentPreviewToken !== previewToken) {
console.log('Preview operation cancelled after load - newer preview started');
document.fonts.delete(fontFace);
return;
}
document.fonts.add(fontFace);
this.previewFontFamily = `"${previewFontName}"`;
} catch (error) {
if (this.currentPreviewToken === previewToken) {
console.error('Failed to load font preview:', error);
this.previewFontFamily = null;
this.messageService.add({
severity: 'warn',
summary: 'Preview Failed',
detail: 'Unable to preview font, but you can still upload it'
});
}
} finally {
if (this.currentPreviewToken === previewToken) {
this.isLoadingPreview = false;
}
}
}
uploadFont(): void {
if (!this.selectedFile) {
this.messageService.add({
severity: 'warn',
summary: 'No File Selected',
detail: 'Please select a font file to upload'
});
return;
}
this.isUploading = true;
this.customFontService.uploadFont(this.selectedFile, this.uploadedFontName || undefined).subscribe({
next: (font) => {
this.messageService.add({
severity: 'success',
summary: 'Success',
detail: `Font "${font.fontName}" uploaded successfully`
});
this.isUploading = false;
this.dialogRef.close(font); // Return the uploaded font
},
error: (error) => {
console.error('Failed to upload font:', error);
let errorMessage = 'Failed to upload font';
if (error.status === 400) {
errorMessage = 'Invalid file format or quota exceeded';
}
this.messageService.add({
severity: 'error',
summary: 'Upload Failed',
detail: errorMessage
});
this.isUploading = false;
this.selectedFile = null;
this.uploadedFontName = '';
this.cleanupPreviewFont();
}
});
}
formatFileSize(bytes: number): string {
return formatFileSize(bytes);
}
cancel(): void {
this.cleanupPreviewFont();
this.dialogRef.close(null);
}
onDragOver(event: DragEvent): void {
event.preventDefault();
event.stopPropagation();
this.isDragOver = true;
}
onDragLeave(event: DragEvent): void {
event.preventDefault();
event.stopPropagation();
this.isDragOver = false;
}
onDrop(event: DragEvent): void {
event.preventDefault();
event.stopPropagation();
this.isDragOver = false;
const files = event.dataTransfer?.files;
if (files && files.length > 0) {
const file = files[0];
if (!this.validateFile(file)) {
return;
}
this.processFile(file);
}
}
private validateFile(file: File): boolean {
const fileName = file.name.toLowerCase();
const isValidFormat = this.acceptedFormats.some(format => fileName.endsWith(format));
if (!isValidFormat) {
this.messageService.add({
severity: 'error',
summary: 'Invalid File Type',
detail: 'Please upload a TTF, OTF, WOFF, or WOFF2 font file'
});
return false;
}
if (file.size > this.maxFileSize) {
this.messageService.add({
severity: 'error',
summary: 'File Too Large',
detail: `File size must not exceed ${this.formatFileSize(this.maxFileSize)}`
});
return false;
}
return true;
}
private processFile(file: File): void {
this.selectedFile = file;
this.uploadedFontName = file.name.replace(/\.[^/.]+$/, '');
this.loadFontPreview(file);
}
cleanupPreviewFont(): void {
if (this.previewFontFamily) {
const fontName = this.previewFontFamily.replace(/"/g, '');
try {
for (const font of document.fonts) {
if (font.family === fontName) {
document.fonts.delete(font);
}
}
} catch (error) {
console.error('Failed to cleanup preview font:', fontName, error);
}
this.previewFontFamily = null;
}
this.currentPreviewToken = null;
this.isLoadingPreview = false;
}
ngOnDestroy(): void {
this.cleanupPreviewFont();
}
}
@@ -37,13 +37,22 @@
type="button"
class="option-button font-button"
[class.selected]="selectedFont === font.key"
[class.separator]="font.key === 'separator'"
[attr.data-font]="font.key"
[disabled]="font.key === 'separator'"
(click)="selectedFont = font.key"
[pTooltip]="font.name"
tooltipPosition="bottom">
<span class="option-text">{{ font.displayName }}</span>
<span class="option-text"
[style.font-family]="font.key && font.key.startsWith('custom:') ? getCustomFontName(font.key) : null">
{{ font.displayName }}
</span>
</button>
}
@if (!customFontsReady) {
<p-skeleton width="3.5rem" height="2.5rem" borderRadius="6px"></p-skeleton>
}
</div>
</div>
<p class="setting-description">
@@ -194,6 +194,28 @@
&[data-font="monospace"] .option-text {
font-family: 'Courier New', monospace;
}
// Custom font buttons use the loaded font
&[data-font^="custom:"] .option-text {
font-size: 0.875rem;
}
}
&.separator {
cursor: default;
pointer-events: none;
opacity: 0.6;
background: transparent;
border-color: transparent;
font-weight: 600;
color: var(--p-text-muted-color);
min-width: auto;
padding: 0.25rem 0.5rem;
&:hover {
transform: none;
box-shadow: none;
}
}
}
}
@@ -1,27 +1,37 @@
import {Component, inject, Input} from '@angular/core';
import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core';
import {Button} from 'primeng/button';
import {FormsModule} from '@angular/forms';
import {ReaderPreferencesService} from '../reader-preferences-service';
import {UserSettings} from '../../user-management/user.service';
import {Tooltip} from 'primeng/tooltip';
import {CustomFontService} from '../../../../shared/service/custom-font.service';
import {CustomFont} from '../../../../shared/model/custom-font.model';
import {skip, Subject, takeUntil} from 'rxjs';
import {addCustomFontsToDropdown} from '../../../../shared/util/custom-font.util';
import {Skeleton} from 'primeng/skeleton';
@Component({
selector: 'app-epub-reader-preferences-component',
imports: [
Button,
FormsModule,
Tooltip
Tooltip,
Skeleton
],
templateUrl: './epub-reader-preferences-component.html',
styleUrl: './epub-reader-preferences-component.scss'
})
export class EpubReaderPreferencesComponent {
export class EpubReaderPreferencesComponent implements OnInit, OnDestroy {
@Input() userSettings!: UserSettings;
private readonly readerPreferencesService = inject(ReaderPreferencesService);
private readonly customFontService = inject(CustomFontService);
private readonly destroy$ = new Subject<void>();
readonly fonts = [
customFonts: CustomFont[] = [];
fonts = [
{name: 'Book Default', displayName: 'Default', key: null},
{name: 'Serif', displayName: 'Aa', key: 'serif'},
{name: 'Sans Serif', displayName: 'Aa', key: 'sans-serif'},
@@ -58,6 +68,81 @@ export class EpubReaderPreferencesComponent {
{name: 'Dark Brown', key: 'dark-brown', color: '#3E2723'}
];
customFontsReady = false;
ngOnInit(): void {
this.subscribeToFontUpdates();
this.customFontService.getUserFonts().subscribe({
next: () => {
this.customFontsReady = true;
},
error: (err) => {
console.error('Failed to load custom fonts:', err);
this.customFontsReady = true;
}
});
}
ngOnDestroy(): void {
this.destroy$.next();
this.destroy$.complete();
}
private subscribeToFontUpdates(): void {
this.customFontService.fonts$
.pipe(
skip(1),
takeUntil(this.destroy$)
)
.subscribe(async fonts => {
try {
const selectedFontDeleted = this.isCurrentlySelectedFontDeleted(fonts);
if (this.hasCustomFontsChanged(fonts)) {
this.customFonts = fonts;
await this.customFontService.loadAllFonts(fonts);
this.updateFontsDropdown(fonts);
}
if (selectedFontDeleted) {
this.resetToDefaultFont();
}
} catch (err) {
console.error('Failed to process custom fonts:', err);
}
});
}
private hasCustomFontsChanged(newFonts: CustomFont[]): boolean {
if (newFonts.length !== this.customFonts.length) {
return true;
}
const newIds = new Set(newFonts.map(f => f.id));
const currentIds = new Set(this.customFonts.map(f => f.id));
return newFonts.some(f => !currentIds.has(f.id)) || this.customFonts.some(f => !newIds.has(f.id));
}
private updateFontsDropdown(fonts: CustomFont[]): void {
this.fonts = this.fonts.filter(font => !font.key || !font.key.startsWith('custom:'));
addCustomFontsToDropdown(fonts, this.fonts, 'preference');
}
private isCurrentlySelectedFontDeleted(newFonts: CustomFont[]): boolean {
const customFontId = this.userSettings.epubReaderSetting.customFontId;
if (!customFontId) {
return false;
}
const fontStillExists = newFonts.some(font => font.id === customFontId);
return !fontStillExists;
}
private resetToDefaultFont(): void {
console.log('Selected custom font was deleted, resetting to default font');
this.selectedFont = null;
}
get selectedTheme(): string | null {
return this.userSettings.epubReaderSetting.theme;
}
@@ -70,14 +155,40 @@ export class EpubReaderPreferencesComponent {
}
get selectedFont(): string | null {
// If customFontId is set, return the custom font key
if (this.userSettings.epubReaderSetting.customFontId) {
return `custom:${this.userSettings.epubReaderSetting.customFontId}`;
}
return this.userSettings.epubReaderSetting.font;
}
set selectedFont(value: string | null) {
if (typeof value === "string") {
// Handle custom fonts
if (value && value.startsWith('custom:')) {
const fontIdStr = value.split(':')[1];
const fontId = parseInt(fontIdStr, 10);
if (isNaN(fontId)) {
console.error('Invalid custom font ID:', value);
return;
}
// Update both fields in local state
this.userSettings.epubReaderSetting.customFontId = fontId;
this.userSettings.epubReaderSetting.font = value;
} else {
// Clear customFontId and set font in local state
this.userSettings.epubReaderSetting.customFontId = null;
if (typeof value === "string") {
this.userSettings.epubReaderSetting.font = value;
} else {
// value is null - set to default font
this.userSettings.epubReaderSetting.font = null as any;
}
}
this.readerPreferencesService.updatePreference(['epubReaderSetting', 'font'], value);
// Single API call with entire epubReaderSetting object
this.readerPreferencesService.updatePreference(['epubReaderSetting'], this.userSettings.epubReaderSetting);
}
get selectedFlow(): string | null {
@@ -122,4 +233,13 @@ export class EpubReaderPreferencesComponent {
this.fontSize -= 10;
}
}
getCustomFontName(fontKey: string): string | null {
if (!fontKey || !fontKey.startsWith('custom:')) {
return null;
}
const fontId = parseInt(fontKey.split(':')[1]);
const customFont = this.customFonts.find(f => f.id === fontId);
return customFont ? customFont.fontName : null;
}
}
@@ -6,6 +6,9 @@
<p-tab [value]="SettingsTab.ReaderSettings">
<i class="pi pi-book"></i> Reader
</p-tab>
<p-tab [value]="SettingsTab.CustomFonts">
<i class="pi pi-palette"></i> Custom Fonts
</p-tab>
<p-tab [value]="SettingsTab.ViewPreferences">
<i class="pi pi-desktop"></i> View
</p-tab>
@@ -56,6 +59,9 @@
<p-tabpanel [value]="SettingsTab.ReaderSettings">
<app-reader-preferences></app-reader-preferences>
</p-tabpanel>
<p-tabpanel [value]="SettingsTab.CustomFonts">
<app-custom-fonts></app-custom-fonts>
</p-tabpanel>
<p-tabpanel [value]="SettingsTab.ViewPreferences">
<app-view-preferences-parent></app-view-preferences-parent>
</p-tabpanel>
@@ -17,9 +17,11 @@ import {DeviceSettingsComponent} from './device-settings/device-settings-compone
import {LibraryMetadataSettingsComponent} from './library-metadata-settings/library-metadata-settings.component';
import { PageTitleService } from "../../shared/service/page-title.service";
import {EmailV2Component} from './email-v2/email-v2.component';
import {CustomFontsComponent} from './custom-fonts/custom-fonts.component';
export enum SettingsTab {
ReaderSettings = 'reader',
CustomFonts = 'custom-fonts',
ViewPreferences = 'view',
DeviceSettings = 'device',
UserManagement = 'user',
@@ -47,6 +49,7 @@ export enum SettingsTab {
AuthenticationSettingsComponent,
ViewPreferencesParentComponent,
ReaderPreferences,
CustomFontsComponent,
MetadataSettingsComponent,
DeviceSettingsComponent,
FileNamingPatternComponent,
@@ -105,6 +105,7 @@ export interface EpubReaderSetting {
lineHeight: number;
margin: number;
letterSpacing: number;
customFontId?: number | null;
}
export interface CbxReaderSetting {
@@ -0,0 +1,23 @@
export interface CustomFont {
id: number;
fontName: string;
originalFileName: string;
format: FontFormat;
fileSize: number;
uploadedAt: string;
}
export enum FontFormat {
TTF = 'TTF',
OTF = 'OTF',
WOFF = 'WOFF',
WOFF2 = 'WOFF2'
}
export function formatFileSize(bytes: number): string {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
}
@@ -0,0 +1,122 @@
import {Injectable, inject} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {BehaviorSubject, Observable, tap} from 'rxjs';
import {CustomFont} from '../model/custom-font.model';
import {API_CONFIG} from '../../core/config/api-config';
import {AuthService} from './auth.service';
@Injectable({
providedIn: 'root'
})
export class CustomFontService {
private apiUrl = `${API_CONFIG.BASE_URL}/api/v1/custom-fonts`;
private fontsSubject = new BehaviorSubject<CustomFont[]>([]);
public fonts$ = this.fontsSubject.asObservable();
private loadedFonts = new Set<string>();
private authService = inject(AuthService);
constructor(private http: HttpClient) {}
uploadFont(file: File, fontName?: string): Observable<CustomFont> {
const formData = new FormData();
formData.append('file', file);
if (fontName) {
formData.append('fontName', fontName);
}
return this.http.post<CustomFont>(`${this.apiUrl}/upload`, formData).pipe(
tap(font => {
// Add to cache
const currentFonts = this.fontsSubject.value;
this.fontsSubject.next([...currentFonts, font]);
// Load the font immediately
this.loadFontFace(font).catch(err => {
console.error('Failed to load font after upload:', err);
});
})
);
}
getUserFonts(): Observable<CustomFont[]> {
return this.http.get<CustomFont[]>(this.apiUrl).pipe(
tap(fonts => {
this.fontsSubject.next(fonts);
})
);
}
deleteFont(fontId: number): Observable<void> {
return this.http.delete<void>(`${this.apiUrl}/${fontId}`).pipe(
tap(() => {
// Remove from cache
const currentFonts = this.fontsSubject.value;
const updatedFonts = currentFonts.filter(f => f.id !== fontId);
this.fontsSubject.next(updatedFonts);
// Remove from loaded fonts set and document.fonts
const deletedFont = currentFonts.find(f => f.id === fontId);
if (deletedFont) {
this.removeFontFace(deletedFont.fontName);
this.loadedFonts.delete(deletedFont.fontName);
}
})
);
}
getFontUrl(fontId: number): string {
return `${this.apiUrl}/${fontId}/file`;
}
private getToken(): string | null {
return this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken();
}
public appendToken(url: string): string {
const token = this.getToken();
return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url;
}
async loadFontFace(font: CustomFont): Promise<void> {
if (this.loadedFonts.has(font.fontName)) {
return;
}
try {
const absoluteFontUrl = this.getFontUrl(font.id);
const fontUrlWithToken = this.appendToken(absoluteFontUrl);
const fontFace = new FontFace(
font.fontName,
`url(${fontUrlWithToken})`,
{
weight: 'normal',
style: 'normal'
}
);
await fontFace.load();
document.fonts.add(fontFace);
this.loadedFonts.add(font.fontName);
} catch (error) {
console.error(`Failed to load font ${font.fontName}:`, error);
throw error;
}
}
async loadAllFonts(fonts: CustomFont[]): Promise<void> {
const loadPromises = fonts.map(font => this.loadFontFace(font));
await Promise.allSettled(loadPromises);
}
isFontLoaded(fontName: string): boolean {
return this.loadedFonts.has(fontName);
}
private removeFontFace(fontName: string): void {
for (const font of document.fonts) {
if (font.family === fontName) {
document.fonts.delete(font);
}
}
}
}
@@ -0,0 +1,74 @@
import { CustomFont } from '../model/custom-font.model';
/**
* Font dropdown item for epub-reader component (PrimeNG Select format)
*/
export interface FontDropdownItem {
label: string;
value: string | null;
disabled?: boolean;
}
/**
* Font dropdown item for epub-reader-preferences component
*/
export interface FontPreferenceItem {
name: string;
displayName: string;
key: string | null;
}
const MAX_FONT_DISPLAY_LENGTH = 12;
/**
* Adds custom fonts to a dropdown array with a separator.
* Removes any existing separator before adding to prevent duplicates.
*/
export function addCustomFontsToDropdown<T extends FontDropdownItem | FontPreferenceItem>(
fonts: CustomFont[],
targetArray: T[],
format: 'select' | 'preference'
): void {
if (fonts.length === 0) {
return;
}
if (format === 'select') {
const separatorIndex = (targetArray as FontDropdownItem[]).findIndex(item => item.value === 'separator');
if (separatorIndex !== -1) {
targetArray.splice(separatorIndex, 1);
}
(targetArray as FontDropdownItem[]).push({
label: '--- Custom Fonts ---',
value: 'separator',
disabled: true
});
fonts.forEach(font => {
(targetArray as FontDropdownItem[]).push({
label: font.fontName,
value: `custom:${font.id}`
});
});
} else {
const separatorIndex = (targetArray as FontPreferenceItem[]).findIndex(item => item.key === 'separator');
if (separatorIndex !== -1) {
targetArray.splice(separatorIndex, 1);
}
(targetArray as FontPreferenceItem[]).push({
name: '--- Custom Fonts ---',
displayName: '---',
key: 'separator'
});
fonts.forEach(font => {
(targetArray as FontPreferenceItem[]).push({
name: font.fontName,
displayName: font.fontName.substring(0, MAX_FONT_DISPLAY_LENGTH),
key: `custom:${font.id}`
});
});
}
}