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