fix(user-settings): fix settings loading errors (#527)

* refactor(user): optimize detail fetching with custom repository implementation

* refactor(fonts): fix font loading and improve custom font handling

* refactor(user-data): update userSettings to use input() for better reactivity

* refactor(fonts): improve font loading logic and improve readi ness state management again

* refactor(user-data): simplify user fetching logic and improve batch loading

* refactor(custom-fonts): improve font loading logic with run ID for better state management
This commit is contained in:
brios
2026-04-22 17:27:35 -04:00
committed by Zach Yale
parent 5bd2e9ad3f
commit 902f5f5d67
7 changed files with 192 additions and 146 deletions
@@ -2,69 +2,18 @@ package org.booklore.repository;
import org.booklore.model.entity.BookLoreUserEntity; import org.booklore.model.entity.BookLoreUserEntity;
import org.booklore.model.enums.ProvisioningMethod; import org.booklore.model.enums.ProvisioningMethod;
import org.jspecify.annotations.NonNull;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional; import java.util.Optional;
@Repository @Repository
public interface UserRepository extends JpaRepository<BookLoreUserEntity, Long> { public interface UserRepository extends JpaRepository<BookLoreUserEntity, Long>, UserRepositoryCustom {
Optional<BookLoreUserEntity> findByUsername(String username); Optional<BookLoreUserEntity> findByUsername(String username);
Optional<BookLoreUserEntity> findByEmail(String email); Optional<BookLoreUserEntity> findByEmail(String email);
Optional<BookLoreUserEntity> findById(@NonNull Long id);
/**
* Fetch a user with all eagerly-needed associations (settings, libraries, permissions)
* in a single query to prevent N+1 problems after OSIV is disabled.
*/
@EntityGraph(attributePaths = {"settings", "libraries", "libraries.libraryPaths", "permissions"})
@Query("SELECT u FROM BookLoreUserEntity u WHERE u.id = :id")
Optional<BookLoreUserEntity> findByIdWithDetails(@Param("id") Long id);
/**
* Fetch a user with settings and permissions (without libraries) for settings-related operations.
*/
@EntityGraph(attributePaths = {"settings", "permissions"})
@Query("SELECT u FROM BookLoreUserEntity u WHERE u.id = :id")
Optional<BookLoreUserEntity> findByIdWithSettings(@Param("id") Long id);
/**
* Fetch a user with libraries and permissions for authorization/library-access operations.
*/
@EntityGraph(attributePaths = {"libraries", "libraries.libraryPaths", "permissions"})
@Query("SELECT u FROM BookLoreUserEntity u WHERE u.id = :id")
Optional<BookLoreUserEntity> findByIdWithLibraries(@Param("id") Long id);
/**
* Fetch a user with just permissions for security checks or simple profile updates.
*/
@EntityGraph(attributePaths = {"permissions"})
@Query("SELECT u FROM BookLoreUserEntity u WHERE u.id = :id")
Optional<BookLoreUserEntity> findByIdWithPermissions(@Param("id") Long id);
/**
* Fetch all users with their settings, libraries, and permissions in a single query.
* Prevents N+1 when listing all users (admin panel).
*/
@EntityGraph(attributePaths = {"settings", "libraries", "libraries.libraryPaths", "permissions"})
@Query("SELECT DISTINCT u FROM BookLoreUserEntity u")
List<BookLoreUserEntity> findAllWithDetails();
/**
* Fetch a user by username with all associations needed for authentication/DTO mapping.
*/
@EntityGraph(attributePaths = {"settings", "libraries", "libraries.libraryPaths", "permissions"})
@Query("SELECT u FROM BookLoreUserEntity u WHERE u.username = :username")
Optional<BookLoreUserEntity> findByUsernameWithDetails(@Param("username") String username);
long countByProvisioningMethod(ProvisioningMethod provisioningMethod); long countByProvisioningMethod(ProvisioningMethod provisioningMethod);
Optional<BookLoreUserEntity> findByOidcIssuerAndOidcSubject(String oidcIssuer, String oidcSubject); Optional<BookLoreUserEntity> findByOidcIssuerAndOidcSubject(String oidcIssuer, String oidcSubject);
@@ -0,0 +1,19 @@
package org.booklore.repository;
import org.booklore.model.entity.BookLoreUserEntity;
import java.util.List;
import java.util.Optional;
public interface UserRepositoryCustom {
Optional<BookLoreUserEntity> findByIdWithDetails(Long id);
List<BookLoreUserEntity> findAllWithDetails();
Optional<BookLoreUserEntity> findByIdWithSettings(Long id);
Optional<BookLoreUserEntity> findByIdWithLibraries(Long id);
Optional<BookLoreUserEntity> findByIdWithPermissions(Long id);
}
@@ -0,0 +1,85 @@
package org.booklore.repository;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.booklore.model.entity.BookLoreUserEntity;
import org.hibernate.Hibernate;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
public class UserRepositoryImpl implements UserRepositoryCustom {
@PersistenceContext
private EntityManager em;
@Override
@Transactional(readOnly = true)
public Optional<BookLoreUserEntity> findByIdWithDetails(Long id) {
List<BookLoreUserEntity> users = em.createQuery(
"SELECT DISTINCT u FROM BookLoreUserEntity u " +
"LEFT JOIN FETCH u.settings " +
"LEFT JOIN FETCH u.permissions " +
"WHERE u.id = :id",
BookLoreUserEntity.class)
.setParameter("id", id)
.getResultList();
if (users.isEmpty()) return Optional.empty();
BookLoreUserEntity user = users.getFirst();
Hibernate.initialize(user.getLibraries());
user.getLibraries().forEach(lib -> Hibernate.initialize(lib.getLibraryPaths()));
return Optional.of(user);
}
@Override
@Transactional(readOnly = true)
public List<BookLoreUserEntity> findAllWithDetails() {
List<BookLoreUserEntity> users = em.createQuery(
"SELECT DISTINCT u FROM BookLoreUserEntity u " +
"LEFT JOIN FETCH u.settings " +
"LEFT JOIN FETCH u.permissions",
BookLoreUserEntity.class)
.getResultList();
if (users.isEmpty()) return users;
users.forEach(user -> {
Hibernate.initialize(user.getLibraries());
user.getLibraries().forEach(lib -> Hibernate.initialize(lib.getLibraryPaths()));
});
return users;
}
@Override
@Transactional(readOnly = true)
public Optional<BookLoreUserEntity> findByIdWithSettings(Long id) {
BookLoreUserEntity user = em.find(BookLoreUserEntity.class, id);
if (user == null) return Optional.empty();
Hibernate.initialize(user.getSettings());
Hibernate.initialize(user.getPermissions());
return Optional.of(user);
}
@Override
@Transactional(readOnly = true)
public Optional<BookLoreUserEntity> findByIdWithLibraries(Long id) {
BookLoreUserEntity user = em.find(BookLoreUserEntity.class, id);
if (user == null) return Optional.empty();
Hibernate.initialize(user.getLibraries());
user.getLibraries().forEach(lib -> Hibernate.initialize(lib.getLibraryPaths()));
Hibernate.initialize(user.getPermissions());
return Optional.of(user);
}
@Override
@Transactional(readOnly = true)
public Optional<BookLoreUserEntity> findByIdWithPermissions(Long id) {
BookLoreUserEntity user = em.find(BookLoreUserEntity.class, id);
if (user == null) return Optional.empty();
Hibernate.initialize(user.getPermissions());
return Optional.of(user);
}
}
@@ -24,8 +24,6 @@ import {DatePipe} from '@angular/common';
providers: [ConfirmationService, DialogService] providers: [ConfirmationService, DialogService]
}) })
export class CustomFontsComponent implements OnInit { export class CustomFontsComponent implements OnInit {
customFonts: CustomFont[] = [];
isLoading = true;
fontsLoadedInBrowser = false; fontsLoadedInBrowser = false;
uploadDialogRef: DynamicDialogRef | null = null; uploadDialogRef: DynamicDialogRef | null = null;
@@ -38,6 +36,9 @@ export class CustomFontsComponent implements OnInit {
private t = inject(TranslocoService); private t = inject(TranslocoService);
private destroyRef = inject(DestroyRef); private destroyRef = inject(DestroyRef);
get customFonts(): CustomFont[] { return this.customFontService.fonts(); }
get isLoading(): boolean { return this.customFontService.isFontsLoading(); }
ngOnInit(): void { ngOnInit(): void {
this.loadFonts(); this.loadFonts();
} }
@@ -48,9 +49,6 @@ export class CustomFontsComponent implements OnInit {
try { try {
const fonts = await this.customFontService.ensureFonts(); const fonts = await this.customFontService.ensureFonts();
this.customFonts = fonts;
this.isLoading = false;
await this.customFontService.loadAllFonts(fonts); await this.customFontService.loadAllFonts(fonts);
this.fontsLoadedInBrowser = true; this.fontsLoadedInBrowser = true;
@@ -61,7 +59,6 @@ export class CustomFontsComponent implements OnInit {
summary: this.t.translate('common.error'), summary: this.t.translate('common.error'),
detail: this.t.translate('settingsReader.fonts.loadError') detail: this.t.translate('settingsReader.fonts.loadError')
}); });
this.isLoading = false;
this.fontsLoadedInBrowser = true; this.fontsLoadedInBrowser = true;
} }
} }
@@ -87,10 +84,7 @@ export class CustomFontsComponent implements OnInit {
if (this.uploadDialogRef) { if (this.uploadDialogRef) {
this.uploadDialogRef.onClose.pipe( this.uploadDialogRef.onClose.pipe(
takeUntilDestroyed(this.destroyRef) takeUntilDestroyed(this.destroyRef)
).subscribe((font: CustomFont | null) => { ).subscribe(() => {
if (font) {
this.customFonts.push(font);
}
this.uploadDialogRef = null; this.uploadDialogRef = null;
}); });
} }
@@ -106,7 +100,6 @@ export class CustomFontsComponent implements OnInit {
takeUntilDestroyed(this.destroyRef) takeUntilDestroyed(this.destroyRef)
).subscribe({ ).subscribe({
next: () => { next: () => {
this.customFonts = this.customFonts.filter(f => f.id !== font.id);
this.messageService.add({ this.messageService.add({
severity: 'success', severity: 'success',
summary: this.t.translate('common.success'), summary: this.t.translate('common.success'),
@@ -72,7 +72,7 @@
<div class="setting-label-row"> <div class="setting-label-row">
<span class="setting-label">{{ t('fontFamily') }}</span> <span class="setting-label">{{ t('fontFamily') }}</span>
<div class="button-group"> <div class="button-group">
@for (font of fonts; track font) { @for (font of fonts(); track font.key) {
<button <button
type="button" type="button"
class="option-button font-button" class="option-button font-button"
@@ -89,7 +89,7 @@
</button> </button>
} }
@if (!customFontsReady) { @if (!customFontsReady()) {
<p-skeleton width="3.5rem" height="2.5rem" borderRadius="6px"></p-skeleton> <p-skeleton width="3.5rem" height="2.5rem" borderRadius="6px"></p-skeleton>
} }
</div> </div>
@@ -1,5 +1,5 @@
import {DecimalPipe} from '@angular/common'; import {DecimalPipe} from '@angular/common';
import {Component, effect, inject, Input} from '@angular/core'; import {Component, computed, effect, untracked, inject, input} from '@angular/core';
import {Button} from 'primeng/button'; import {Button} from 'primeng/button';
import {FormsModule} from '@angular/forms'; import {FormsModule} from '@angular/forms';
import {TranslocoDirective} from '@jsverse/transloco'; import {TranslocoDirective} from '@jsverse/transloco';
@@ -7,8 +7,7 @@ import {ReaderPreferencesService} from '../reader-preferences.service';
import {UserSettings} from '../../user-management/user.service'; import {UserSettings} from '../../user-management/user.service';
import {Tooltip} from 'primeng/tooltip'; import {Tooltip} from 'primeng/tooltip';
import {CustomFontService} from '../../../../shared/service/custom-font.service'; import {CustomFontService} from '../../../../shared/service/custom-font.service';
import {CustomFont} from '../../../../shared/model/custom-font.model'; import {addCustomFontsToDropdown, FontPreferenceItem} from '../../../../shared/util/custom-font.util';
import {addCustomFontsToDropdown} from '../../../../shared/util/custom-font.util';
import {Skeleton} from 'primeng/skeleton'; import {Skeleton} from 'primeng/skeleton';
import {themes} from '../../../readers/ebook-reader/state/themes.constant'; import {themes} from '../../../readers/ebook-reader/state/themes.constant';
@@ -27,14 +26,12 @@ import {themes} from '../../../readers/ebook-reader/state/themes.constant';
}) })
export class EpubReaderPreferencesComponent { export class EpubReaderPreferencesComponent {
@Input() userSettings!: UserSettings; userSettings = input.required<UserSettings>();
private readonly readerPreferencesService = inject(ReaderPreferencesService); private readonly readerPreferencesService = inject(ReaderPreferencesService);
private readonly customFontService = inject(CustomFontService); private readonly customFontService = inject(CustomFontService);
customFonts: CustomFont[] = []; private static readonly baseFonts: FontPreferenceItem[] = [
fonts = [
{name: 'Book Default', displayName: 'Default', key: null}, {name: 'Book Default', displayName: 'Default', key: null},
{name: 'Serif', displayName: 'Serif', key: 'serif'}, {name: 'Serif', displayName: 'Serif', key: 'serif'},
{name: 'Sans Serif', displayName: 'Sans Serif', key: 'sans-serif'}, {name: 'Sans Serif', displayName: 'Sans Serif', key: 'sans-serif'},
@@ -45,58 +42,35 @@ export class EpubReaderPreferencesComponent {
readonly themes = themes; readonly themes = themes;
customFontsReady = false; readonly customFontsReady = computed(() => {
return this.customFontService.isFontsReady() || !this.customFontService.isFontsLoading();
private readonly syncFontsEffect = effect(() => {
const fonts = this.customFontService.fonts();
if (fonts.length > 0 || !this.customFontService.isFontsLoading()) {
this.customFontsReady = true;
}
if (this.hasCustomFontsChanged(fonts)) {
this.onFontsChanged(fonts);
}
}); });
private async onFontsChanged(fonts: CustomFont[]): Promise<void> { readonly fonts = computed<FontPreferenceItem[]>(() => {
try { const base: FontPreferenceItem[] = [...EpubReaderPreferencesComponent.baseFonts];
const selectedFontDeleted = this.isCurrentlySelectedFontDeleted(fonts); addCustomFontsToDropdown(this.customFontService.fonts(), base, 'preference');
return base;
});
this.customFonts = fonts; private readonly loadFontsEffect = effect(() => {
await this.customFontService.loadAllFonts(fonts); const fonts = this.customFontService.fonts();
this.updateFontsDropdown(fonts); if (fonts.length === 0 && this.customFontService.isFontsLoading()) return;
if (selectedFontDeleted) { untracked(() => {
this.resetToDefaultFont(); this.customFontService.loadAllFonts(fonts).catch(err => {
console.error('Failed to load custom fonts:', err);
});
});
const fontFamily = this.userSettings()?.ebookReaderSetting?.fontFamily;
if (fontFamily && fontFamily.startsWith('custom:')) {
const fontId = parseInt(fontFamily.split(':')[1], 10);
const fontStillExists = fonts.some(font => font.id === fontId);
if (!fontStillExists) {
queueMicrotask(() => 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 fontFamily = this.userSettings.ebookReaderSetting.fontFamily;
if (!fontFamily || !fontFamily.startsWith('custom:')) {
return false;
}
const fontId = fontFamily.split(':')[1];
const fontStillExists = newFonts.some(font => font.id === parseInt(fontId, 10));
return !fontStillExists;
}
private resetToDefaultFont(): void { private resetToDefaultFont(): void {
console.log('Selected custom font was deleted, resetting to default font'); console.log('Selected custom font was deleted, resetting to default font');
@@ -104,116 +78,116 @@ export class EpubReaderPreferencesComponent {
} }
get selectedTheme(): string | null { get selectedTheme(): string | null {
return this.userSettings.ebookReaderSetting.theme; return this.userSettings().ebookReaderSetting.theme;
} }
set selectedTheme(value: string | null) { set selectedTheme(value: string | null) {
if (typeof value === "string") { if (typeof value === "string") {
this.userSettings.ebookReaderSetting.theme = value; this.userSettings().ebookReaderSetting.theme = value;
} }
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'theme'], value); this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'theme'], value);
} }
get selectedFont(): string | null { get selectedFont(): string | null {
return this.userSettings.ebookReaderSetting.fontFamily || null; return this.userSettings().ebookReaderSetting.fontFamily || null;
} }
set selectedFont(value: string | null) { set selectedFont(value: string | null) {
if (typeof value === "string") { if (typeof value === "string") {
this.userSettings.ebookReaderSetting.fontFamily = value; this.userSettings().ebookReaderSetting.fontFamily = value;
} else { } else {
this.userSettings.ebookReaderSetting.fontFamily = ''; this.userSettings().ebookReaderSetting.fontFamily = '';
} }
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'fontFamily'], value); this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'fontFamily'], value);
} }
get fontSize(): number { get fontSize(): number {
return this.userSettings.ebookReaderSetting.fontSize; return this.userSettings().ebookReaderSetting.fontSize;
} }
set fontSize(value: number) { set fontSize(value: number) {
this.userSettings.ebookReaderSetting.fontSize = value; this.userSettings().ebookReaderSetting.fontSize = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'fontSize'], value); this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'fontSize'], value);
} }
get lineHeight(): number { get lineHeight(): number {
return this.userSettings.ebookReaderSetting.lineHeight; return this.userSettings().ebookReaderSetting.lineHeight;
} }
set lineHeight(value: number) { set lineHeight(value: number) {
this.userSettings.ebookReaderSetting.lineHeight = value; this.userSettings().ebookReaderSetting.lineHeight = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'lineHeight'], value); this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'lineHeight'], value);
} }
get justify(): boolean { get justify(): boolean {
return this.userSettings.ebookReaderSetting.justify; return this.userSettings().ebookReaderSetting.justify;
} }
set justify(value: boolean) { set justify(value: boolean) {
this.userSettings.ebookReaderSetting.justify = value; this.userSettings().ebookReaderSetting.justify = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'justify'], value); this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'justify'], value);
} }
get hyphenate(): boolean { get hyphenate(): boolean {
return this.userSettings.ebookReaderSetting.hyphenate; return this.userSettings().ebookReaderSetting.hyphenate;
} }
set hyphenate(value: boolean) { set hyphenate(value: boolean) {
this.userSettings.ebookReaderSetting.hyphenate = value; this.userSettings().ebookReaderSetting.hyphenate = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'hyphenate'], value); this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'hyphenate'], value);
} }
get maxColumnCount(): number { get maxColumnCount(): number {
return this.userSettings.ebookReaderSetting.maxColumnCount; return this.userSettings().ebookReaderSetting.maxColumnCount;
} }
set maxColumnCount(value: number) { set maxColumnCount(value: number) {
this.userSettings.ebookReaderSetting.maxColumnCount = value; this.userSettings().ebookReaderSetting.maxColumnCount = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'maxColumnCount'], value); this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'maxColumnCount'], value);
} }
get gap(): number { get gap(): number {
return this.userSettings.ebookReaderSetting.gap; return this.userSettings().ebookReaderSetting.gap;
} }
set gap(value: number) { set gap(value: number) {
this.userSettings.ebookReaderSetting.gap = value; this.userSettings().ebookReaderSetting.gap = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'gap'], value); this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'gap'], value);
} }
get maxInlineSize(): number { get maxInlineSize(): number {
return this.userSettings.ebookReaderSetting.maxInlineSize; return this.userSettings().ebookReaderSetting.maxInlineSize;
} }
set maxInlineSize(value: number) { set maxInlineSize(value: number) {
this.userSettings.ebookReaderSetting.maxInlineSize = value; this.userSettings().ebookReaderSetting.maxInlineSize = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'maxInlineSize'], value); this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'maxInlineSize'], value);
} }
get maxBlockSize(): number { get maxBlockSize(): number {
return this.userSettings.ebookReaderSetting.maxBlockSize; return this.userSettings().ebookReaderSetting.maxBlockSize;
} }
set maxBlockSize(value: number) { set maxBlockSize(value: number) {
this.userSettings.ebookReaderSetting.maxBlockSize = value; this.userSettings().ebookReaderSetting.maxBlockSize = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'maxBlockSize'], value); this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'maxBlockSize'], value);
} }
get isDark(): boolean { get isDark(): boolean {
return this.userSettings.ebookReaderSetting.isDark; return this.userSettings().ebookReaderSetting.isDark;
} }
set isDark(value: boolean) { set isDark(value: boolean) {
this.userSettings.ebookReaderSetting.isDark = value; this.userSettings().ebookReaderSetting.isDark = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'isDark'], value); this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'isDark'], value);
} }
get flow(): 'paginated' | 'scrolled' { get flow(): 'paginated' | 'scrolled' {
return this.userSettings.ebookReaderSetting.flow; return this.userSettings().ebookReaderSetting.flow;
} }
set flow(value: 'paginated' | 'scrolled') { set flow(value: 'paginated' | 'scrolled') {
this.userSettings.ebookReaderSetting.flow = value; this.userSettings().ebookReaderSetting.flow = value;
this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'flow'], value); this.readerPreferencesService.updatePreference(['ebookReaderSetting', 'flow'], value);
} }
@@ -283,7 +257,7 @@ export class EpubReaderPreferencesComponent {
return null; return null;
} }
const fontId = parseInt(fontKey.split(':')[1]); const fontId = parseInt(fontKey.split(':')[1]);
const customFont = this.customFonts.find(f => f.id === fontId); const customFont = this.customFontService.fonts().find(f => f.id === fontId);
return customFont ? customFont.fontName : null; return customFont ? customFont.fontName : null;
} }
} }
@@ -1,4 +1,4 @@
import {computed, effect, inject, Injectable} from '@angular/core'; import {computed, signal, effect, inject, Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http'; import {HttpClient} from '@angular/common/http';
import {lastValueFrom, Observable, tap} from 'rxjs'; import {lastValueFrom, Observable, tap} from 'rxjs';
import {CustomFont} from '../model/custom-font.model'; import {CustomFont} from '../model/custom-font.model';
@@ -13,6 +13,7 @@ const CUSTOM_FONTS_QUERY_KEY = ['customFonts'] as const;
}) })
export class CustomFontService { export class CustomFontService {
private apiUrl = `${API_CONFIG.BASE_URL}/api/v1/custom-fonts`; private apiUrl = `${API_CONFIG.BASE_URL}/api/v1/custom-fonts`;
private loadAllFontsRunId = 0;
private loadedFonts = new Set<string>(); private loadedFonts = new Set<string>();
private http = inject(HttpClient); private http = inject(HttpClient);
private authService = inject(AuthService); private authService = inject(AuthService);
@@ -27,11 +28,15 @@ export class CustomFontService {
fonts = computed(() => this.fontsQuery.data() ?? []); fonts = computed(() => this.fontsQuery.data() ?? []);
isFontsLoading = computed(() => !!this.token() && this.fontsQuery.isPending()); isFontsLoading = computed(() => !!this.token() && this.fontsQuery.isPending());
private readonly isFontsReadyInternal = signal(false);
isFontsReady = this.isFontsReadyInternal.asReadonly();
constructor() { constructor() {
effect(() => { effect(() => {
const token = this.token(); const token = this.token();
if (token === null) { if (token === null) {
this.queryClient.removeQueries({queryKey: CUSTOM_FONTS_QUERY_KEY}); this.queryClient.removeQueries({queryKey: CUSTOM_FONTS_QUERY_KEY});
this.isFontsReadyInternal.set(false);
} }
}); });
} }
@@ -125,8 +130,29 @@ export class CustomFontService {
} }
async loadAllFonts(fonts: CustomFont[]): Promise<void> { async loadAllFonts(fonts: CustomFont[]): Promise<void> {
const runId = ++this.loadAllFontsRunId;
this.isFontsReadyInternal.set(false);
if (fonts.length === 0) {
if (runId === this.loadAllFontsRunId) {
this.isFontsReadyInternal.set(true);
}
return;
}
const loadPromises = fonts.map(font => this.loadFontFace(font)); const loadPromises = fonts.map(font => this.loadFontFace(font));
await Promise.allSettled(loadPromises); const results = await Promise.allSettled(loadPromises);
if (runId !== this.loadAllFontsRunId) {
return;
}
const hasFailures = results.some(r => r.status === 'rejected');
if (hasFailures) {
const failures = results.filter(r => r.status === 'rejected');
console.error(`Failed to load ${failures.length} fonts out of ${fonts.length}`);
}
this.isFontsReadyInternal.set(true);
} }
isFontLoaded(fontName: string): boolean { isFontLoaded(fontName: string): boolean {