feat(ui): sync profile locale and theme preferences (#1604)
This commit is contained in:
@@ -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 },
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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));
|
||||
};
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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<void> {
|
||||
return of(undefined);
|
||||
return defer(() => from(this.injector.get(StartupService).load()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
+4
@@ -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,
|
||||
|
||||
+4
@@ -38,6 +38,10 @@ function buildUser(overrides: Partial<User['permissions']> = {}): 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'],
|
||||
|
||||
@@ -17,6 +17,10 @@ function buildUser(overrides: Partial<User['permissions']> = {}): 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'],
|
||||
|
||||
+8
@@ -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();
|
||||
|
||||
@@ -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,
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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<User> {
|
||||
return this.http.put<User>(`${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<void> {
|
||||
return this.http.delete<void>(`${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,
|
||||
|
||||
+10
-1
@@ -48,7 +48,7 @@
|
||||
<p-toggleswitch
|
||||
inputId="oled-dark-mode"
|
||||
[ngModel]="oledDarkMode()"
|
||||
(ngModelChange)="configService.setOledDarkMode($event)">
|
||||
(ngModelChange)="updateOledDarkMode($event)">
|
||||
</p-toggleswitch>
|
||||
</div>
|
||||
}
|
||||
@@ -93,6 +93,15 @@
|
||||
</p-select>
|
||||
</div>
|
||||
|
||||
<div class="form-field">
|
||||
<label class="field-label" for="theme-sync">{{ 'layout.theme.syncAcrossDevices' | transloco }}</label>
|
||||
<p-toggleswitch
|
||||
inputId="theme-sync"
|
||||
[ngModel]="selectedThemeSyncEnabled()"
|
||||
(ngModelChange)="updateThemeSyncEnabled($event)">
|
||||
</p-toggleswitch>
|
||||
</div>
|
||||
|
||||
@if (selectedThemePreference() === 'custom') {
|
||||
<fieldset class="form-field">
|
||||
<legend class="field-label">{{ 'layout.theme.customPrimary' | transloco }}</legend>
|
||||
|
||||
+74
-21
@@ -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<CustomPrimary>(
|
||||
() => 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;
|
||||
|
||||
+4
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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<void> {
|
||||
const nextLocale = AVAILABLE_LANGS.includes(locale) ? locale : DEFAULT_LOCALE;
|
||||
await firstValueFrom(this.translocoService.load(nextLocale));
|
||||
this.translocoService.setActiveLang(nextLocale);
|
||||
localStorage.setItem(STORAGE_KEY, nextLocale);
|
||||
}
|
||||
}
|
||||
+49
-10
@@ -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<typeof createLocalStorageMock>;
|
||||
let faviconServiceMock: { updateFavicon: ReturnType<typeof vi.fn> };
|
||||
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,
|
||||
}));
|
||||
+36
-7
@@ -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<AppState>(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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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<void> {
|
||||
async load(): Promise<void> {
|
||||
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<void> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,6 +75,7 @@
|
||||
"dark": "Dark",
|
||||
"system": "System",
|
||||
"customPrimary": "Custom color",
|
||||
"syncAcrossDevices": "Sync my theme across devices",
|
||||
"options": {
|
||||
"grimmory": "Grimmory",
|
||||
"cobalt": "Cobalt",
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user