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
@@ -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();