Cache epub fonts for faster page refresh

This commit is contained in:
acx10
2026-01-09 09:33:25 -07:00
parent 34ac70c251
commit 810f3994d4
@@ -91,6 +91,7 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
selectedCustomFontId?: number | null = null; selectedCustomFontId?: number | null = null;
customFonts: CustomFont[] = []; customFonts: CustomFont[] = [];
customFontsReady = false; customFontsReady = false;
private customFontBlobUrls = new Map<number, string>();
fontTypes: any[] = [ fontTypes: any[] = [
{label: "Publisher's Default", value: null}, {label: "Publisher's Default", value: null},
@@ -137,18 +138,15 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
this.isLoading = true; this.isLoading = true;
const bookId = +params.get('bookId')!; const bookId = +params.get('bookId')!;
// Load custom fonts FIRST and wait for them
try { try {
const fonts = await firstValueFrom(this.customFontService.getUserFonts()); const fonts = await firstValueFrom(this.customFontService.getUserFonts());
this.customFonts = fonts; this.customFonts = fonts;
// Wait for all fonts to load into the browser
await this.customFontService.loadAllFonts(fonts); await this.customFontService.loadAllFonts(fonts);
// Add custom fonts to dropdown await this.cacheCustomFontsAsBlobs(fonts);
addCustomFontsToDropdown(fonts, this.fontTypes, 'select'); addCustomFontsToDropdown(fonts, this.fontTypes, 'select');
} catch (err) { } catch (err) {
console.error('Failed to load custom fonts:', err); console.error('Failed to load custom fonts:', err);
} finally { } finally {
// Mark fonts as ready even if loading fails (allows UI to proceed)
this.customFontsReady = true; this.customFontsReady = true;
} }
@@ -191,8 +189,6 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
if (resolvedFlow != null) this.selectedFlow = resolvedFlow; if (resolvedFlow != null) this.selectedFlow = resolvedFlow;
if (resolvedSpread != null) this.selectedSpread = resolvedSpread; 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) { if (resolvedCustomFontId != null) {
this.selectedFontType = `custom:${resolvedCustomFontId}`; this.selectedFontType = `custom:${resolvedCustomFontId}`;
} }
@@ -299,23 +295,35 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
async changeFontType(): Promise<void> { async changeFontType(): Promise<void> {
const result = await this.applyEpubTheme(); const result = await this.applyEpubTheme();
// Update state based on result
if (!result.success) { if (!result.success) {
// Font loading failed, clear the selection
this.selectedFontType = null; this.selectedFontType = null;
this.selectedCustomFontId = null; this.selectedCustomFontId = null;
} else if (result.customFontId !== undefined) { } else if (result.customFontId !== undefined) {
// Custom font loaded successfully or cleared
this.selectedCustomFontId = result.customFontId; this.selectedCustomFontId = result.customFontId;
} }
this.updateViewerSetting(); this.updateViewerSetting();
} }
private async cacheCustomFontsAsBlobs(fonts: CustomFont[]): Promise<void> {
const promises = fonts.map(async (font) => {
try {
const fontUrl = this.customFontService.getFontUrl(font.id);
const fontUrlWithToken = this.customFontService.appendToken(fontUrl);
const response = await fetch(fontUrlWithToken);
const blob = await response.blob();
const blobUrl = URL.createObjectURL(blob);
this.customFontBlobUrls.set(font.id, blobUrl);
} catch (error) {
console.error(`Failed to cache font ${font.fontName}:`, error);
}
});
await Promise.all(promises);
}
private async applyEpubTheme(): Promise<{ success: boolean, customFontId?: number | null }> { private async applyEpubTheme(): Promise<{ success: boolean, customFontId?: number | null }> {
if (!this.rendition) return {success: false}; if (!this.rendition) return {success: false};
// Determine font family - handle custom fonts
let fontFamily = this.selectedFontType; let fontFamily = this.selectedFontType;
let customFontToInject: CustomFont | null = null; let customFontToInject: CustomFont | null = null;
let customFontId: number | null = null; let customFontId: number | null = null;
@@ -331,11 +339,9 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
customFontId = fontId; customFontId = fontId;
customFontToInject = customFont; customFontToInject = customFont;
} else { } else {
// Font didn't load properly
return {success: false}; return {success: false};
} }
} catch (error) { } catch (error) {
// Font loading failed
console.error('Failed to load custom font:', error); console.error('Failed to load custom font:', error);
this.messageService.add({ this.messageService.add({
severity: 'warn', severity: 'warn',
@@ -349,14 +355,16 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
customFontId = null; customFontId = null;
} }
// Inject or clear @font-face rules
if (customFontToInject) { if (customFontToInject) {
const fontUrl = this.customFontService.getFontUrl(customFontToInject.id); const blobUrl = this.customFontBlobUrls.get(customFontToInject.id);
const fontUrlWithToken = this.customFontService.appendToken(fontUrl); if (!blobUrl) {
console.error('Blob URL not found for custom font');
return {success: false};
}
this.rendition.themes.default({ this.rendition.themes.default({
'@font-face': [{ '@font-face': [{
'font-family': `"${customFontToInject.fontName}"`, 'font-family': `"${customFontToInject.fontName}"`,
'src': `url(${fontUrlWithToken})`, 'src': `url(${blobUrl})`,
'font-weight': 'normal', 'font-weight': 'normal',
'font-style': 'normal' 'font-style': 'normal'
}] }]
@@ -365,14 +373,12 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
this.rendition.themes.default({}); this.rendition.themes.default({});
} }
// Apply font using EPUB.js font() method
if (fontFamily) { if (fontFamily) {
this.rendition.themes.font(customFontToInject ? `"${fontFamily}"` : fontFamily); this.rendition.themes.font(customFontToInject ? `"${fontFamily}"` : fontFamily);
} else { } else {
this.rendition.themes.font(''); this.rendition.themes.font('');
} }
// Apply theme with other settings
const baseTheme = EpubThemeUtil.themesMap.get(this.selectedTheme ?? 'black') || {}; const baseTheme = EpubThemeUtil.themesMap.get(this.selectedTheme ?? 'black') || {};
const combinedTheme = { const combinedTheme = {
...baseTheme, ...baseTheme,
@@ -788,10 +794,8 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
: (this.epub?.epubProgress?.cfi ? this.rendition.display(this.epub.epubProgress.cfi) : this.rendition.display()); : (this.epub?.epubProgress?.cfi ? this.rendition.display(this.epub.epubProgress.cfi) : this.rendition.display());
displayPromise.then(async () => { displayPromise.then(async () => {
// Apply custom font after rendition is displayed
const result = await this.applyEpubTheme(); const result = await this.applyEpubTheme();
// If font loading failed during initialization, clear the selection
if (!result.success) { if (!result.success) {
this.selectedFontType = null; this.selectedFontType = null;
this.selectedCustomFontId = null; this.selectedCustomFontId = null;
@@ -816,6 +820,9 @@ export class EpubReaderComponent implements OnInit, OnDestroy {
); );
} }
this.customFontBlobUrls.forEach(url => URL.revokeObjectURL(url));
this.customFontBlobUrls.clear();
this.routeSubscription?.unsubscribe(); this.routeSubscription?.unsubscribe();
if (this.currentIframe && this.currentIframe.contentDocument) { if (this.currentIframe && this.currentIframe.contentDocument) {