A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(app): store theme profiles per account and installation
Hampus099ec70700f9
diff --git a/fluxer_app/src/app/AppBootstrap.tsx b/fluxer_app/src/app/AppBootstrap.tsxindex a0c270c20..6cf0223ed 100644--- a/fluxer_app/src/app/AppBootstrap.tsx+++ b/fluxer_app/src/app/AppBootstrap.tsx@@ -3,7 +3,6 @@import 'urlpattern-polyfill';import {bootstrapSyntheticHistory} from '@app/app/HistoryBootstrap';import reactiveI18n, {initI18n} from '@app/app/I18n';-import {Routes} from '@app/app/Routes';import {AppErrorBoundary} from '@app/features/app/components/AppErrorBoundary';import {ErrorFallback} from '@app/features/app/components/ErrorFallback';import type {DomainMigrationSide} from '@app/features/app/domain_migration/DomainMigrationCore';@@ -104,25 +103,6 @@ function storageSessionAccount(account: Account | null): AppStorageSessionAccounreturn {accountKey: account.storageKey, userId: account.userId, token: account.token, instance: account.instance};}-async function bootstrapThemeStudio(storageBootstrap: AppStorageBootstrapHandle): Promise<void> {- const markdownParserReady = preloadMarkdownParser();- const [{ThemeStudioStandaloneApp}, {setupHttp}, {default: Accounts}] = await Promise.all([- loadLazyModule(() => import('@app/features/theme_studio/ThemeStudioStandaloneApp')),- loadLazyModule(() => import('@app/app/SetupHttp')),- loadLazyModule(() => import('@app/features/auth/state/Accounts')),- ]);- await Accounts.bootstrap();- await storageBootstrap.finalizeAfterSessionResolution(storageSessionAccount(Accounts.currentAccount));- setupHttp();- await markdownParserReady;- mountRoot(- <AppI18nProvider i18n={i18n}>- <ThemeStudioStandaloneApp data-flx="index.render-theme-studio.theme-studio-standalone-app" />- </AppI18nProvider>,- 'index.render-theme-studio',- );-}-export async function runPasskeyBridge(side: DomainMigrationSide): Promise<void> {const hash = window.location.hash;const opensInOwnTab = window.history.length === 1;@@ -206,6 +186,7 @@ async function bootstrapApp(storageBootstrap: AppStorageBootstrapHandle): Promis_runtimeConfig,{default: StatusPage},{installMigratedDeviceRemap},+ {migrateThemeProfiles},] = await Promise.all([loadLazyModule(() => import(/* webpackChunkName: "boot-app" */ '@app/app/App')),loadLazyModule(() => import('@app/app/SetupHttp')),@@ -223,6 +204,7 @@ async function bootstrapApp(storageBootstrap: AppStorageBootstrapHandle): PromisloadLazyModule(() => import('@app/features/app/state/RuntimeConfig')),loadLazyModule(() => import('@app/features/user/state/StatusPage')),loadLazyModule(() => import('@app/features/app/domain_migration/DomainMigrationDeviceRemap')),+ loadLazyModule(() => import('@app/features/theme/state/ThemeProfileMigration')),]);void preloadClientInfo();QuickSwitcher.setI18n(reactiveI18n);@@ -235,6 +217,7 @@ async function bootstrapApp(storageBootstrap: AppStorageBootstrapHandle): PromisStatusPage.startPolling();await Promise.all([Accounts.bootstrap(), installMigratedDeviceRemap()]);await storageBootstrap.finalizeAfterSessionResolution(storageSessionAccount(Accounts.currentAccount));+ await migrateThemeProfiles(Accounts.orderedAccounts.map((account) => account.storageKey));if (Accounts.currentUserId === null) {void probeSignedOutDomainMigration();}@@ -255,9 +238,5 @@ export async function runApp(storageBootstrap: AppStorageBootstrapHandle): PromiinstallLocaleSwitchWatchdog();installSelfXssNotice();void logClientInfo();- if (window.location.pathname === Routes.THEME_STUDIO) {- await bootstrapThemeStudio(storageBootstrap);- } else {- await bootstrapApp(storageBootstrap);- }+ await bootstrapApp(storageBootstrap);}diff --git a/fluxer_app/src/features/theme/commands/ThemePreferenceCommands.ts b/fluxer_app/src/features/theme/commands/ThemePreferenceCommands.tsdeleted file mode 100644index 2caacf0d1..000000000--- a/fluxer_app/src/features/theme/commands/ThemePreferenceCommands.ts+++ /dev/null@@ -1,34 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import Theme from '@app/features/theme/state/Theme';-import {broadcastThemeStudioMessage} from '@app/features/theme_studio/state/ThemeStudioBroadcast';-import * as UserSettingsCommands from '@app/features/user/commands/UserSettingsCommands';-import type {ThemeType} from '@fluxer/constants/src/UserConstants';--function applyLocalThemePreference(theme: ThemeType): void {- Theme.setTheme(theme);-}--function persistThemePreference(theme: ThemeType): void {- void UserSettingsCommands.update({theme});-}--function broadcastThemePreference(): void {- broadcastThemeStudioMessage({type: 'themePreference', snapshot: Theme.getPreferenceSnapshot()});-}--export function updateThemePreference(theme: ThemeType): boolean {- if (Theme.syncAcrossDevices) {- persistThemePreference(theme);- } else {- applyLocalThemePreference(theme);- }- broadcastThemePreference();- return true;-}--export function setSyncAcrossDevices(sync: boolean): boolean {- Theme.setSyncAcrossDevices(sync);- broadcastThemePreference();- return true;-}diff --git a/fluxer_app/src/features/theme/commands/ThemeProfileCommands.ts b/fluxer_app/src/features/theme/commands/ThemeProfileCommands.tsnew file mode 100644index 000000000..de376a63b--- /dev/null+++ b/fluxer_app/src/features/theme/commands/ThemeProfileCommands.ts@@ -0,0 +1,62 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import * as AccessibilityCommands from '@app/features/accessibility/commands/AccessibilityCommands';+import AccountTheme from '@app/features/theme/state/AccountTheme';+import AccountThemeMode from '@app/features/theme/state/AccountThemeMode';+import InstallationTheme from '@app/features/theme/state/InstallationTheme';+import ThemeEditTarget, {type ThemeTarget} from '@app/features/theme/state/ThemeEditTarget';+import ThemeLibrary from '@app/features/theme/state/ThemeLibrary';+import * as UserSettingsCommands from '@app/features/user/commands/UserSettingsCommands';+import type {ThemeType} from '@fluxer/constants/src/UserConstants';+import {runInAction} from 'mobx';++export function setThemePreference(theme: ThemeType, target: ThemeTarget): void {+ if (target === 'desktop') {+ InstallationTheme.setBaseTheme(theme);+ return;+ }+ if (AccountTheme.syncAcrossDevices) {+ void UserSettingsCommands.update({theme});+ return;+ }+ AccountTheme.setTheme(theme);+}++export function setSignedOutThemePreference(theme: ThemeType): void {+ if (AccountThemeMode.canUseDesktopTheme) {+ InstallationTheme.setBaseTheme(theme);+ return;+ }+ AccountTheme.setTheme(theme);+}++export function setSyncAcrossDevices(sync: boolean): void {+ AccountTheme.setSyncAcrossDevices(sync);+}++export function setCustomThemeCss(css: string | null, target: ThemeTarget): void {+ if (target === 'desktop') {+ InstallationTheme.setCustomThemeCss(css);+ return;+ }+ AccessibilityCommands.update({customThemeCss: css});+}++export async function setThemeEnabled(id: string, enabled: boolean, target: ThemeTarget): Promise<void> {+ await ThemeLibrary.setThemeEnabled(id, enabled, target);+}++export async function moveEnabledTheme(id: string, offset: -1 | 1, target: ThemeTarget): Promise<void> {+ await ThemeLibrary.moveEnabledTheme(id, offset, target);+}++export function setFollowDesktopTheme(value: boolean): void {+ runInAction(() => {+ AccountThemeMode.setFollowDesktopTheme(value);+ ThemeEditTarget.reset();+ });+}++export function pickEditTarget(target: ThemeTarget | null): void {+ ThemeEditTarget.pick(target);+}diff --git a/fluxer_app/src/features/theme/state/AccountTheme.ts b/fluxer_app/src/features/theme/state/AccountTheme.tsnew file mode 100644index 000000000..ba965ff7b--- /dev/null+++ b/fluxer_app/src/features/theme/state/AccountTheme.ts@@ -0,0 +1,139 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {AppStorageKey} from '@app/features/platform/state/AppStorageKeys';+import AppStorage from '@app/features/platform/state/PersistentStorage';+import {Logger} from '@app/features/platform/utils/AppLogger';+import type {ThemeType} from '@fluxer/constants/src/UserConstants';+import {ThemeTypes} from '@fluxer/constants/src/UserConstants';+import {isRecord} from '@fluxer/record_utils/src/RecordGuards';+import {makeAutoObservable} from 'mobx';++const logger = new Logger('AccountTheme');++interface AccountThemeSnapshot {+ readonly syncAcrossDevices: boolean;+ readonly localTheme: ThemeType;+ readonly serverTheme: ThemeType;+}++const VALID_THEMES = new Set<string>(Object.values(ThemeTypes));++const DEFAULT_ACCOUNT_THEME: AccountThemeSnapshot = Object.freeze({+ syncAcrossDevices: true,+ localTheme: ThemeTypes.DARK,+ serverTheme: ThemeTypes.DARK,+});++export function isThemeType(theme: unknown): theme is ThemeType {+ return typeof theme === 'string' && VALID_THEMES.has(theme);+}++export function parseAccountThemeSnapshot(raw: string | null | undefined): AccountThemeSnapshot | null {+ if (raw == null) {+ return null;+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch (error) {+ if (!(error instanceof SyntaxError)) {+ logger.warn('Failed to decode a stored account theme', error);+ }+ return null;+ }+ if (!isRecord(parsed)) {+ return null;+ }+ return {+ syncAcrossDevices:+ typeof parsed.syncAcrossDevices === 'boolean'+ ? parsed.syncAcrossDevices+ : DEFAULT_ACCOUNT_THEME.syncAcrossDevices,+ localTheme: isThemeType(parsed.localTheme) ? parsed.localTheme : DEFAULT_ACCOUNT_THEME.localTheme,+ serverTheme: isThemeType(parsed.serverTheme) ? parsed.serverTheme : DEFAULT_ACCOUNT_THEME.serverTheme,+ };+}++export function serializeAccountThemeSnapshot(snapshot: AccountThemeSnapshot): string {+ return JSON.stringify({+ syncAcrossDevices: snapshot.syncAcrossDevices,+ localTheme: snapshot.localTheme,+ serverTheme: snapshot.serverTheme,+ });+}++function readStoredSnapshot(): AccountThemeSnapshot {+ try {+ return parseAccountThemeSnapshot(AppStorage.getItem(AppStorageKey.ACCOUNT_THEME)) ?? DEFAULT_ACCOUNT_THEME;+ } catch (error) {+ logger.warn('Failed to read the account theme', error);+ return DEFAULT_ACCOUNT_THEME;+ }+}++class AccountTheme {+ syncAcrossDevices = DEFAULT_ACCOUNT_THEME.syncAcrossDevices;+ localTheme: ThemeType = DEFAULT_ACCOUNT_THEME.localTheme;+ serverTheme: ThemeType = DEFAULT_ACCOUNT_THEME.serverTheme;++ constructor() {+ makeAutoObservable(this, {}, {autoBind: true});+ this.load();+ }++ get themePreference(): ThemeType {+ return this.syncAcrossDevices ? this.serverTheme : this.localTheme;+ }++ load(): void {+ const snapshot = readStoredSnapshot();+ this.syncAcrossDevices = snapshot.syncAcrossDevices;+ this.localTheme = snapshot.localTheme;+ this.serverTheme = snapshot.serverTheme;+ }++ setTheme(theme: ThemeType): void {+ if (!isThemeType(theme)) {+ return;+ }+ if (this.syncAcrossDevices) {+ this.serverTheme = theme;+ } else {+ this.localTheme = theme;+ }+ this.persist();+ }++ setSyncAcrossDevices(sync: boolean): void {+ if (sync === this.syncAcrossDevices) {+ return;+ }+ if (!sync) {+ this.localTheme = this.themePreference;+ }+ this.syncAcrossDevices = sync;+ this.persist();+ }++ updateServerTheme(theme: string | null | undefined): void {+ this.serverTheme = isThemeType(theme) ? theme : ThemeTypes.DARK;+ this.persist();+ }++ private persist(): void {+ try {+ AppStorage.setItem(+ AppStorageKey.ACCOUNT_THEME,+ serializeAccountThemeSnapshot({+ syncAcrossDevices: this.syncAcrossDevices,+ localTheme: this.localTheme,+ serverTheme: this.serverTheme,+ }),+ );+ } catch (error) {+ logger.warn('Failed to save the account theme', error);+ }+ }+}++export default new AccountTheme();diff --git a/fluxer_app/src/features/theme/state/AccountThemeMode.ts b/fluxer_app/src/features/theme/state/AccountThemeMode.tsnew file mode 100644index 000000000..be383a2b2--- /dev/null+++ b/fluxer_app/src/features/theme/state/AccountThemeMode.ts@@ -0,0 +1,63 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {AppStorageKey} from '@app/features/platform/state/AppStorageKeys';+import AppStorage from '@app/features/platform/state/PersistentStorage';+import {Logger} from '@app/features/platform/utils/AppLogger';+import type {ThemeTarget} from '@app/features/theme/state/ThemeEditTarget';+import {isDesktop} from '@app/features/ui/utils/NativeUtils';+import {isRecord} from '@fluxer/record_utils/src/RecordGuards';+import {makeAutoObservable} from 'mobx';++const logger = new Logger('AccountThemeMode');++function readStoredFollowDesktopTheme(): boolean {+ try {+ const raw = AppStorage.getItem(AppStorageKey.ACCOUNT_THEME_MODE);+ if (raw === null) {+ return true;+ }+ const parsed: unknown = JSON.parse(raw);+ return !(isRecord(parsed) && parsed.followDesktopTheme === false);+ } catch (error) {+ if (!(error instanceof SyntaxError)) {+ logger.warn('Failed to read the desktop theme preference', error);+ }+ return true;+ }+}++class AccountThemeMode {+ followDesktopTheme = true;++ constructor() {+ makeAutoObservable(this, {}, {autoBind: true});+ this.load();+ }++ get canUseDesktopTheme(): boolean {+ return isDesktop();+ }++ get usesDesktopTheme(): boolean {+ return this.canUseDesktopTheme && this.followDesktopTheme;+ }++ get activeTarget(): ThemeTarget {+ return this.usesDesktopTheme ? 'desktop' : 'account';+ }++ load(): void {+ this.followDesktopTheme = readStoredFollowDesktopTheme();+ }++ setFollowDesktopTheme(value: boolean): void {+ this.followDesktopTheme = value;+ try {+ AppStorage.setItem(AppStorageKey.ACCOUNT_THEME_MODE, JSON.stringify({followDesktopTheme: value}));+ } catch (error) {+ logger.warn('Failed to save the desktop theme preference', error);+ }+ }+}++export default new AccountThemeMode();diff --git a/fluxer_app/src/features/theme/state/InstallationTheme.ts b/fluxer_app/src/features/theme/state/InstallationTheme.tsnew file mode 100644index 000000000..4c45ed048--- /dev/null+++ b/fluxer_app/src/features/theme/state/InstallationTheme.ts@@ -0,0 +1,100 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {normalizeCustomThemeCss} from '@app/features/accessibility/state/Accessibility';+import {AppStorageKey} from '@app/features/platform/state/AppStorageKeys';+import AppStorage from '@app/features/platform/state/PersistentStorage';+import {Logger} from '@app/features/platform/utils/AppLogger';+import {isThemeType} from '@app/features/theme/state/AccountTheme';+import type {ThemeType} from '@fluxer/constants/src/UserConstants';+import {ThemeTypes} from '@fluxer/constants/src/UserConstants';+import {isRecord} from '@fluxer/record_utils/src/RecordGuards';+import {makeAutoObservable} from 'mobx';++const logger = new Logger('InstallationTheme');++interface InstallationThemeSnapshot {+ readonly baseTheme: ThemeType;+ readonly customThemeCss: string | null;+}++export const DEFAULT_INSTALLATION_THEME: InstallationThemeSnapshot = Object.freeze({+ baseTheme: ThemeTypes.DARK,+ customThemeCss: null,+});++export function serializeInstallationThemeSnapshot(snapshot: InstallationThemeSnapshot): string {+ return JSON.stringify({baseTheme: snapshot.baseTheme, customThemeCss: snapshot.customThemeCss});+}++function parseInstallationThemeSnapshot(raw: string | null): InstallationThemeSnapshot | null {+ if (raw === null) {+ return null;+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch (error) {+ if (!(error instanceof SyntaxError)) {+ logger.warn('Failed to decode a stored installation theme', error);+ }+ return null;+ }+ if (!isRecord(parsed)) {+ return null;+ }+ return {+ baseTheme: isThemeType(parsed.baseTheme) ? parsed.baseTheme : DEFAULT_INSTALLATION_THEME.baseTheme,+ customThemeCss: normalizeCustomThemeCss(typeof parsed.customThemeCss === 'string' ? parsed.customThemeCss : null),+ };+}++function readStoredSnapshot(): InstallationThemeSnapshot | null {+ try {+ return parseInstallationThemeSnapshot(AppStorage.getItem(AppStorageKey.INSTALLATION_THEME));+ } catch (error) {+ logger.warn('Failed to read the installation theme', error);+ return null;+ }+}++class InstallationTheme {+ baseTheme: ThemeType = DEFAULT_INSTALLATION_THEME.baseTheme;+ customThemeCss: string | null = DEFAULT_INSTALLATION_THEME.customThemeCss;++ constructor() {+ makeAutoObservable(this, {}, {autoBind: true});+ this.load();+ }++ load(): void {+ const snapshot = readStoredSnapshot();+ this.baseTheme = snapshot?.baseTheme ?? DEFAULT_INSTALLATION_THEME.baseTheme;+ this.customThemeCss = snapshot?.customThemeCss ?? DEFAULT_INSTALLATION_THEME.customThemeCss;+ }++ setBaseTheme(theme: ThemeType): void {+ if (!isThemeType(theme)) {+ return;+ }+ this.baseTheme = theme;+ this.persist();+ }++ setCustomThemeCss(css: string | null): void {+ this.customThemeCss = normalizeCustomThemeCss(css);+ this.persist();+ }++ private persist(): void {+ try {+ AppStorage.setItem(+ AppStorageKey.INSTALLATION_THEME,+ serializeInstallationThemeSnapshot({baseTheme: this.baseTheme, customThemeCss: this.customThemeCss}),+ );+ } catch (error) {+ logger.warn('Failed to save the installation theme', error);+ }+ }+}++export default new InstallationTheme();diff --git a/fluxer_app/src/features/theme/state/ThemeEditTarget.ts b/fluxer_app/src/features/theme/state/ThemeEditTarget.tsnew file mode 100644index 000000000..d30526265--- /dev/null+++ b/fluxer_app/src/features/theme/state/ThemeEditTarget.ts@@ -0,0 +1,31 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import AccountThemeMode from '@app/features/theme/state/AccountThemeMode';+import {makeAutoObservable} from 'mobx';++export type ThemeTarget = 'desktop' | 'account';++class ThemeEditTarget {+ picked: ThemeTarget | null = null;++ constructor() {+ makeAutoObservable(this, {}, {autoBind: true});+ }++ get target(): ThemeTarget {+ if (!AccountThemeMode.canUseDesktopTheme) {+ return 'account';+ }+ return this.picked ?? AccountThemeMode.activeTarget;+ }++ pick(target: ThemeTarget | null): void {+ this.picked = target;+ }++ reset(): void {+ this.picked = null;+ }+}++export default new ThemeEditTarget();diff --git a/fluxer_app/src/features/theme/state/ThemeProfile.ts b/fluxer_app/src/features/theme/state/ThemeProfile.tsnew file mode 100644index 000000000..803a0f7bb--- /dev/null+++ b/fluxer_app/src/features/theme/state/ThemeProfile.ts@@ -0,0 +1,98 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import Accessibility, {+ ACCESSIBILITY_CUSTOM_THEME_STORAGE_KEY,+ ACCESSIBILITY_CUSTOM_THEME_SYNC_STORAGE_KEY,+} from '@app/features/accessibility/state/Accessibility';+import {AppStorageKey} from '@app/features/platform/state/AppStorageKeys';+import AppStorage, {type StorageChangeEvent} from '@app/features/platform/state/PersistentStorage';+import AccountTheme from '@app/features/theme/state/AccountTheme';+import AccountThemeMode from '@app/features/theme/state/AccountThemeMode';+import InstallationTheme from '@app/features/theme/state/InstallationTheme';+import ThemeEditTarget, {type ThemeTarget} from '@app/features/theme/state/ThemeEditTarget';+import ThemeLibrary from '@app/features/theme/state/ThemeLibrary';+import type {ThemeType} from '@fluxer/constants/src/UserConstants';+import {makeAutoObservable, runInAction} from 'mobx';++const PROFILE_STORAGE_KEYS: ReadonlySet<string> = new Set([+ AppStorageKey.ACCOUNT_THEME,+ AppStorageKey.ACCOUNT_THEME_MODE,+ AppStorageKey.INSTALLATION_THEME,+ AppStorageKey.THEME_LIBRARY_ACCOUNT_ENABLED_IDS,+ ACCESSIBILITY_CUSTOM_THEME_STORAGE_KEY,+ ACCESSIBILITY_CUSTOM_THEME_SYNC_STORAGE_KEY,+]);++class ThemeProfile {+ isReady = false;++ constructor() {+ makeAutoObservable(this, {}, {autoBind: true});+ AppStorage.subscribe(this.handleStorageChange);+ }++ get usesDesktopTheme(): boolean {+ return AccountThemeMode.usesDesktopTheme;+ }++ get activeTarget(): ThemeTarget {+ return AccountThemeMode.activeTarget;+ }++ get themePreference(): ThemeType {+ return this.themePreferenceFor(this.activeTarget);+ }++ get customThemeCss(): string | null {+ return this.customThemeCssFor(this.activeTarget);+ }++ get enabledThemeIds(): Array<string> {+ return ThemeLibrary.enabledIdsFor(this.activeTarget);+ }++ get activeThemeCss(): string {+ return ThemeLibrary.themeCssFor(this.enabledThemeIds);+ }++ themePreferenceFor(target: ThemeTarget): ThemeType {+ return target === 'desktop' ? InstallationTheme.baseTheme : AccountTheme.themePreference;+ }++ customThemeCssFor(target: ThemeTarget): string | null {+ return target === 'desktop' ? InstallationTheme.customThemeCss : Accessibility.customThemeCss;+ }++ reload(): void {+ runInAction(() => {+ InstallationTheme.load();+ AccountThemeMode.load();+ AccountTheme.load();+ ThemeLibrary.loadAccountEnabledIds();+ Accessibility.loadCustomThemeCssFromStorage();+ });+ }++ markReady(): void {+ this.reload();+ this.isReady = true;+ }++ private handleStorageChange(event: StorageChangeEvent): void {+ if (event.key === null) {+ runInAction(() => {+ this.reload();+ ThemeEditTarget.reset();+ });+ return;+ }+ if (!PROFILE_STORAGE_KEYS.has(event.key)) {+ return;+ }+ if (event.source === 'external' || event.newValue === null) {+ this.reload();+ }+ }+}++export default new ThemeProfile();diff --git a/fluxer_app/src/features/theme/state/ThemeProfileMigration.ts b/fluxer_app/src/features/theme/state/ThemeProfileMigration.tsnew file mode 100644index 000000000..5176122f9--- /dev/null+++ b/fluxer_app/src/features/theme/state/ThemeProfileMigration.ts@@ -0,0 +1,80 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {normalizeCustomThemeCss, readLocalCustomThemeCss} from '@app/features/accessibility/state/Accessibility';+import {AppStorageKey} from '@app/features/platform/state/AppStorageKeys';+import AppStorage, {flushAppStorageWrites, getAppStorageScope} from '@app/features/platform/state/PersistentStorage';+import {getPersistentStorageBackend} from '@app/features/platform/state/PersistentStorageBackend';+import {Logger} from '@app/features/platform/utils/AppLogger';+import {parseAccountThemeSnapshot, serializeAccountThemeSnapshot} from '@app/features/theme/state/AccountTheme';+import AccountThemeMode from '@app/features/theme/state/AccountThemeMode';+import {+ DEFAULT_INSTALLATION_THEME,+ serializeInstallationThemeSnapshot,+} from '@app/features/theme/state/InstallationTheme';+import ThemeProfile from '@app/features/theme/state/ThemeProfile';+import {getEnabledThemeIds} from '@app/features/theme/utils/ThemeLibraryDb';+import type {ThemeType} from '@fluxer/constants/src/UserConstants';++const logger = new Logger('ThemeProfileMigration');+const UNUSED_THEME_STUDIO_KEYS = ['ThemeStudio:section', 'ThemeStudio:librarySplit'];++async function writeIfAbsent(scope: string, key: string, value: string): Promise<void> {+ if (scope === getAppStorageScope()) {+ if (AppStorage.getItem(key) === null) {+ AppStorage.setItem(key, value);+ }+ return;+ }+ const backend = getPersistentStorageBackend();+ if ((await backend.get(scope, key)) === null) {+ await backend.set(scope, key, value);+ }+}++async function runMigration(accountScopes: ReadonlyArray<string>): Promise<void> {+ if (AppStorage.getItem(AppStorageKey.THEME_PROFILES_MIGRATED) !== null) {+ return;+ }+ const legacyTheme = parseAccountThemeSnapshot(AppStorage.getItem(AppStorageKey.THEME));+ if (AccountThemeMode.canUseDesktopTheme) {+ const signedIn = accountScopes.includes(getAppStorageScope());+ if (AppStorage.getItem(AppStorageKey.INSTALLATION_THEME) === null) {+ let baseTheme: ThemeType;+ if (legacyTheme === null) {+ baseTheme = DEFAULT_INSTALLATION_THEME.baseTheme;+ } else if (legacyTheme.syncAcrossDevices) {+ baseTheme = legacyTheme.serverTheme;+ } else {+ baseTheme = legacyTheme.localTheme;+ }+ const customThemeCss = signedIn ? normalizeCustomThemeCss(readLocalCustomThemeCss()) : null;+ AppStorage.setItem(+ AppStorageKey.INSTALLATION_THEME,+ serializeInstallationThemeSnapshot({baseTheme, customThemeCss}),+ );+ }+ }+ const enabledThemeIds = JSON.stringify(await getEnabledThemeIds());+ await flushAppStorageWrites();+ const scopes = new Set([getAppStorageScope(), ...accountScopes]);+ for (const scope of scopes) {+ if (legacyTheme !== null) {+ await writeIfAbsent(scope, AppStorageKey.ACCOUNT_THEME, serializeAccountThemeSnapshot(legacyTheme));+ }+ await writeIfAbsent(scope, AppStorageKey.THEME_LIBRARY_ACCOUNT_ENABLED_IDS, enabledThemeIds);+ }+ for (const key of UNUSED_THEME_STUDIO_KEYS) {+ AppStorage.removeItem(key);+ }+ AppStorage.setItem(AppStorageKey.THEME_PROFILES_MIGRATED, '1');+}++export async function migrateThemeProfiles(accountScopes: ReadonlyArray<string>): Promise<void> {+ try {+ await runMigration(accountScopes);+ } catch (error) {+ logger.error('Failed to move theme settings into each account', error);+ } finally {+ ThemeProfile.markReady();+ }+}