From d6d18aa90b3b873ffbeb2a71159b1bdf1c0d5f95 Mon Sep 17 00:00:00 2001 From: Zach Date: Tue, 2 Jun 2026 16:40:16 -0400 Subject: [PATCH] feat(ui): sync profile locale and theme preferences (#1604) --- frontend/src/app/app.component.spec.ts | 4 +- frontend/src/app/app.component.ts | 4 +- .../core/config/language-initializer.spec.ts | 90 ----------- .../app/core/config/language-initializer.ts | 38 ----- .../post-login-initializer.service.spec.ts | 13 +- .../post-login-initializer.service.ts | 8 +- .../book-browser.component.spec.ts | 4 + .../book-card/book-card.component.spec.ts | 4 + .../kobo-sync-settings-component.spec.ts | 4 + .../opds-settings/opds-settings.spec.ts | 4 + .../reader-preferences.service.spec.ts | 8 + .../user-management/user.service.spec.ts | 24 +++ .../settings/user-management/user.service.ts | 30 ++++ .../user-profile-dialog.component.html | 11 +- .../user-profile-dialog.component.ts | 95 +++++++++--- .../meta-center-view-mode-component.spec.ts | 4 + .../src/app/shared/model/app-state.model.ts | 7 +- .../shared/service/app-locale.service.spec.ts | 73 +++++++++ .../app/shared/service/app-locale.service.ts | 24 +++ ...vice.spec.ts => app-theme.service.spec.ts} | 59 ++++++-- ...config.service.ts => app-theme.service.ts} | 43 +++++- .../shared/service/startup.service.spec.ts | 140 +++++++++++++++++- .../src/app/shared/service/startup.service.ts | 35 ++++- frontend/src/i18n/en/layout.json | 1 + frontend/src/main.ts | 12 +- 25 files changed, 543 insertions(+), 196 deletions(-) delete mode 100644 frontend/src/app/core/config/language-initializer.spec.ts delete mode 100644 frontend/src/app/core/config/language-initializer.ts create mode 100644 frontend/src/app/shared/service/app-locale.service.spec.ts create mode 100644 frontend/src/app/shared/service/app-locale.service.ts rename frontend/src/app/shared/service/{app-config.service.spec.ts => app-theme.service.spec.ts} (77%) rename frontend/src/app/shared/service/{app-config.service.ts => app-theme.service.ts} (85%) diff --git a/frontend/src/app/app.component.spec.ts b/frontend/src/app/app.component.spec.ts index a4b73e870..d9b2593b2 100644 --- a/frontend/src/app/app.component.spec.ts +++ b/frontend/src/app/app.component.spec.ts @@ -9,7 +9,7 @@ import { AuthInitializationService } from "./core/security/auth-initialization-s import { RxStompService } from "./shared/websocket/rx-stomp.service"; import { BookService } from "./features/book/service/book.service"; import { NotificationEventService } from "./shared/websocket/notification-event.service"; -import { AppConfigService } from "./shared/service/app-config.service"; +import { AppThemeService } from "./shared/service/app-theme.service"; import { MetadataProgressService } from "./shared/service/metadata-progress.service"; import { BookdropFileService } from "./features/bookdrop/service/bookdrop-file.service"; import { TaskService } from "./features/settings/task-management/task.service"; @@ -117,7 +117,7 @@ describe("AppComponent", () => { provide: NotificationEventService, useValue: notificationEventService, }, - { provide: AppConfigService, useValue: {} }, + { provide: AppThemeService, useValue: {} }, { provide: MetadataProgressService, useValue: metadataProgressService }, { provide: BookdropFileService, useValue: bookdropFileService }, { provide: TaskService, useValue: taskService }, diff --git a/frontend/src/app/app.component.ts b/frontend/src/app/app.component.ts index e896f5288..34302848e 100644 --- a/frontend/src/app/app.component.ts +++ b/frontend/src/app/app.component.ts @@ -8,7 +8,7 @@ import {Toast} from 'primeng/toast'; import {RouterOutlet} from '@angular/router'; import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco'; import {AuthInitializationService} from './core/security/auth-initialization-service'; -import {AppConfigService} from './shared/service/app-config.service'; +import {AppThemeService} from './shared/service/app-theme.service'; import {MetadataBatchProgressNotification} from './shared/model/metadata-batch-progress.model'; import {MetadataProgressService} from './shared/service/metadata-progress.service'; import {BookdropFileNotification, BookdropFileService} from './features/bookdrop/service/bookdrop-file.service'; @@ -35,7 +35,7 @@ export class AppComponent implements OnInit, OnDestroy { private subscriptions: Subscription[] = []; private subscriptionsInitialized = false; - private appConfigService = inject(AppConfigService); // DO NOT REMOVE: Used to initialize app config on startup + private appThemeService = inject(AppThemeService); // DO NOT REMOVE: Used to initialize app theme on startup private authInit = inject(AuthInitializationService); private bookService = inject(BookService); private authorService = inject(AuthorService); diff --git a/frontend/src/app/core/config/language-initializer.spec.ts b/frontend/src/app/core/config/language-initializer.spec.ts deleted file mode 100644 index f32873f7a..000000000 --- a/frontend/src/app/core/config/language-initializer.spec.ts +++ /dev/null @@ -1,90 +0,0 @@ -import {TestBed} from '@angular/core/testing'; -import {of} from 'rxjs'; -import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; -import {TranslocoService} from '@jsverse/transloco'; - -import {initializeLanguage, LANG_STORAGE_KEY, LEGACY_LANG_STORAGE_KEY} from './language-initializer'; - -describe('initializeLanguage', () => { - const translocoService = { - setActiveLang: vi.fn(), - load: vi.fn(), - }; - - beforeEach(() => { - vi.restoreAllMocks(); - localStorage.clear(); - translocoService.setActiveLang.mockReset(); - translocoService.load.mockReset(); - translocoService.load.mockReturnValue(of({})); - - TestBed.configureTestingModule({ - providers: [ - {provide: TranslocoService, useValue: translocoService}, - ] - }); - }); - - afterEach(() => { - localStorage.clear(); - TestBed.resetTestingModule(); - }); - - it('uses the current persisted language when it is available', async () => { - localStorage.setItem(LANG_STORAGE_KEY, 'de'); - - const initializer = TestBed.runInInjectionContext(() => initializeLanguage()); - - await TestBed.runInInjectionContext(() => initializer()); - - expect(translocoService.setActiveLang).toHaveBeenCalledWith('de'); - expect(translocoService.load).toHaveBeenCalledWith('de'); - expect(localStorage.getItem(LANG_STORAGE_KEY)).toBe('de'); - }); - - it('migrates the legacy persisted language key', async () => { - localStorage.setItem(LEGACY_LANG_STORAGE_KEY, 'fr'); - - const initializer = TestBed.runInInjectionContext(() => initializeLanguage()); - - await TestBed.runInInjectionContext(() => initializer()); - - expect(translocoService.setActiveLang).toHaveBeenCalledWith('fr'); - expect(localStorage.getItem(LANG_STORAGE_KEY)).toBe('fr'); - }); - - it('prefers the exact browser locale when it is available', async () => { - vi.spyOn(window.navigator, 'language', 'get').mockReturnValue('pt'); - - const initializer = TestBed.runInInjectionContext(() => initializeLanguage()); - - await TestBed.runInInjectionContext(() => initializer()); - - expect(translocoService.setActiveLang).toHaveBeenCalledWith('pt'); - expect(localStorage.getItem(LANG_STORAGE_KEY)).toBe('pt'); - }); - - it('falls back to the browser base language when the full locale is unavailable', async () => { - vi.spyOn(window.navigator, 'language', 'get').mockReturnValue('pt-BR'); - - const initializer = TestBed.runInInjectionContext(() => initializeLanguage()); - - await TestBed.runInInjectionContext(() => initializer()); - - expect(translocoService.setActiveLang).toHaveBeenCalledWith('pt'); - expect(localStorage.getItem(LANG_STORAGE_KEY)).toBe('pt'); - }); - - it('falls back to english when there is no supported saved or browser language', async () => { - localStorage.setItem(LANG_STORAGE_KEY, 'zz'); - vi.spyOn(window.navigator, 'language', 'get').mockReturnValue('zz-ZZ'); - - const initializer = TestBed.runInInjectionContext(() => initializeLanguage()); - - await TestBed.runInInjectionContext(() => initializer()); - - expect(translocoService.setActiveLang).toHaveBeenCalledWith('en'); - expect(translocoService.load).toHaveBeenCalledWith('en'); - expect(localStorage.getItem(LANG_STORAGE_KEY)).toBe('en'); - }); -}); diff --git a/frontend/src/app/core/config/language-initializer.ts b/frontend/src/app/core/config/language-initializer.ts deleted file mode 100644 index b43ecd627..000000000 --- a/frontend/src/app/core/config/language-initializer.ts +++ /dev/null @@ -1,38 +0,0 @@ -import {inject} from '@angular/core'; -import {TranslocoService} from '@jsverse/transloco'; -import {firstValueFrom} from 'rxjs'; -import {AVAILABLE_LANGS} from './transloco-loader'; - -// TODO(grimmory-cleanup): Remove after the Booklore-to-Grimmory localStorage migration window closes. -export const LEGACY_LANG_STORAGE_KEY = 'booklore-lang'; -export const LANG_STORAGE_KEY = 'grimmory-lang'; - -function detectLanguage(available: string[]): string { - const saved = localStorage.getItem(LANG_STORAGE_KEY) ?? localStorage.getItem(LEGACY_LANG_STORAGE_KEY); - if (saved && available.includes(saved)) { - localStorage.setItem(LANG_STORAGE_KEY, saved); - return saved; - } - - const browserLocale = navigator.language; - if (browserLocale && available.includes(browserLocale)) { - return browserLocale; - } - - const baseLang = browserLocale?.split('-')[0]; - if (baseLang && available.includes(baseLang)) { - return baseLang; - } - - return 'en'; -} - -export function initializeLanguage() { - return () => { - const translocoService = inject(TranslocoService); - const lang = detectLanguage(AVAILABLE_LANGS); - translocoService.setActiveLang(lang); - localStorage.setItem(LANG_STORAGE_KEY, lang); - return firstValueFrom(translocoService.load(lang)); - }; -} diff --git a/frontend/src/app/core/services/post-login-initializer.service.spec.ts b/frontend/src/app/core/services/post-login-initializer.service.spec.ts index b5d88d510..53f7538af 100644 --- a/frontend/src/app/core/services/post-login-initializer.service.spec.ts +++ b/frontend/src/app/core/services/post-login-initializer.service.spec.ts @@ -1,17 +1,24 @@ import {TestBed} from '@angular/core/testing'; import {firstValueFrom} from 'rxjs'; -import {describe, expect, it} from 'vitest'; +import {describe, expect, it, vi} from 'vitest'; import {PostLoginInitializerService} from './post-login-initializer.service'; +import {StartupService} from '../../shared/service/startup.service'; describe('PostLoginInitializerService', () => { - it('completes successfully', async () => { + it('hydrates startup preferences after login', async () => { + const load = vi.fn().mockResolvedValue(undefined); + TestBed.configureTestingModule({ - providers: [PostLoginInitializerService], + providers: [ + PostLoginInitializerService, + {provide: StartupService, useValue: {load}}, + ], }); const service = TestBed.inject(PostLoginInitializerService); await expect(firstValueFrom(service.initialize())).resolves.toBeUndefined(); + expect(load).toHaveBeenCalledOnce(); }); }); diff --git a/frontend/src/app/core/services/post-login-initializer.service.ts b/frontend/src/app/core/services/post-login-initializer.service.ts index bfe4f93b4..4a58df5e9 100644 --- a/frontend/src/app/core/services/post-login-initializer.service.ts +++ b/frontend/src/app/core/services/post-login-initializer.service.ts @@ -1,12 +1,14 @@ -import {Injectable} from '@angular/core'; -import {Observable, of} from 'rxjs'; +import {Injectable, inject, Injector} from '@angular/core'; +import {defer, from, Observable} from 'rxjs'; +import {StartupService} from '../../shared/service/startup.service'; @Injectable({ providedIn: 'root' }) export class PostLoginInitializerService { + private readonly injector = inject(Injector); initialize(): Observable { - return of(undefined); + return defer(() => from(this.injector.get(StartupService).load())); } } diff --git a/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts b/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts index f5e9cd316..abe29f36e 100644 --- a/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts +++ b/frontend/src/app/features/book/components/book-browser/book-browser.component.spec.ts @@ -52,6 +52,10 @@ function makeCurrentUser() { username: 'tester', name: 'Tester', email: 'tester@example.com', + locale: 'en', + theme: 'grimmory', + themeAccent: null, + themeSyncEnabled: true, assignedLibraries: [], permissions: { admin: false, diff --git a/frontend/src/app/features/book/components/book-browser/book-card/book-card.component.spec.ts b/frontend/src/app/features/book/components/book-browser/book-card/book-card.component.spec.ts index a961536d1..51e003bb7 100644 --- a/frontend/src/app/features/book/components/book-browser/book-card/book-card.component.spec.ts +++ b/frontend/src/app/features/book/components/book-browser/book-card/book-card.component.spec.ts @@ -41,6 +41,10 @@ function makeUser(metadataCenterViewMode: 'route' | 'dialog'): User { username: 'tester', name: 'Tester', email: 'tester@example.com', + locale: 'en', + theme: 'grimmory', + themeAccent: null, + themeSyncEnabled: true, assignedLibraries: [], permissions: { admin: false, diff --git a/frontend/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo-sync-settings-component.spec.ts b/frontend/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo-sync-settings-component.spec.ts index 8fc7d0373..ad869df8d 100644 --- a/frontend/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo-sync-settings-component.spec.ts +++ b/frontend/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo-sync-settings-component.spec.ts @@ -38,6 +38,10 @@ function buildUser(overrides: Partial = {}): User { username: 'admin', name: 'Admin', email: 'admin@example.com', + locale: 'en', + theme: 'grimmory', + themeAccent: null, + themeSyncEnabled: true, assignedLibraries: [], permissions: {admin: false, ...overrides} as User['permissions'], userSettings: {} as User['userSettings'], diff --git a/frontend/src/app/features/settings/opds-settings/opds-settings.spec.ts b/frontend/src/app/features/settings/opds-settings/opds-settings.spec.ts index ebe2b7f1d..18101af4e 100644 --- a/frontend/src/app/features/settings/opds-settings/opds-settings.spec.ts +++ b/frontend/src/app/features/settings/opds-settings/opds-settings.spec.ts @@ -17,6 +17,10 @@ function buildUser(overrides: Partial = {}): User { username: 'reader', name: 'Reader', email: 'reader@example.com', + locale: 'en', + theme: 'grimmory', + themeAccent: null, + themeSyncEnabled: true, assignedLibraries: [], permissions: {admin: false, canAccessOpds: true, ...overrides} as User['permissions'], userSettings: {} as User['userSettings'], diff --git a/frontend/src/app/features/settings/reader-preferences/reader-preferences.service.spec.ts b/frontend/src/app/features/settings/reader-preferences/reader-preferences.service.spec.ts index 0e787932a..52a177ba9 100644 --- a/frontend/src/app/features/settings/reader-preferences/reader-preferences.service.spec.ts +++ b/frontend/src/app/features/settings/reader-preferences/reader-preferences.service.spec.ts @@ -64,6 +64,10 @@ describe('ReaderPreferencesService', () => { username: 'reader', name: 'Reader', email: 'reader@example.test', + locale: 'en', + theme: 'grimmory', + themeAccent: null, + themeSyncEnabled: true, assignedLibraries: [], } as unknown as User); const updateUserSetting = vi.fn(); @@ -148,6 +152,10 @@ describe('ReaderPreferencesService', () => { username: 'reader', name: 'Reader', email: 'reader@example.test', + locale: 'en', + theme: 'grimmory', + themeAccent: null, + themeSyncEnabled: true, assignedLibraries: [], } as unknown as User); const updateUserSetting = vi.fn(); diff --git a/frontend/src/app/features/settings/user-management/user.service.spec.ts b/frontend/src/app/features/settings/user-management/user.service.spec.ts index 7b776cdad..bad351ce5 100644 --- a/frontend/src/app/features/settings/user-management/user.service.spec.ts +++ b/frontend/src/app/features/settings/user-management/user.service.spec.ts @@ -109,6 +109,10 @@ function buildUser(overrides: BuildUserOverrides = {}): User { username: 'reader', name: 'Reader', email: 'reader@example.test', + locale: 'en', + theme: 'grimmory', + themeAccent: null, + themeSyncEnabled: true, assignedLibraries: [], permissions, userSettings: buildUserSettings(userSettings), @@ -233,4 +237,24 @@ describe('UserService', () => { }), ); }); + + it('updates the current-user profile through the profile endpoint', async () => { + httpTestingController.expectOne(req => req.url.endsWith('/api/v1/users/me')).flush(buildUser()); + await flushCurrentUserQuery(); + + service.updateUserProfile(7, {locale: 'de', theme: 'custom', themeAccent: 'teal', themeSyncEnabled: true}).subscribe(); + + const request = httpTestingController.expectOne(req => req.url.endsWith('/api/v1/users/7/profile')); + expect(request.request.method).toBe('PUT'); + expect(request.request.body).toEqual({locale: 'de', theme: 'custom', themeAccent: 'teal', themeSyncEnabled: true}); + request.flush(buildUser({locale: 'de', theme: 'custom', themeAccent: 'teal', themeSyncEnabled: true})); + await flushCurrentUserQuery(); + + expect(service.currentUser()).toEqual(expect.objectContaining({ + locale: 'de', + theme: 'custom', + themeAccent: 'teal', + themeSyncEnabled: true, + })); + }); }); diff --git a/frontend/src/app/features/settings/user-management/user.service.ts b/frontend/src/app/features/settings/user-management/user.service.ts index e67e51a0f..aa40f5980 100644 --- a/frontend/src/app/features/settings/user-management/user.service.ts +++ b/frontend/src/app/features/settings/user-management/user.service.ts @@ -8,6 +8,7 @@ import { AuthService } from '../../../shared/service/auth.service'; import { DashboardConfig } from '../../dashboard/models/dashboard-config.model'; import { injectQuery, queryOptions, QueryClient } from '@tanstack/angular-query-experimental'; import { CURRENT_USER_QUERY_KEY } from './user-query-keys'; +import { AppTheme, CustomPrimary } from '../../../shared/model/app-state.model'; export interface EntityViewPreferences { global: EntityViewPreference; @@ -319,6 +320,10 @@ export interface User { username: string; name: string; email: string; + locale: string; + theme: AppTheme; + themeAccent: CustomPrimary | null; + themeSyncEnabled: boolean; assignedLibraries: Library[]; permissions: { admin: boolean; @@ -370,6 +375,15 @@ export interface UserUpdateRequest { assignedLibraries?: number[]; } +export interface UserProfileUpdateRequest { + name?: string; + email?: string; + locale?: string; + theme?: AppTheme; + themeAccent?: CustomPrimary | null; + themeSyncEnabled?: boolean; +} + @Injectable({ providedIn: 'root' }) @@ -446,6 +460,17 @@ export class UserService { ); } + updateUserProfile(userId: number, updateData: UserProfileUpdateRequest): Observable { + return this.http.put(`${this.userUrl}/${userId}/profile`, updateData).pipe( + map(user => this.normalizeUser(user)), + tap(user => { + if (this.currentUser()?.id === user.id) { + this.queryClient.setQueryData(CURRENT_USER_QUERY_KEY, user); + } + }) + ); + } + deleteUser(userId: number): Observable { return this.http.delete(`${this.userUrl}/${userId}`); } @@ -496,8 +521,13 @@ export class UserService { private normalizeUser(user: User): User { const permissions = user.permissions; + const theme = user.theme ?? 'grimmory'; return { ...user, + locale: user.locale ?? 'en', + theme, + themeAccent: theme === 'custom' ? user.themeAccent ?? 'orange' : null, + themeSyncEnabled: user.themeSyncEnabled ?? true, permissions: { ...permissions, canBulkResetGrimmoryReadProgress: permissions.canBulkResetGrimmoryReadProgress ?? permissions.canBulkResetBookloreReadProgress, diff --git a/frontend/src/app/features/settings/user-profile-dialog/user-profile-dialog.component.html b/frontend/src/app/features/settings/user-profile-dialog/user-profile-dialog.component.html index 995ec61b9..d07ca084d 100644 --- a/frontend/src/app/features/settings/user-profile-dialog/user-profile-dialog.component.html +++ b/frontend/src/app/features/settings/user-profile-dialog/user-profile-dialog.component.html @@ -48,7 +48,7 @@ + (ngModelChange)="updateOledDarkMode($event)"> } @@ -93,6 +93,15 @@ +
+ + + +
+ @if (selectedThemePreference() === 'custom') {
{{ 'layout.theme.customPrimary' | transloco }} diff --git a/frontend/src/app/features/settings/user-profile-dialog/user-profile-dialog.component.ts b/frontend/src/app/features/settings/user-profile-dialog/user-profile-dialog.component.ts index 0c6f3307c..af7c600fd 100644 --- a/frontend/src/app/features/settings/user-profile-dialog/user-profile-dialog.component.ts +++ b/frontend/src/app/features/settings/user-profile-dialog/user-profile-dialog.component.ts @@ -3,21 +3,24 @@ import {Button} from 'primeng/button'; import {AbstractControl, FormBuilder, FormGroup, FormsModule, ReactiveFormsModule, ValidationErrors, ValidatorFn, Validators} from '@angular/forms'; import {InputText} from 'primeng/inputtext'; import {Password} from 'primeng/password'; +import {User, UserProfileUpdateRequest, UserService} from '../user-management/user.service'; import {ToggleSwitch} from 'primeng/toggleswitch'; -import {User, UserService, UserUpdateRequest} from '../user-management/user.service'; import {MessageService} from 'primeng/api'; import {DynamicDialogRef} from 'primeng/dynamicdialog'; import {TranslocoDirective, TranslocoPipe, TranslocoService} from '@jsverse/transloco'; import {Select} from 'primeng/select'; import {takeUntilDestroyed, toSignal} from '@angular/core/rxjs-interop'; +import {from, switchMap} from 'rxjs'; import {AVAILABLE_LANGS, LANG_LABELS} from '../../../core/config/transloco-loader'; -import {LANG_STORAGE_KEY} from '../../../core/config/language-initializer'; -import {AppConfigService} from '../../../shared/service/app-config.service'; +import {AppThemeService} from '../../../shared/service/app-theme.service'; +import {AppLocaleService} from '../../../shared/service/app-locale.service'; import { AppearancePreference, AppTheme, CUSTOM_PRIMARY_OPTIONS, CustomPrimary, + DEFAULT_APP_THEME, + DEFAULT_CUSTOM_PRIMARY, } from '../../../shared/model/app-state.model'; export const passwordMatchValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => { @@ -59,24 +62,26 @@ export class UserProfileDialogComponent { })); protected readonly userService = inject(UserService); - protected readonly configService = inject(AppConfigService); + protected readonly themeService = inject(AppThemeService); + protected readonly appLocaleService = inject(AppLocaleService); private readonly messageService = inject(MessageService); private readonly fb = inject(FormBuilder); private readonly dialogRef = inject(DynamicDialogRef); private readonly t = inject(TranslocoService); private readonly destroyRef = inject(DestroyRef); protected readonly activeLang = toSignal(this.t.langChanges$, {initialValue: this.t.getActiveLang()}); - protected readonly selectedThemePreference = computed(() => this.configService.appState().themePreference); - protected readonly selectedAppearancePreference = computed(() => this.configService.appState().appearancePreference); - protected readonly oledDarkMode = computed(() => this.configService.appState().oledDarkMode); - protected readonly showOledDarkModeToggle = computed(() => this.configService.effectiveAppearance() === 'dark'); + protected readonly selectedThemePreference = computed(() => this.themeService.appState().themePreference ?? DEFAULT_APP_THEME); + protected readonly selectedAppearancePreference = computed(() => this.themeService.appState().appearancePreference ?? 'system'); + protected readonly oledDarkMode = computed(() => this.themeService.appState().oledDarkMode); + protected readonly showOledDarkModeToggle = computed(() => this.themeService.effectiveAppearance() === 'dark'); protected readonly selectedCustomPrimary = computed( - () => this.configService.appState().customPrimary, + () => this.themeService.appState().customPrimary ?? DEFAULT_CUSTOM_PRIMARY, ); + protected readonly selectedThemeSyncEnabled = computed(() => this.themeService.appState().themeSyncEnabled !== false); protected readonly customPrimaryOptions = CUSTOM_PRIMARY_OPTIONS; protected readonly themeOptions = computed(() => { this.activeLang(); - return this.configService.themes.map((theme) => ({ + return this.themeService.themes.map((theme) => ({ value: theme.name, label: this.t.translate(theme.labelKey), })); @@ -128,24 +133,72 @@ export class UserProfileDialogComponent { onLanguageChange(lang: string): void { if (lang === this.activeLang()) return; - this.t.load(lang).pipe(takeUntilDestroyed(this.destroyRef)).subscribe({ - next: () => { - this.t.setActiveLang(lang); - localStorage.setItem(LANG_STORAGE_KEY, lang); - }, - }); + if (!this.currentUser) return; + + this.userService.updateUserProfile(this.currentUser.id, {locale: lang}).pipe( + switchMap(user => from(this.appLocaleService.applyLocale(user.locale))), + takeUntilDestroyed(this.destroyRef), + ).subscribe(); } updateThemePreference(themePreference: AppTheme): void { - this.configService.setThemePreference(themePreference); + if (!this.currentUser) return; + + if (!this.selectedThemeSyncEnabled()) { + this.themeService.applyDeviceTheme(themePreference, this.selectedCustomPrimary()); + return; + } + + const updateRequest: UserProfileUpdateRequest = { + theme: themePreference, + ...(themePreference === 'custom' ? {themeAccent: this.selectedCustomPrimary()} : {}), + }; + + this.userService.updateUserProfile(this.currentUser.id, updateRequest).pipe(takeUntilDestroyed(this.destroyRef)).subscribe({ + next: (user) => this.themeService.applySyncedTheme(user.theme, user.themeAccent ?? DEFAULT_CUSTOM_PRIMARY), + }); } updateCustomPrimary(customPrimary: CustomPrimary): void { - this.configService.setCustomPrimary(customPrimary); + if (!this.currentUser) return; + + if (!this.selectedThemeSyncEnabled()) { + this.themeService.applyDeviceTheme('custom', customPrimary); + return; + } + + this.userService.updateUserProfile(this.currentUser.id, {theme: 'custom', themeAccent: customPrimary}).pipe(takeUntilDestroyed(this.destroyRef)).subscribe({ + next: (user) => this.themeService.applySyncedTheme(user.theme, user.themeAccent ?? DEFAULT_CUSTOM_PRIMARY), + }); + } + + updateThemeSyncEnabled(themeSyncEnabled: boolean): void { + if (!this.currentUser) return; + + if (!themeSyncEnabled) { + this.userService.updateUserProfile(this.currentUser.id, {themeSyncEnabled: false}).pipe(takeUntilDestroyed(this.destroyRef)).subscribe({ + next: () => this.themeService.applyDeviceTheme(this.selectedThemePreference(), this.selectedCustomPrimary()), + }); + return; + } + + const theme = this.selectedThemePreference(); + const updateRequest: UserProfileUpdateRequest = { + themeSyncEnabled: true, + theme, + ...(theme === 'custom' ? {themeAccent: this.selectedCustomPrimary()} : {}), + }; + this.userService.updateUserProfile(this.currentUser.id, updateRequest).pipe(takeUntilDestroyed(this.destroyRef)).subscribe({ + next: (user) => this.themeService.applySyncedTheme(user.theme, user.themeAccent ?? DEFAULT_CUSTOM_PRIMARY), + }); } updateAppearancePreference(appearancePreference: AppearancePreference): void { - this.configService.setAppearancePreference(appearancePreference); + this.themeService.setAppearancePreference(appearancePreference); + } + + updateOledDarkMode(oledDarkMode: boolean): void { + this.themeService.setOledDarkMode(oledDarkMode); } updateProfile(): void { @@ -164,11 +217,11 @@ export class UserProfileDialogComponent { return; } - const updateRequest: UserUpdateRequest = { + const updateRequest: UserProfileUpdateRequest = { name: this.editUserData.name, email: this.editUserData.email, }; - this.userService.updateUser(this.currentUser.id, updateRequest).subscribe({ + this.userService.updateUserProfile(this.currentUser.id, updateRequest).subscribe({ next: () => { this.messageService.add({severity: 'success', summary: this.t.translate('common.success'), detail: this.t.translate('settingsProfile.toast.profileUpdated')}); this.isEditing = false; diff --git a/frontend/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.spec.ts b/frontend/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.spec.ts index 656bb7e85..62bc20f78 100644 --- a/frontend/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.spec.ts +++ b/frontend/src/app/features/settings/view-preferences-parent/meta-center-view-mode/meta-center-view-mode-component.spec.ts @@ -35,6 +35,10 @@ describe('MetaCenterViewModeComponent', () => { name: 'Reader', email: 'reader@example.test', assignedLibraries: [], + locale: 'en', + theme: 'grimmory', + themeAccent: null, + themeSyncEnabled: true, } as unknown as User; } diff --git a/frontend/src/app/shared/model/app-state.model.ts b/frontend/src/app/shared/model/app-state.model.ts index 21bdba424..898a3b290 100644 --- a/frontend/src/app/shared/model/app-state.model.ts +++ b/frontend/src/app/shared/model/app-state.model.ts @@ -12,8 +12,9 @@ export { export type {AppTheme, CustomPrimary} from './theme-registry'; export interface AppState { - themePreference: AppTheme; - appearancePreference: AppearancePreference; - customPrimary: CustomPrimary; + themePreference?: AppTheme; + appearancePreference?: AppearancePreference; + customPrimary?: CustomPrimary; + themeSyncEnabled?: boolean; oledDarkMode: boolean; } diff --git a/frontend/src/app/shared/service/app-locale.service.spec.ts b/frontend/src/app/shared/service/app-locale.service.spec.ts new file mode 100644 index 000000000..19b885d2c --- /dev/null +++ b/frontend/src/app/shared/service/app-locale.service.spec.ts @@ -0,0 +1,73 @@ +import {TestBed} from '@angular/core/testing'; +import {TranslocoService} from '@jsverse/transloco'; +import {of} from 'rxjs'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; + +import {AppLocaleService} from './app-locale.service'; + +describe('AppLocaleService', () => { + const translocoService = { + load: vi.fn(), + setActiveLang: vi.fn(), + }; + + beforeEach(() => { + vi.restoreAllMocks(); + localStorage.clear(); + translocoService.load.mockReset(); + translocoService.setActiveLang.mockReset(); + translocoService.load.mockReturnValue(of({})); + + TestBed.configureTestingModule({ + providers: [ + AppLocaleService, + {provide: TranslocoService, useValue: translocoService}, + ], + }); + }); + + afterEach(() => { + localStorage.clear(); + TestBed.resetTestingModule(); + }); + + it('defaults the display locale to english', () => { + const service = TestBed.inject(AppLocaleService); + + expect(service.getDisplayLocale()).toBe('en'); + }); + + it('uses a supported stored display locale', () => { + localStorage.setItem('appLocale', 'de'); + const service = TestBed.inject(AppLocaleService); + + expect(service.getDisplayLocale()).toBe('de'); + }); + + it('ignores an unsupported stored display locale', () => { + localStorage.setItem('appLocale', 'zz'); + const service = TestBed.inject(AppLocaleService); + + expect(service.getDisplayLocale()).toBe('en'); + }); + + it('loads, activates, and stores an applied locale', async () => { + const service = TestBed.inject(AppLocaleService); + + await service.applyLocale('de'); + + expect(translocoService.load).toHaveBeenCalledWith('de'); + expect(translocoService.setActiveLang).toHaveBeenCalledWith('de'); + expect(localStorage.getItem('appLocale')).toBe('de'); + }); + + it('falls back to english for unsupported applied locales', async () => { + const service = TestBed.inject(AppLocaleService); + + await service.applyLocale('zz'); + + expect(translocoService.load).toHaveBeenCalledWith('en'); + expect(translocoService.setActiveLang).toHaveBeenCalledWith('en'); + expect(localStorage.getItem('appLocale')).toBe('en'); + }); +}); diff --git a/frontend/src/app/shared/service/app-locale.service.ts b/frontend/src/app/shared/service/app-locale.service.ts new file mode 100644 index 000000000..734ea9d0d --- /dev/null +++ b/frontend/src/app/shared/service/app-locale.service.ts @@ -0,0 +1,24 @@ +import {Injectable, inject} from '@angular/core'; +import {TranslocoService} from '@jsverse/transloco'; +import {firstValueFrom} from 'rxjs'; +import {AVAILABLE_LANGS} from '../../core/config/transloco-loader'; + +const DEFAULT_LOCALE = 'en'; +const STORAGE_KEY = 'appLocale'; + +@Injectable({providedIn: 'root'}) +export class AppLocaleService { + private translocoService = inject(TranslocoService); + + getDisplayLocale(): string { + const locale = localStorage.getItem(STORAGE_KEY); + return locale && AVAILABLE_LANGS.includes(locale) ? locale : DEFAULT_LOCALE; + } + + async applyLocale(locale: string): Promise { + const nextLocale = AVAILABLE_LANGS.includes(locale) ? locale : DEFAULT_LOCALE; + await firstValueFrom(this.translocoService.load(nextLocale)); + this.translocoService.setActiveLang(nextLocale); + localStorage.setItem(STORAGE_KEY, nextLocale); + } +} diff --git a/frontend/src/app/shared/service/app-config.service.spec.ts b/frontend/src/app/shared/service/app-theme.service.spec.ts similarity index 77% rename from frontend/src/app/shared/service/app-config.service.spec.ts rename to frontend/src/app/shared/service/app-theme.service.spec.ts index 9f8972cac..56b103c0a 100644 --- a/frontend/src/app/shared/service/app-config.service.spec.ts +++ b/frontend/src/app/shared/service/app-theme.service.spec.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { TestBed } from '@angular/core/testing'; -import { AppConfigService } from './app-config.service'; +import { AppThemeService } from './app-theme.service'; import { FaviconService } from '../layout/theme/favicon-service'; function createLocalStorageMock() { @@ -44,8 +44,8 @@ function createMatchMediaMock(matches: boolean) { }) as unknown as MediaQueryList); } -describe('AppConfigService', () => { - let service: AppConfigService; +describe('AppThemeService', () => { + let service: AppThemeService; let localStorageMock: ReturnType; let faviconServiceMock: { updateFavicon: ReturnType }; const root = document.documentElement; @@ -72,12 +72,12 @@ describe('AppConfigService', () => { TestBed.resetTestingModule(); TestBed.configureTestingModule({ providers: [ - AppConfigService, + AppThemeService, { provide: FaviconService, useValue: faviconServiceMock }, ], }); - service = TestBed.inject(AppConfigService); + service = TestBed.inject(AppThemeService); }); afterEach(() => { @@ -95,6 +95,7 @@ describe('AppConfigService', () => { themePreference: 'grimmory', appearancePreference: 'system', customPrimary: 'orange', + themeSyncEnabled: true, oledDarkMode: false, }); expect(localStorageMock.getItem('appConfigState')).toBeNull(); @@ -111,10 +112,10 @@ describe('AppConfigService', () => { }); it('updates the root theme attributes without writing palette tokens inline', () => { - service.setThemePreference('grimmory'); + service.applySyncedTheme('cobalt'); service.setAppearancePreference('light'); - expect(root.dataset['appTheme']).toBe('grimmory'); + expect(root.dataset['appTheme']).toBe('cobalt'); expect(root.classList.contains('dark')).toBe(false); expect(rootStyle.getPropertyValue('color-scheme')).toBe('light'); expect(rootStyle.getPropertyValue('--color-primary')).toBe(''); @@ -137,24 +138,62 @@ describe('AppConfigService', () => { TestBed.resetTestingModule(); TestBed.configureTestingModule({ providers: [ - AppConfigService, + AppThemeService, { provide: FaviconService, useValue: faviconServiceMock }, ], }); - service = TestBed.inject(AppConfigService); + service = TestBed.inject(AppThemeService); expect(service.appState()).toEqual({ themePreference: 'grimmory', appearancePreference: 'system', customPrimary: 'orange', + themeSyncEnabled: true, oledDarkMode: false, }); expect(root.dataset['appTheme']).toBe('grimmory'); expect(root.classList.contains('dark')).toBe(false); expect(localStorageMock.getItem('appConfigState')).toBe(JSON.stringify({ - themePreference: 'grimmory', appearancePreference: 'system', + themePreference: 'grimmory', + customPrimary: 'orange', + oledDarkMode: false, + })); + }); + + it('persists device theme and disabled sync state when theme sync is disabled', () => { + service.applyDeviceTheme('custom', 'teal'); + + expect(service.appState()).toEqual({ + themePreference: 'custom', + appearancePreference: 'system', + customPrimary: 'teal', + themeSyncEnabled: false, + oledDarkMode: false, + }); + expect(localStorageMock.getItem('appConfigState')).toBe(JSON.stringify({ + appearancePreference: 'system', + themePreference: 'custom', + customPrimary: 'teal', + oledDarkMode: false, + themeSyncEnabled: false, + })); + }); + + it('persists the last synced theme as a local display fallback', () => { + service.applySyncedTheme('cobalt'); + + expect(service.appState()).toEqual({ + themePreference: 'cobalt', + appearancePreference: 'system', + customPrimary: 'orange', + themeSyncEnabled: true, + oledDarkMode: false, + }); + expect(localStorageMock.getItem('appConfigState')).toBe(JSON.stringify({ + appearancePreference: 'system', + themePreference: 'cobalt', customPrimary: 'orange', oledDarkMode: false, })); diff --git a/frontend/src/app/shared/service/app-config.service.ts b/frontend/src/app/shared/service/app-theme.service.ts similarity index 85% rename from frontend/src/app/shared/service/app-config.service.ts rename to frontend/src/app/shared/service/app-theme.service.ts index b6b2d20f5..9c65ed492 100644 --- a/frontend/src/app/shared/service/app-config.service.ts +++ b/frontend/src/app/shared/service/app-theme.service.ts @@ -32,7 +32,7 @@ interface LoadedAppState { @Injectable({ providedIn: 'root', }) -export class AppConfigService { +export class AppThemeService { private readonly STORAGE_KEY = 'appConfigState'; readonly themes = APP_THEME_OPTIONS; private readonly appStateSignal = signal(this.withDefaults({})); @@ -53,12 +53,24 @@ export class AppConfigService { this.applyAppState(initialState.state); } - setThemePreference(themePreference: AppTheme): void { - this.updateAppState({themePreference}); + applySyncedTheme(themePreference: AppTheme, customPrimary: CustomPrimary = DEFAULT_CUSTOM_PRIMARY): void { + this.updateAppState({ + themePreference, + customPrimary, + themeSyncEnabled: true, + }); } - setCustomPrimary(customPrimary: CustomPrimary): void { - this.updateAppState({customPrimary}); + applyDeviceTheme(themePreference: AppTheme, customPrimary: CustomPrimary = DEFAULT_CUSTOM_PRIMARY): void { + this.updateAppState({ + themePreference, + customPrimary, + themeSyncEnabled: false, + }); + } + + useStoredDeviceTheme(): void { + this.updateAppState({themeSyncEnabled: false}); } setAppearancePreference(appearancePreference: AppearancePreference): void { @@ -87,7 +99,7 @@ export class AppConfigService { const parsedState = JSON.parse(storedState) as StoredAppState; return { state: this.normalizeStoredState(parsedState), - shouldPersist: this.isLegacyPaletteState(parsedState), + shouldPersist: this.shouldRewriteStoredState(parsedState), }; } catch { return {state: this.withDefaults({}), shouldPersist: false}; @@ -107,10 +119,12 @@ export class AppConfigService { }); } + const themeSyncEnabled = state.themeSyncEnabled === false ? false : true; return this.withDefaults({ themePreference: state.themePreference, appearancePreference: state.appearancePreference, customPrimary: state.customPrimary, + themeSyncEnabled, oledDarkMode: state.oledDarkMode, }); } @@ -119,11 +133,16 @@ export class AppConfigService { return 'preset' in state || 'primary' in state || 'surface' in state; } + private shouldRewriteStoredState(state: StoredAppState): boolean { + return this.isLegacyPaletteState(state); + } + private withDefaults(state: AppStatePatch): AppState { return { themePreference: this.resolveThemePreference(state.themePreference), appearancePreference: this.resolveAppearancePreference(state.appearancePreference), customPrimary: this.resolveCustomPrimary(state.customPrimary), + themeSyncEnabled: state.themeSyncEnabled !== false, oledDarkMode: state.oledDarkMode === true, }; } @@ -162,7 +181,17 @@ export class AppConfigService { private saveAppState(state: AppState): void { if (isPlatformBrowser(this.platformId)) { - localStorage.setItem(this.STORAGE_KEY, JSON.stringify(state)); + const defaults = this.withDefaults(state); + const storedState: AppState = { + appearancePreference: defaults.appearancePreference, + themePreference: defaults.themePreference, + customPrimary: defaults.customPrimary, + oledDarkMode: defaults.oledDarkMode, + }; + if (!defaults.themeSyncEnabled) { + storedState.themeSyncEnabled = false; + } + localStorage.setItem(this.STORAGE_KEY, JSON.stringify(storedState)); } } diff --git a/frontend/src/app/shared/service/startup.service.spec.ts b/frontend/src/app/shared/service/startup.service.spec.ts index b5f64be55..d35560340 100644 --- a/frontend/src/app/shared/service/startup.service.spec.ts +++ b/frontend/src/app/shared/service/startup.service.spec.ts @@ -1,15 +1,33 @@ import {signal} from '@angular/core'; import {TestBed} from '@angular/core/testing'; -import {describe, expect, it, vi} from 'vitest'; +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {QueryClient, queryOptions} from '@tanstack/angular-query-experimental'; +import {of} from 'rxjs'; import {AuthService} from './auth.service'; import {StartupService} from './startup.service'; import {UserService} from '../../features/settings/user-management/user.service'; +import {AppThemeService} from './app-theme.service'; +import {AppLocaleService} from './app-locale.service'; describe('StartupService', () => { + beforeEach(() => { + vi.restoreAllMocks(); + localStorage.clear(); + }); + + afterEach(() => { + localStorage.clear(); + TestBed.resetTestingModule(); + }); + it('loads the current user when a token is present', async () => { - const fetchQuery = vi.fn().mockResolvedValue({username: 'admin'}); + const fetchQuery = vi.fn().mockResolvedValue({id: 1, username: 'admin', locale: 'en', theme: 'grimmory', themeAccent: null, themeSyncEnabled: true}); + const applySyncedTheme = vi.fn(); + const applyDeviceTheme = vi.fn(); + const useStoredDeviceTheme = vi.fn(); + const applyLocale = vi.fn().mockResolvedValue(undefined); + const getDisplayLocale = vi.fn().mockReturnValue('en'); TestBed.configureTestingModule({ providers: [ @@ -25,6 +43,8 @@ describe('StartupService', () => { }, }, {provide: QueryClient, useValue: {fetchQuery}}, + {provide: AppThemeService, useValue: {applySyncedTheme, applyDeviceTheme, useStoredDeviceTheme, appState: () => ({themeSyncEnabled: true})}}, + {provide: AppLocaleService, useValue: {applyLocale, getDisplayLocale}}, ] }); @@ -32,10 +52,16 @@ describe('StartupService', () => { await expect(service.load()).resolves.toBeUndefined(); expect(fetchQuery).toHaveBeenCalledOnce(); + expect(applySyncedTheme).toHaveBeenCalledWith('grimmory', 'orange'); + expect(applyDeviceTheme).not.toHaveBeenCalled(); + expect(applyLocale).toHaveBeenCalledWith('en'); }); - it('resolves immediately when there is no token', async () => { + it('loads the local display locale when there is no token', async () => { const fetchQuery = vi.fn(); + const applySyncedTheme = vi.fn(); + const applyLocale = vi.fn().mockResolvedValue(undefined); + const getDisplayLocale = vi.fn().mockReturnValue('de'); TestBed.configureTestingModule({ providers: [ @@ -51,6 +77,8 @@ describe('StartupService', () => { }, }, {provide: QueryClient, useValue: {fetchQuery}}, + {provide: AppThemeService, useValue: {applySyncedTheme, appState: () => ({themeSyncEnabled: true})}}, + {provide: AppLocaleService, useValue: {applyLocale, getDisplayLocale}}, ] }); @@ -58,5 +86,111 @@ describe('StartupService', () => { await expect(service.load()).resolves.toBeUndefined(); expect(fetchQuery).not.toHaveBeenCalled(); + expect(getDisplayLocale).toHaveBeenCalledOnce(); + expect(applyLocale).toHaveBeenCalledWith('de'); + }); + + it('uses the backend locale for authenticated users', async () => { + const fetchQuery = vi.fn().mockResolvedValue({id: 1, username: 'admin', locale: 'en', theme: 'custom', themeAccent: 'teal', themeSyncEnabled: true}); + const updateUserProfile = vi.fn().mockReturnValue(of({id: 1, username: 'admin', locale: 'de', theme: 'custom', themeAccent: 'teal', themeSyncEnabled: true})); + const applySyncedTheme = vi.fn(); + const applyLocale = vi.fn().mockResolvedValue(undefined); + const getDisplayLocale = vi.fn().mockReturnValue('de'); + + TestBed.configureTestingModule({ + providers: [ + StartupService, + {provide: AuthService, useValue: {token: signal('token')}}, + { + provide: UserService, + useValue: { + getUserQueryOptions: () => queryOptions({ + queryKey: ['user'], + queryFn: async () => ({id: 1, username: 'admin', locale: 'en', theme: 'custom', themeAccent: 'teal', themeSyncEnabled: true}), + }), + updateUserProfile, + }, + }, + {provide: QueryClient, useValue: {fetchQuery}}, + {provide: AppThemeService, useValue: {applySyncedTheme, appState: () => ({themeSyncEnabled: true})}}, + {provide: AppLocaleService, useValue: {applyLocale, getDisplayLocale}}, + ] + }); + + const service = TestBed.inject(StartupService); + + await service.load(); + + expect(updateUserProfile).not.toHaveBeenCalled(); + expect(applySyncedTheme).toHaveBeenCalledWith('custom', 'teal'); + expect(applyLocale).toHaveBeenCalledWith('en'); + }); + + it('uses a local device theme when theme sync is disabled', async () => { + const fetchQuery = vi.fn().mockResolvedValue({id: 1, username: 'admin', locale: 'en', theme: 'cobalt', themeAccent: null, themeSyncEnabled: false}); + const applySyncedTheme = vi.fn(); + const applyDeviceTheme = vi.fn(); + const useStoredDeviceTheme = vi.fn(); + const applyLocale = vi.fn().mockResolvedValue(undefined); + const getDisplayLocale = vi.fn().mockReturnValue('en'); + + TestBed.configureTestingModule({ + providers: [ + StartupService, + {provide: AuthService, useValue: {token: signal('token')}}, + { + provide: UserService, + useValue: { + getUserQueryOptions: () => queryOptions({ + queryKey: ['user'], + queryFn: async () => ({id: 1, username: 'admin', locale: 'en', theme: 'cobalt', themeAccent: null, themeSyncEnabled: false}), + }), + }, + }, + {provide: QueryClient, useValue: {fetchQuery}}, + {provide: AppThemeService, useValue: {applySyncedTheme, applyDeviceTheme, useStoredDeviceTheme, appState: () => ({themeSyncEnabled: false})}}, + {provide: AppLocaleService, useValue: {applyLocale, getDisplayLocale}}, + ] + }); + + const service = TestBed.inject(StartupService); + + await service.load(); + + expect(applySyncedTheme).not.toHaveBeenCalled(); + expect(applyDeviceTheme).not.toHaveBeenCalled(); + expect(useStoredDeviceTheme).toHaveBeenCalledOnce(); + }); + + it('seeds the local device theme from the backend when sync is disabled without a local override', async () => { + const fetchQuery = vi.fn().mockResolvedValue({id: 1, username: 'admin', locale: 'en', theme: 'cobalt', themeAccent: null, themeSyncEnabled: false}); + const applyDeviceTheme = vi.fn(); + const applyLocale = vi.fn().mockResolvedValue(undefined); + const getDisplayLocale = vi.fn().mockReturnValue('en'); + + TestBed.configureTestingModule({ + providers: [ + StartupService, + {provide: AuthService, useValue: {token: signal('token')}}, + { + provide: UserService, + useValue: { + getUserQueryOptions: () => queryOptions({ + queryKey: ['user'], + queryFn: async () => ({id: 1, username: 'admin', locale: 'en', theme: 'cobalt', themeAccent: null, themeSyncEnabled: false}), + }), + }, + }, + {provide: QueryClient, useValue: {fetchQuery}}, + {provide: AppThemeService, useValue: {applyDeviceTheme, appState: () => ({themeSyncEnabled: true})}}, + {provide: AppLocaleService, useValue: {applyLocale, getDisplayLocale}}, + ] + }); + + const service = TestBed.inject(StartupService); + + await service.load(); + + expect(applyDeviceTheme).toHaveBeenCalledWith('cobalt', 'orange'); }); }); diff --git a/frontend/src/app/shared/service/startup.service.ts b/frontend/src/app/shared/service/startup.service.ts index 7d49ab451..03dafb533 100644 --- a/frontend/src/app/shared/service/startup.service.ts +++ b/frontend/src/app/shared/service/startup.service.ts @@ -1,19 +1,46 @@ import {Injectable, inject} from '@angular/core'; import {AuthService} from './auth.service'; -import {UserService} from '../../features/settings/user-management/user.service'; +import {User, UserService} from '../../features/settings/user-management/user.service'; import {QueryClient} from '@tanstack/angular-query-experimental'; +import {AppThemeService} from './app-theme.service'; +import {DEFAULT_CUSTOM_PRIMARY} from '../model/app-state.model'; +import {AppLocaleService} from './app-locale.service'; @Injectable({providedIn: 'root'}) export class StartupService { private authService = inject(AuthService); private userService = inject(UserService); private queryClient = inject(QueryClient); + private appThemeService = inject(AppThemeService); + private appLocaleService = inject(AppLocaleService); - load(): Promise { + async load(): Promise { if (this.authService.token()) { - return this.queryClient.fetchQuery(this.userService.getUserQueryOptions()).then(() => undefined); + const user = await this.queryClient.fetchQuery(this.userService.getUserQueryOptions()); + await this.applyUserPreferences(user); + return undefined; } - return Promise.resolve(); + await this.appLocaleService.applyLocale(this.appLocaleService.getDisplayLocale()); + } + + private async applyUserPreferences(user: User): Promise { + this.applyTheme(user); + await this.appLocaleService.applyLocale(user.locale); + } + + private applyTheme(user: User): void { + const customPrimary = user.themeAccent ?? DEFAULT_CUSTOM_PRIMARY; + if (user.themeSyncEnabled) { + this.appThemeService.applySyncedTheme(user.theme, customPrimary); + return; + } + + if (this.appThemeService.appState().themeSyncEnabled === false) { + this.appThemeService.useStoredDeviceTheme(); + return; + } + + this.appThemeService.applyDeviceTheme(user.theme, customPrimary); } } diff --git a/frontend/src/i18n/en/layout.json b/frontend/src/i18n/en/layout.json index 0ac456335..d1c5c9bde 100644 --- a/frontend/src/i18n/en/layout.json +++ b/frontend/src/i18n/en/layout.json @@ -75,6 +75,7 @@ "dark": "Dark", "system": "System", "customPrimary": "Custom color", + "syncAcrossDevices": "Sync my theme across devices", "options": { "grimmory": "Grimmory", "cobalt": "Cobalt", diff --git a/frontend/src/main.ts b/frontend/src/main.ts index 090ea5ec4..9e8aa7795 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -12,7 +12,7 @@ import { AppComponent } from './app/app.component'; import Aura from './app/shared/layout/theme/theme-palette-extend'; import { routes } from './app/app.routes'; import { AuthInterceptorService } from './app/core/security/auth-interceptor.service'; -import { AuthService, websocketInitializer } from './app/shared/service/auth.service'; +import { AuthService } from './app/shared/service/auth.service'; import { GlobalErrorHandler } from './app/core/errors/global-error-handler'; import { PwaUpdateService } from './app/core/services/pwa-update.service'; import { initializeAuthFactory } from './app/core/security/auth-initializer'; @@ -20,7 +20,6 @@ import { StartupService } from './app/shared/service/startup.service'; import { provideServiceWorker } from '@angular/service-worker'; import { provideTransloco } from '@jsverse/transloco'; import { AVAILABLE_LANGS, TranslocoInlineLoader } from './app/core/config/transloco-loader'; -import { initializeLanguage } from './app/core/config/language-initializer'; import { provideTanStackQuery, QueryClient } from '@tanstack/angular-query-experimental'; bootstrapApplication(AppComponent, { @@ -36,15 +35,11 @@ bootstrapApplication(AppComponent, { }, })), provideAppInitializer(() => { - const authService = inject(AuthService); - return websocketInitializer(authService)(); - }), - provideAppInitializer(() => { + const initializeAuth = initializeAuthFactory(); const startup = inject(StartupService); - return startup.load(); + return Promise.resolve(initializeAuth()).then(() => startup.load()); }), provideHttpClient(withInterceptors([AuthInterceptorService])), - provideAppInitializer(initializeAuthFactory()), provideRouter(routes), DialogService, MessageService, @@ -68,7 +63,6 @@ bootstrapApplication(AppComponent, { }, loader: TranslocoInlineLoader, }), - provideAppInitializer(initializeLanguage()), providePrimeNG({ theme: { preset: Aura,