A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(app): apply account theme profiles and instance custom CSS
Hampus43d4385fa62d
diff --git a/fluxer_app/scripts/GenerateThemeVariables.ts b/fluxer_app/scripts/GenerateThemeVariables.tsindex 23caec333..904c3aa81 100644--- a/fluxer_app/scripts/GenerateThemeVariables.ts+++ b/fluxer_app/scripts/GenerateThemeVariables.ts@@ -34,7 +34,7 @@ const PRIORITY_CSS_SOURCES: ReadonlyArray<CssSource> = [},];const PRIORITY_SOURCE_INDEX = new Map(PRIORITY_CSS_SOURCES.map((source, index) => [source.file, index]));-const IGNORED_SOURCE_PREFIXES = ['src/features/theme_studio/', 'src/theme/'];+const IGNORED_SOURCE_PREFIXES = ['src/theme/'];const BUNDLED_FONT_VARIABLES_CSS = resolve(import.meta.dirname,@@ -448,9 +448,9 @@ ${renderStringArray(definitions.map((definition) => definition.name),)}-${renderValueMap('THEME_STUDIO_DARK_DEFAULT_VARIABLE_VALUES', darkDefaults)}+${renderValueMap('THEME_DARK_DEFAULT_VARIABLE_VALUES', darkDefaults)}-${renderValueMap('THEME_STUDIO_LIGHT_DEFAULT_VARIABLE_VALUES', lightDefaults)}+${renderValueMap('THEME_LIGHT_DEFAULT_VARIABLE_VALUES', lightDefaults)}`;}diff --git a/fluxer_app/src/app/App.tsx b/fluxer_app/src/app/App.tsxindex 315bbcce2..3a7db453d 100644--- a/fluxer_app/src/app/App.tsx+++ b/fluxer_app/src/app/App.tsx@@ -2,10 +2,10 @@import styles from '@app/app/App.module.css';import {router} from '@app/app/Router';-import * as AccessibilityCommands from '@app/features/accessibility/commands/AccessibilityCommands';import {NekoSprite} from '@app/features/accessibility/components/NekoSprite';import Accessibility from '@app/features/accessibility/state/Accessibility';import ScreenReader from '@app/features/accessibility/state/ScreenReader';+import AccountEngine from '@app/features/account_engine/state/AccountEngine';import {DndContext} from '@app/features/app/components/layout/DndContext';import GlobalOverlays from '@app/features/app/components/layout/GlobalOverlays';import {NativeTitlebar} from '@app/features/app/components/layout/NativeTitlebar';@@ -22,6 +22,7 @@ import {useTabKeyFocusGuard} from '@app/features/app/hooks/useTabKeyFocusGuard';import {type LayoutVariant, LayoutVariantProvider} from '@app/features/app/state/LayoutVariantContext';import RuntimeConfig from '@app/features/app/state/RuntimeConfig';import RuntimeCrash from '@app/features/app/state/RuntimeCrash';+import {getServedDocumentBranding} from '@app/features/app/state/ServedDocumentBranding';import DeveloperOptions from '@app/features/devtools/state/DeveloperOptions';import {showMyselfTypingHelper} from '@app/features/devtools/utils/ShowMyselfTypingHelper';import GatewaySessions from '@app/features/gateway/transport/GatewaySessionPool';@@ -37,14 +38,15 @@ import {startDesktopJumpListBridge} from '@app/features/platform/utils/DesktopJuimport {startDesktopLocaleBridge} from '@app/features/platform/utils/DesktopLocaleBridge';import {PremiumCheckoutReturnWatcher} from '@app/features/premium/components/PremiumCheckoutReturnWatcher';import {QUICK_SWITCHER_PORTAL_ID} from '@app/features/search/components/quick_switcher/QuickSwitcherConstants';-import {useCustomThemeStyle} from '@app/features/theme/hooks/useCustomThemeStyle';+import {useCustomThemeStyle, useInstanceCustomCss} from '@app/features/theme/hooks/useCustomThemeStyle';import {useRemScaleTracking} from '@app/features/theme/hooks/useRemScaleTracking';import {useThemeCssVariables} from '@app/features/theme/hooks/useThemeCssVariables';import Theme from '@app/features/theme/state/Theme';import ThemeLibrary from '@app/features/theme/state/ThemeLibrary';+import ThemeProfile from '@app/features/theme/state/ThemeProfile';import WindowsFont from '@app/features/theme/state/WindowsFont';-import {useThemeStudioBroadcast} from '@app/features/theme_studio/state/ThemeStudioBroadcast';-import ThemeStudioState from '@app/features/theme_studio/state/ThemeStudioState';+import {QuickCssEditorWindowHost} from '@app/features/theme_settings/components/QuickCssEditorWindowHost';+import ThemeSettingsState from '@app/features/theme_settings/state/ThemeSettingsState';import {SVGMasks} from '@app/features/ui/components/SVGMasks';import FocusRingScope from '@app/features/ui/focus_ring/FocusRingScope';import {useTextInputContextMenu} from '@app/features/ui/hooks/useTextInputContextMenu';@@ -64,31 +66,46 @@ import {startScreenSharePiPController} from '@app/features/voice/state/ScreenShaimport {useNativeTitleBar} from '@app/features/window/hooks/useNativeTitleBar';import {useStopFlashFrameOnFocus} from '@app/features/window/hooks/useStopFlashFrameOnFocus';import {useWindowEventListeners} from '@app/features/window/hooks/useWindowEventListeners';+import {ThemeTypes} from '@fluxer/constants/src/UserConstants';import {i18n} from '@lingui/core';import {msg} from '@lingui/core/macro';import {useLingui} from '@lingui/react/macro';import {IconContext} from '@phosphor-icons/react';import {reaction} from 'mobx';import {observer} from 'mobx-react-lite';-import React, {type ReactNode, useCallback, useEffect, useMemo, useRef, useState} from 'react';+import React, {type ReactNode, useEffect, useMemo, useRef, useState} from 'react';const SKIP_TO_CONTENT_DESCRIPTOR = msg({message: 'Skip to content',comment: 'Accessible skip-link label for keyboard users.',});+function focusMainContent(event: React.MouseEvent<HTMLButtonElement>): void {+ event.currentTarget.ownerDocument.getElementById('main-content')?.focus();+}+const logger = new Logger('App');interface AppWrapperProps {children: ReactNode;}-function getInstanceThemeColor(): string | null {+interface InstanceBrandStyle {+ readonly themeColor: string | null;+ readonly customCss: string | null;+}++const NO_INSTANCE_BRAND_STYLE: InstanceBrandStyle = Object.freeze({themeColor: null, customCss: null});++function getInstanceBrandStyle(): InstanceBrandStyle {const snapshot = RuntimeConfig.getSnapshotOrNull();- if (snapshot === null || !(DeveloperOptions.selfHostedModeOverride || snapshot.features.self_hosted)) {- return null;+ if (snapshot === null) {+ return getServedDocumentBranding();+ }+ if (!(DeveloperOptions.selfHostedModeOverride || snapshot.features.self_hosted)) {+ return NO_INSTANCE_BRAND_STYLE;}- return snapshot.appPublic.branding.theme_color ?? null;+ return {themeColor: snapshot.appPublic.branding.theme_color, customCss: snapshot.appPublic.branding.custom_css};}export const AppWrapper = observer(({children}: AppWrapperProps) => {@@ -111,25 +128,6 @@ export const AppWrapper = observer(({children}: AppWrapperProps) => {const overlayScopeRef = useRef<HTMLDivElement>(null);useElectronScreenSharePicker();useTextInputContextMenu();- useThemeStudioBroadcast(- useCallback((message) => {- switch (message.type) {- case 'customThemeCss':- if ((Accessibility.customThemeCss ?? null) !== message.value) {- AccessibilityCommands.update({customThemeCss: message.value});- }- return;- case 'themeLibrary':- void ThemeLibrary.reload();- return;- case 'studio:closed-popout':- ThemeStudioState.clearPoppedOut();- return;- default:- return;- }- }, []),- );const handleSkipLinkFocus = useTabKeyFocusGuard();useInertBackground(ringsContainerRef, hasBlockingModal || topPopoutRequiresBackdrop);useEffect(() => {@@ -138,6 +136,7 @@ export const AppWrapper = observer(({children}: AppWrapperProps) => {}, []);useEffect(() => {let active = true;+ AccountEngine.start();void SessionManager.initialize().then(() => {if (active) {@@ -150,6 +149,7 @@ export const AppWrapper = observer(({children}: AppWrapperProps) => {return () => {active = false;GatewaySessions.dispose();+ AccountEngine.stop();};}, []);useEffect(@@ -189,8 +189,10 @@ export const AppWrapper = observer(({children}: AppWrapperProps) => {useWindowEventListeners();useRemScaleTracking();usePlatformClasses(platform, isNative);+ const isAuthLayout = layoutVariant === 'auth';+ const instanceBrandStyle = getInstanceBrandStyle();useThemeCssVariables({- effectiveTheme: Theme.effectiveTheme,+ effectiveTheme: isAuthLayout ? ThemeTypes.DARK : Theme.effectiveTheme,saturationFactor: Accessibility.saturationFactor,alwaysUnderlineLinks: Accessibility.alwaysUnderlineLinks,dimStrikethroughText: Accessibility.dimStrikethroughText,@@ -199,14 +201,16 @@ export const AppWrapper = observer(({children}: AppWrapperProps) => {messageGutter: Accessibility.messageGutter,messageGroupSpacing: Accessibility.getMessageGroupSpacingValue(messageDisplayCompact),hdrDisplayMode: Accessibility.hdrDisplayMode,- instanceThemeColor: getInstanceThemeColor(),+ instanceThemeColor: instanceBrandStyle.themeColor,});+ useInstanceCustomCss(instanceBrandStyle.customCss);useCustomThemeStyle({- enabledThemeCss: ThemeLibrary.activeThemeCss,- customThemeCss: Accessibility.customThemeCss,+ enabledThemeCss: isAuthLayout ? null : ThemeProfile.activeThemeCss,+ customThemeCss: isAuthLayout ? null : ThemeProfile.customThemeCss,themeLibraryAssets: ThemeLibrary.assets,themeLibraryLocalFiles: ThemeLibrary.localFiles,themeLibraryRevision: ThemeLibrary.revision,+ onMissingReferences: ThemeSettingsState.setMissingReferences,});return (<LayoutVariantProvider value={layoutVariantContextValue} data-flx="app.app.app-wrapper.layout-variant-provider">@@ -214,14 +218,15 @@ export const AppWrapper = observer(({children}: AppWrapperProps) => {<VoiceLiveKitRoot room={room} data-flx="app.app.app-wrapper.voice-live-kit-root"><div ref={ringsContainerRef} className={styles.appContainer} data-flx="app.app.app-wrapper.app-container"><FocusRingScope containerRef={ringsContainerRef} data-flx="app.app.app-wrapper.focus-ring-scope">- <a- href="#main-content"+ <button+ type="button"className={styles.skipLink}onFocus={handleSkipLinkFocus}+ onClick={focusMainContent}data-flx="app.app.app-wrapper.skip-link">{i18n._(SKIP_TO_CONTENT_DESCRIPTOR)}- </a>+ </button>{isNative && !useSystemTitleBar && !isRootDocumentFullscreen && (<NativeTitlebar platform={platform} data-flx="app.app.app-wrapper.native-titlebar" />)}@@ -239,6 +244,9 @@ export const AppWrapper = observer(({children}: AppWrapperProps) => {/><GlobalOverlays data-flx="app.app.app-wrapper.global-overlays" /><IncomingCallManager data-flx="app.app.app-wrapper.incoming-call-manager" />+ {isAuthLayout ? null : (+ <QuickCssEditorWindowHost data-flx="app.app.app-wrapper.quick-css-editor-window-host" />+ )}</div></VoiceLiveKitRoot></LayoutVariantProvider>@@ -260,8 +268,9 @@ export const App = observer((): React.ReactElement => {useEffect(() => {if (!isDesktop()) return;startDesktopLocaleBridge();- startDesktopJumpListBridge();+ const disposeJumpList = startDesktopJumpListBridge();ScreenReader.startDesktopBridge();+ return disposeJumpList;}, []);useStopFlashFrameOnFocus();useEffect(() => {diff --git a/fluxer_app/src/features/theme/components/modals/ThemeAcceptModal.module.css b/fluxer_app/src/features/theme/components/modals/ThemeAcceptModal.module.cssindex f6850e5bb..eba84e894 100644--- a/fluxer_app/src/features/theme/components/modals/ThemeAcceptModal.module.css+++ b/fluxer_app/src/features/theme/components/modals/ThemeAcceptModal.module.css@@ -53,7 +53,7 @@.codeActions {position: absolute;top: 0.5rem;- right: 0.5rem;+ inset-inline-end: 0.5rem;opacity: 0;transition: opacity var(--transition-normal);z-index: 10;diff --git a/fluxer_app/src/features/theme/components/modals/ThemeAcceptModal.tsx b/fluxer_app/src/features/theme/components/modals/ThemeAcceptModal.tsxindex 14b80b8ec..ca693c6fa 100644--- a/fluxer_app/src/features/theme/components/modals/ThemeAcceptModal.tsx+++ b/fluxer_app/src/features/theme/components/modals/ThemeAcceptModal.tsx@@ -1,6 +1,5 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import * as AccessibilityCommands from '@app/features/accessibility/commands/AccessibilityCommands';import {showGenericErrorModal} from '@app/features/app/components/alerts/GenericErrorModalCommands';import * as Modal from '@app/features/app/components/dialogs/Modal';import type {RuntimeConfigSnapshot} from '@app/features/app/state/InstanceSnapshotStore';@@ -8,12 +7,14 @@ import {useArboriumHighlightedHtml} from '@app/features/code_highlighting/utils/import {COPY_CODE_DESCRIPTOR, SOMETHING_WENT_WRONG_DESCRIPTOR} from '@app/features/i18n/utils/CommonMessageDescriptors';import {Logger} from '@app/features/platform/utils/AppLogger';import styles from '@app/features/theme/components/modals/ThemeAcceptModal.module.css';+import ThemeEditTarget from '@app/features/theme/state/ThemeEditTarget';import {buildThemeCssFetchUrl} from '@app/features/theme/utils/ThemeUtils';+import * as ThemeSettingsCommands from '@app/features/theme_settings/commands/ThemeSettingsCommands';+import {useCurrentAccountLabels} from '@app/features/theme_settings/hooks/useCurrentAccountLabels';import {Button} from '@app/features/ui/button/Button';import * as ModalCommands from '@app/features/ui/commands/ModalCommands';import * as ToastCommands from '@app/features/ui/commands/ToastCommands';import {CopyButton} from '@app/features/ui/components/CopyButton';-import {formatUserSettingsPath} from '@app/features/user/components/settings_utils/SettingsConstants';import {msg} from '@lingui/core/macro';import {Trans, useLingui} from '@lingui/react/macro';import {observer} from 'mobx-react-lite';@@ -35,6 +36,19 @@ const WE_COULDN_T_APPLY_THIS_THEME_DESCRIPTOR = msg({message: "We couldn't apply this theme.",comment: 'Error message in the theme accept modal.',});+const REPLACES_DESKTOP_QUICK_CSS_DESCRIPTOR = msg({+ message: 'This replaces the quick CSS in the desktop app theme.',+ comment: 'Shown in the modal that applies a shared theme while the desktop app theme is being edited.',+});+const REPLACES_ACCOUNT_QUICK_CSS_DESCRIPTOR = msg({+ message: 'This replaces the quick CSS for {username} on {instanceName}.',+ comment:+ "Shown in the modal that applies a shared theme to the current account's own theme. {username} is the account's username and {instanceName} is its instance.",+});+const OPEN_IN_THEMES_DESCRIPTOR = msg({+ message: 'Open in Themes',+ comment: 'Button in the modal that applied a shared theme. Opens Settings > Themes.',+});const logger = new Logger('ThemeAcceptModal');interface ThemeAcceptModalProps {@@ -44,8 +58,10 @@ interface ThemeAcceptModalProps {export const ThemeAcceptModal = observer(function ThemeAcceptModal({themeId, runtimeSnapshot}: ThemeAcceptModalProps) {const {i18n} = useLingui();- const themeSettingsPath = formatUserSettingsPath(i18n, 'appearance', 'theme');+ const {username, instanceName} = useCurrentAccountLabels();+ const target = ThemeEditTarget.target;const [isApplying, setIsApplying] = useState(false);+ const [isApplied, setIsApplied] = useState(false);const [css, setCss] = useState<string | null>(null);const [fetchStatus, setFetchStatus] = useState<'idle' | 'loading' | 'error' | 'ready'>('idle');const [fetchError, setFetchError] = useState<string | null>(null);@@ -95,9 +111,10 @@ export const ThemeAcceptModal = observer(function ThemeAcceptModal({themeId, run}setIsApplying(true);try {- AccessibilityCommands.update({customThemeCss: css});+ ThemeSettingsCommands.setEditedCustomThemeCss(css);ToastCommands.success(i18n._(THEME_APPLIED_SUCCESSFULLY_DESCRIPTOR));- ModalCommands.pop();+ setIsApplied(true);+ setIsApplying(false);} catch (error) {logger.error('Failed to apply theme:', error);showGenericErrorModal({@@ -139,7 +156,9 @@ export const ThemeAcceptModal = observer(function ThemeAcceptModal({themeId, run<Modal.Header title={<Trans>Import theme</Trans>} data-flx="theme.theme-accept-modal.modal-header" /><Modal.Content padding="none" className={styles.content} data-flx="theme.theme-accept-modal.content"><p className={styles.description} data-flx="theme.theme-accept-modal.description">- <Trans>This will replace your current custom theme. You can edit it later in {themeSettingsPath}.</Trans>+ {target === 'desktop'+ ? i18n._(REPLACES_DESKTOP_QUICK_CSS_DESCRIPTOR)+ : i18n._(REPLACES_ACCOUNT_QUICK_CSS_DESCRIPTOR, {username, instanceName})}</p><div className={styles.codeContainer} data-flx="theme.theme-accept-modal.code-container"><CopyButton@@ -158,22 +177,41 @@ export const ThemeAcceptModal = observer(function ThemeAcceptModal({themeId, run</div></Modal.Content><Modal.Footer className={styles.footer} data-flx="theme.theme-accept-modal.footer">- <Button- variant="secondary"- onClick={handleDismiss}- disabled={isApplying}- data-flx="theme.theme-accept-modal.button.dismiss"- >- <Trans>Cancel</Trans>- </Button>- <Button- onClick={handleApply}- disabled={isApplying || fetchStatus !== 'ready'}- submitting={isApplying}- data-flx="theme.theme-accept-modal.button.apply"- >- <Trans>Apply</Trans>- </Button>+ {isApplied ? (+ <>+ <Button variant="secondary" onClick={handleDismiss} data-flx="theme.theme-accept-modal.button.done">+ <Trans>Done</Trans>+ </Button>+ <Button+ onClick={() => {+ ModalCommands.pop();+ ThemeSettingsCommands.openThemesSettings();+ }}+ data-flx="theme.theme-accept-modal.button.open-in-themes"+ >+ {i18n._(OPEN_IN_THEMES_DESCRIPTOR)}+ </Button>+ </>+ ) : (+ <>+ <Button+ variant="secondary"+ onClick={handleDismiss}+ disabled={isApplying}+ data-flx="theme.theme-accept-modal.button.dismiss"+ >+ <Trans>Cancel</Trans>+ </Button>+ <Button+ onClick={handleApply}+ disabled={isApplying || fetchStatus !== 'ready'}+ submitting={isApplying}+ data-flx="theme.theme-accept-modal.button.apply"+ >+ <Trans>Apply</Trans>+ </Button>+ </>+ )}</Modal.Footer></Modal.Root>);diff --git a/fluxer_app/src/features/theme/hooks/useCustomThemeStyle.ts b/fluxer_app/src/features/theme/hooks/useCustomThemeStyle.tsindex 43a9b41ae..47f98444d 100644--- a/fluxer_app/src/features/theme/hooks/useCustomThemeStyle.ts+++ b/fluxer_app/src/features/theme/hooks/useCustomThemeStyle.ts@@ -6,7 +6,8 @@ import type {ThemeLibraryAsset, ThemeLibraryLocalFileReference} from '@app/featuimport {resolveThemeCssReferences} from '@app/features/theme/utils/ThemeCssUtils';import {useEffect} from 'react';-const STYLE_ELEMENT_ID = 'fluxer-custom-theme-style';+export const CUSTOM_THEME_STYLE_ELEMENT_ID = 'fluxer-custom-theme-style';+export const INSTANCE_CUSTOM_CSS_ELEMENT_ID = 'fluxer-instance-custom-css';const logger = new Logger('useCustomThemeStyle');interface CustomThemeStyleOptions {@@ -15,6 +16,28 @@ interface CustomThemeStyleOptions {themeLibraryAssets: ReadonlyArray<ThemeLibraryAsset>;themeLibraryLocalFiles: ReadonlyArray<ThemeLibraryLocalFileReference>;themeLibraryRevision: number;+ onMissingReferences: (references: ReadonlyArray<string>) => void;+}++export function useInstanceCustomCss(instanceCss: string | null): void {+ useEffect(() => {+ const css = instanceCss?.trim() ?? '';+ const existing = document.getElementById(INSTANCE_CUSTOM_CSS_ELEMENT_ID);+ if (!css) {+ if (existing) {+ existing.remove();+ clearRemScaleCache();+ }+ return;+ }+ const styleElement = existing ?? document.createElement('style');+ styleElement.id = INSTANCE_CUSTOM_CSS_ELEMENT_ID;+ styleElement.textContent = css;+ if (!existing) {+ document.head.insertBefore(styleElement, document.getElementById(CUSTOM_THEME_STYLE_ELEMENT_ID));+ }+ clearRemScaleCache();+ }, [instanceCss]);}export function useCustomThemeStyle({@@ -23,14 +46,16 @@ export function useCustomThemeStyle({themeLibraryAssets,themeLibraryLocalFiles,themeLibraryRevision,+ onMissingReferences,}: CustomThemeStyleOptions): void {useEffect(() => {- const existing = document.getElementById(STYLE_ELEMENT_ID) as HTMLStyleElement | null;+ const existing = document.getElementById(CUSTOM_THEME_STYLE_ELEMENT_ID) as HTMLStyleElement | null;const css = [enabledThemeCss, customThemeCss].map((value) => value?.trim() ?? '').filter(Boolean).join('\n\n');if (!css) {+ onMissingReferences([]);if (existing?.parentNode) {existing.parentNode.removeChild(existing);clearRemScaleCache();@@ -42,7 +67,7 @@ export function useCustomThemeStyle({styleElement.textContent = value;clearRemScaleCache();};- styleElement.id = STYLE_ELEMENT_ID;+ styleElement.id = CUSTOM_THEME_STYLE_ELEMENT_ID;let disposed = false;let objectUrls: Array<string> = [];void resolveThemeCssReferences(css, themeLibraryAssets, themeLibraryLocalFiles)@@ -55,6 +80,7 @@ export function useCustomThemeStyle({}objectUrls = resolved.objectUrls;applyThemeCss(resolved.css);+ onMissingReferences([...resolved.missingAssetReferences, ...resolved.missingLocalFileReferences]);if (resolved.missingAssetReferences.length > 0 || resolved.missingLocalFileReferences.length > 0) {logger.warn('Custom theme CSS has unresolved file references', {assets: resolved.missingAssetReferences,@@ -75,5 +101,12 @@ export function useCustomThemeStyle({URL.revokeObjectURL(objectUrl);}};- }, [customThemeCss, enabledThemeCss, themeLibraryAssets, themeLibraryLocalFiles, themeLibraryRevision]);+ }, [+ customThemeCss,+ enabledThemeCss,+ themeLibraryAssets,+ themeLibraryLocalFiles,+ themeLibraryRevision,+ onMissingReferences,+ ]);}diff --git a/fluxer_app/src/features/theme/state/Theme.ts b/fluxer_app/src/features/theme/state/Theme.tsindex 9f7005352..32022a981 100644--- a/fluxer_app/src/features/theme/state/Theme.ts+++ b/fluxer_app/src/features/theme/state/Theme.ts@@ -1,12 +1,11 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport AppStorage from '@app/features/platform/state/PersistentStorage';-import {makePersistent} from '@app/features/platform/utils/MobXPersistence';-import {initializeStore} from '@app/features/platform/utils/StoreInitialization';+import type {ThemeTarget} from '@app/features/theme/state/ThemeEditTarget';+import ThemeProfile from '@app/features/theme/state/ThemeProfile';import {getElectronAPI} from '@app/features/ui/utils/NativeUtils';import type {LinuxAppearanceSnapshot} from '@app/types/electron.d';-import type {ThemeType} from '@fluxer/constants/src/UserConstants';-import {ThemeTypes} from '@fluxer/constants/src/UserConstants';+import {type ThemeType, ThemeTypes} from '@fluxer/constants/src/UserConstants';import {makeAutoObservable, reaction, runInAction} from 'mobx';type ExplicitTheme =@@ -15,24 +14,13 @@ type ExplicitTheme =| typeof ThemeTypes.LIGHT| typeof ThemeTypes.COAL;-export interface ThemePreferenceSnapshot {- syncAcrossDevices: boolean;- localTheme: ThemeType;- serverTheme: ThemeType;-}-const EXPLICIT_THEMES = new Set<string>([ThemeTypes.DARK, ThemeTypes.DARK_LEGACY, ThemeTypes.LIGHT, ThemeTypes.COAL]);-const VALID_THEMES = new Set<string>(Object.values(ThemeTypes));const STORAGE_KEY = 'theme';function isExplicitTheme(theme: string | null | undefined): theme is ExplicitTheme {return typeof theme === 'string' && EXPLICIT_THEMES.has(theme);}-function isValidTheme(theme: string | null | undefined): theme is ThemeType {- return typeof theme === 'string' && VALID_THEMES.has(theme);-}-function loadThemeFromLocalStorage(): ExplicitTheme | null {try {const stored = AppStorage.getItem(STORAGE_KEY);@@ -50,13 +38,12 @@ function persistThemeToLocalStorage(theme: string): void {} catch {}}+function reportPrebootTheme(theme: string): void {+ getElectronAPI()?.setPrebootTheme?.(theme);+}+class Theme {- syncAcrossDevices = true;- localTheme: ThemeType = ThemeTypes.DARK;- serverTheme: ThemeType = ThemeTypes.DARK;systemPrefersDark = false;- private _hydrated = false;- private _pendingServerTheme: ThemeType | null = null;private mediaQuery: MediaQueryList | null = null;private localStorageSyncDisposer: (() => void) | null = null;private linuxPortalPrefersDark: boolean | null = null;@@ -66,76 +53,37 @@ class Theme {makeAutoObservable(this, {}, {autoBind: true});this.initSystemThemeDetection();this.initLinuxPortalThemeDetection();- initializeStore(this, () => this.initPersistence());- }-- get isHydrated(): boolean {- return this._hydrated;- }-- get themePreference(): ThemeType {- return this.syncAcrossDevices ? this.serverTheme : this.localTheme;+ this.localStorageSyncDisposer = reaction(+ () => (ThemeProfile.isReady ? this.effectiveTheme : null),+ (theme) => {+ if (theme !== null) {+ persistThemeToLocalStorage(theme);+ reportPrebootTheme(theme);+ }+ },+ {fireImmediately: true},+ );}get effectiveTheme(): ExplicitTheme {- if (!this._hydrated) {+ if (!ThemeProfile.isReady) {const earlyTheme = loadThemeFromLocalStorage();if (earlyTheme) {return earlyTheme;}}- const preference = this.themePreference;- if (preference === ThemeTypes.SYSTEM) {- return this.systemPrefersDark ? ThemeTypes.DARK : ThemeTypes.LIGHT;- }- return preference;+ return this.resolvePreference(ThemeProfile.themePreference);}- setTheme(theme: ThemeType): void {- if (!isValidTheme(theme)) {- return;- }- if (this.syncAcrossDevices) {- this.serverTheme = theme;- } else {- this.localTheme = theme;- }+ themeFor(target: ThemeTarget): ExplicitTheme {+ return this.resolvePreference(ThemeProfile.themePreferenceFor(target));}- setSyncAcrossDevices(sync: boolean): void {- if (sync === this.syncAcrossDevices) {- return;- }- if (sync) {- this.syncAcrossDevices = true;- this.localTheme = ThemeTypes.DARK;- } else {- const currentPreference = this.themePreference;- this.syncAcrossDevices = false;- this.localTheme = currentPreference;- }- }-- getPreferenceSnapshot(): ThemePreferenceSnapshot {- return {- syncAcrossDevices: this.syncAcrossDevices,- localTheme: this.localTheme,- serverTheme: this.serverTheme,- };- }-- applyPreferenceSnapshot(snapshot: ThemePreferenceSnapshot): void {- this.syncAcrossDevices = Boolean(snapshot.syncAcrossDevices);- this.localTheme = isValidTheme(snapshot.localTheme) ? snapshot.localTheme : ThemeTypes.DARK;- this.serverTheme = isValidTheme(snapshot.serverTheme) ? snapshot.serverTheme : ThemeTypes.DARK;- }-- updateServerTheme(theme: string | null | undefined): void {- const normalized = isValidTheme(theme) ? theme : ThemeTypes.DARK;- this.serverTheme = normalized;- if (!this._hydrated) {- this._pendingServerTheme = normalized;+ private resolvePreference(preference: ThemeType): ExplicitTheme {+ if (preference === ThemeTypes.SYSTEM) {+ return this.systemPrefersDark ? ThemeTypes.DARK : ThemeTypes.LIGHT;}+ return preference;}private initSystemThemeDetection(): void {@@ -190,22 +138,6 @@ class Theme {});}- private async initPersistence(): Promise<void> {- await makePersistent(this, 'Theme', ['syncAcrossDevices', 'localTheme', 'serverTheme'], {syncAcrossTabs: true});- runInAction(() => {- if (this._pendingServerTheme !== null) {- this.serverTheme = this._pendingServerTheme;- this._pendingServerTheme = null;- }- this._hydrated = true;- });- this.localStorageSyncDisposer = reaction(- () => this.effectiveTheme,- (theme) => persistThemeToLocalStorage(theme),- {fireImmediately: true},- );- }-destroy(): void {if (this.mediaQuery) {this.mediaQuery.removeEventListener('change', this.handleSystemThemeChange);diff --git a/fluxer_app/src/features/theme/state/ThemeLibrary.ts b/fluxer_app/src/features/theme/state/ThemeLibrary.tsindex 9d5353213..d6276fd7b 100644--- a/fluxer_app/src/features/theme/state/ThemeLibrary.ts+++ b/fluxer_app/src/features/theme/state/ThemeLibrary.ts@@ -4,6 +4,7 @@ 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 {randomUuid} from '@app/features/platform/utils/RandomUuid';+import type {ThemeTarget} from '@app/features/theme/state/ThemeEditTarget';import {assetToExportDataUrl,parseThemeMetadata,@@ -17,6 +18,7 @@ import {deleteThemeLibraryAsset,deleteThemeLibraryLocalFile,deleteThemeLibraryTheme,+ getAccountEnabledThemeIds,getEnabledThemeIds,listThemeLibraryAssets,listThemeLibraryLocalFiles,@@ -24,6 +26,7 @@ import {saveThemeLibraryAsset,saveThemeLibraryLocalFile,saveThemeLibraryTheme,+ setAccountEnabledThemeIds,setEnabledThemeIds,updateThemeLibraryThemes,} from '@app/features/theme/utils/ThemeLibraryDb';@@ -39,7 +42,7 @@ const logger = new Logger('ThemeLibrary');const DUPLICATE_THEME_NAME_DESCRIPTOR = msg({message: '{themeName} Copy',comment:- 'Name given to the copy created by the Duplicate button in the Theme Studio theme library. {themeName} is the name of the theme being duplicated.',+ 'Name given to the copy created by the "Duplicate" menu item in Settings > Themes. {themeName} is the name of the theme being duplicated.',});type ThemeLibraryThemeSource = 'quick_css' | 'css_file' | 'desktop_directory' | 'shared_theme' | 'import';@@ -121,6 +124,10 @@ const THEME_LIBRARY_STORAGE_KEYS: ReadonlySet<string> = new Set([AppStorageKey.THEME_LIBRARY_ENABLED_IDS,]);+export function getThemeLabel(theme: ThemeLibraryTheme): string {+ return theme.name || theme.fileName;+}+function themeSortValue(theme: ThemeLibraryTheme): string {return `${theme.name.toLowerCase()}\u0000${theme.updatedAt}`;}@@ -129,7 +136,8 @@ class ThemeLibrary {themes: Array<ThemeLibraryTheme> = [];assets: Array<ThemeLibraryAsset> = [];localFiles: Array<ThemeLibraryLocalFileReference> = [];- enabledThemeIds: Array<string> = [];+ installationEnabledIds: Array<string> = [];+ accountEnabledIds: Array<string> = getAccountEnabledThemeIds();isHydrated = false;loadFailed = false;isBusy = false;@@ -140,32 +148,37 @@ class ThemeLibrary {private loadGeneration = 0;private storageSyncStarted = false;private linkedFileCss = new Map<string, string>();- private linkedThemesChanged: (() => void) | null = null;constructor() {- makeAutoObservable<this, 'linkedFileCss' | 'linkedThemesChanged' | 'loadGeneration' | 'storageSyncStarted'>(+ makeAutoObservable<this, 'linkedFileCss' | 'loadGeneration' | 'storageSyncStarted'>(this,- {linkedFileCss: false, linkedThemesChanged: false, loadGeneration: false, storageSyncStarted: false},+ {linkedFileCss: false, loadGeneration: false, storageSyncStarted: false},{autoBind: true},);}- get enabledThemes(): Array<ThemeLibraryTheme> {- const byId = new Map(this.themes.map((theme) => [theme.id, theme]));- return this.enabledThemeIds.map((id) => byId.get(id)).filter((theme): theme is ThemeLibraryTheme => theme != null);+ enabledIdsFor(target: ThemeTarget): Array<string> {+ const ids = target === 'desktop' ? this.installationEnabledIds : this.accountEnabledIds;+ return ids.filter((id) => this.has(id));}- get activeThemeCss(): string {- return this.enabledThemes- .map((theme) => theme.css.trim())+ has(id: string): boolean {+ return this.themes.some((theme) => theme.id === id);+ }++ themeCssFor(themeIds: ReadonlyArray<string>): string {+ const byId = new Map(this.themes.map((theme) => [theme.id, theme]));+ return themeIds+ .map((id) => byId.get(id)?.css.trim() ?? '').filter(Boolean).join('\n\n');}get watchedLinkedPaths(): Array<string> {const paths = new Set<string>();- for (const theme of this.enabledThemes) {- if (theme.linkedPath) paths.add(theme.linkedPath);+ const enabledIds = new Set([...this.installationEnabledIds, ...this.accountEnabledIds]);+ for (const theme of this.themes) {+ if (theme.linkedPath && enabledIds.has(theme.id)) paths.add(theme.linkedPath);}const focusedTheme = this.focusedThemeId? this.themes.find((theme) => theme.id === this.focusedThemeId)@@ -227,7 +240,7 @@ class ThemeLibrary {this.themes = themes.sort((a, b) => themeSortValue(a).localeCompare(themeSortValue(b)));this.assets = assets.sort((a, b) => a.name.localeCompare(b.name));this.localFiles = localFiles.sort((a, b) => a.name.localeCompare(b.name));- this.enabledThemeIds = enabledThemeIds.filter((id) => themes.some((theme) => theme.id === id));+ this.installationEnabledIds = enabledThemeIds;this.isHydrated = true;this.loadFailed = false;this.revision += 1;@@ -406,14 +419,13 @@ class ThemeLibrary {});}- startLinkedFileSync(options?: {onThemesChanged?: () => void}): () => void {+ startLinkedFileSync(): () => void {const electronApi = getElectronAPI();const watchThemeLinkedFiles = electronApi?.watchThemeLinkedFiles;const onThemeLinkedFileChange = electronApi?.onThemeLinkedFileChange;if (!watchThemeLinkedFiles || !onThemeLinkedFileChange) {return () => {};}- this.linkedThemesChanged = options?.onThemesChanged ?? null;const watch = (paths: Array<string>): void => {void watchThemeLinkedFiles(paths).catch((error) => {logger.warn('Failed to update linked theme file watch', error);@@ -452,21 +464,15 @@ class ThemeLibrary {disposeReaction();unsubscribe();this.linkedFileCss.clear();- this.linkedThemesChanged = null;watch([]);};}private syncLinkedFileCss(path: string): void {- void this.applyLinkedFileCss(path).then(- (written) => {- if (written) this.linkedThemesChanged?.();- },- (error) => logger.warn('Failed to apply linked theme file', error),- );+ void this.applyLinkedFileCss(path).catch((error) => logger.warn('Failed to apply linked theme file', error));}- private async applyLinkedFileCss(path: string): Promise<boolean> {+ private async applyLinkedFileCss(path: string): Promise<void> {const result = await updateThemeLibraryThemes((theme) => theme.linkedPath === path,(theme) => {@@ -486,7 +492,6 @@ class ThemeLibrary {},);this.replaceStoredThemes(result.themes);- return result.written;}private refreshLinkedThemes(): void {@@ -558,24 +563,58 @@ class ThemeLibrary {async deleteTheme(id: string): Promise<void> {await this.mutate(async () => {await deleteThemeLibraryTheme(id);- const nextEnabledThemeIds = this.enabledThemeIds.filter((themeId) => themeId !== id);- await setEnabledThemeIds(nextEnabledThemeIds);runInAction(() => {this.themes = this.themes.filter((theme) => theme.id !== id);- this.enabledThemeIds = nextEnabledThemeIds;});});}- async setThemeEnabled(id: string, enabled: boolean): Promise<void> {+ loadAccountEnabledIds(): void {+ this.accountEnabledIds = getAccountEnabledThemeIds();+ }++ async setThemeEnabled(id: string, enabled: boolean, target: ThemeTarget): Promise<void> {await this.mutate(async () => {+ const current = target === 'desktop' ? this.installationEnabledIds : this.accountEnabledIds;const next = enabled- ? [...this.enabledThemeIds.filter((themeId) => themeId !== id), id]- : this.enabledThemeIds.filter((themeId) => themeId !== id);- await setEnabledThemeIds(next);- runInAction(() => {- this.enabledThemeIds = next;+ ? [...current.filter((themeId) => themeId !== id), id]+ : current.filter((themeId) => themeId !== id);+ await this.writeEnabledIds(next, target);+ });+ }++ async moveEnabledTheme(id: string, offset: -1 | 1, target: ThemeTarget): Promise<void> {+ await this.mutate(async () => {+ const enabledIds = this.enabledIdsFor(target);+ const index = enabledIds.indexOf(id);+ const neighbor = index < 0 ? undefined : enabledIds[index + offset];+ if (neighbor === undefined) return;+ const current = target === 'desktop' ? this.installationEnabledIds : this.accountEnabledIds;+ const next = current.map((themeId) => {+ if (themeId === id) {+ return neighbor;+ }+ if (themeId === neighbor) {+ return id;+ }+ return themeId;});+ await this.writeEnabledIds(next, target);+ });+ }++ private async writeEnabledIds(next: Array<string>, target: ThemeTarget): Promise<void> {+ if (target === 'desktop') {+ await setEnabledThemeIds(next);+ } else {+ setAccountEnabledThemeIds(next);+ }+ runInAction(() => {+ if (target === 'desktop') {+ this.installationEnabledIds = next;+ } else {+ this.accountEnabledIds = next;+ }});}@@ -671,7 +710,7 @@ class ThemeLibrary {this.themes = [];this.assets = [];this.localFiles = [];- this.enabledThemeIds = [];+ this.installationEnabledIds = [];});});}diff --git a/fluxer_app/src/features/theme/utils/ThemeLibraryDb.ts b/fluxer_app/src/features/theme/utils/ThemeLibraryDb.tsindex a55dbc894..ff08d3687 100644--- a/fluxer_app/src/features/theme/utils/ThemeLibraryDb.ts+++ b/fluxer_app/src/features/theme/utils/ThemeLibraryDb.ts@@ -233,25 +233,18 @@ export async function updateThemeLibraryThemes(select: (theme: ThemeLibraryTheme) => boolean,update: (theme: ThemeLibraryTheme) => ThemeLibraryTheme | null,): Promise<{themes: Array<ThemeLibraryTheme>; written: boolean}> {- return await withReadwriteDb(THEMES_STORE, (store) => {- const result: {themes: Array<ThemeLibraryTheme>; written: boolean} = {themes: [], written: false};- const request = store.openCursor();- request.onsuccess = () => {- const cursor = request.result;- if (!cursor) return;- const stored: unknown = cursor.value;- if (isThemeLibraryTheme(stored) && select(stored)) {- const next = update(stored);- if (next) {- cursor.update(next);- result.written = true;- }- result.themes.push(next ?? stored);- }- cursor.continue();- };- return result;+ await ensureThemeLibraryMigrated();+ const result: {themes: Array<ThemeLibraryTheme>; written: boolean} = {themes: [], written: false};+ const stored = readDurableList(DURABLE_THEMES_KEY, isThemeLibraryTheme);+ const next = stored.map((theme) => {+ if (!select(theme)) return theme;+ const updated = update(theme);+ if (updated) result.written = true;+ result.themes.push(updated ?? theme);+ return updated ?? theme;});+ if (result.written) writeDurableList(DURABLE_THEMES_KEY, next);+ return result;}export async function deleteThemeLibraryTheme(id: string): Promise<void> {@@ -325,6 +318,15 @@ export async function setEnabledThemeIds(themeIds: ReadonlyArray<string>): PromiAppStorage.setItem(DURABLE_ENABLED_IDS_KEY, JSON.stringify([...themeIds]));}+export function getAccountEnabledThemeIds(): Array<string> {+ const raw = AppStorage.getItem(AppStorageKey.THEME_LIBRARY_ACCOUNT_ENABLED_IDS);+ return raw == null ? [] : readDurableStringArray(raw);+}++export function setAccountEnabledThemeIds(themeIds: ReadonlyArray<string>): void {+ AppStorage.setItem(AppStorageKey.THEME_LIBRARY_ACCOUNT_ENABLED_IDS, JSON.stringify([...themeIds]));+}+export async function clearThemeLibraryMeta(): Promise<void> {AppStorage.removeItem(DURABLE_ENABLED_IDS_KEY);}diff --git a/fluxer_app/src/features/theme/variables/ThemeVariableManifest.ts b/fluxer_app/src/features/theme/variables/ThemeVariableManifest.tsindex 990367506..dabb5cbe3 100644--- a/fluxer_app/src/features/theme/variables/ThemeVariableManifest.ts+++ b/fluxer_app/src/features/theme/variables/ThemeVariableManifest.ts@@ -1435,7 +1435,7 @@ export const THEME_VARIABLE_NAMES: ReadonlyArray<string> = ["--z-index-tooltip",];-export const THEME_STUDIO_DARK_DEFAULT_VARIABLE_VALUES: Readonly<Record<string, string>> = {+export const THEME_DARK_DEFAULT_VARIABLE_VALUES: Readonly<Record<string, string>> = {"--accent-danger": "hsl(0, calc(84% * var(--saturation-factor)), 60%)","--accent-info": "hsl(198, calc(92% * var(--saturation-factor)), 70%)","--accent-primary": "hsl(242, calc(70% * var(--saturation-factor)), 55%)",@@ -1787,7 +1787,7 @@ export const THEME_STUDIO_DARK_DEFAULT_VARIABLE_VALUES: Readonly<Record<string,"--message-unknown-warning-color": "#ff9933","--messages-bottom-clearance": "1.5rem","--mobile-bottom-nav-height": "3.75rem",- "--native-titlebar-height": "2rem",+ "--native-titlebar-height": "32px","--outline-frame-border-width": "0.0625rem","--outline-frame-radius-native": "clamp(0.5rem, 1.2vw, 0.875rem)","--panel-control-bg": "color-mix( in srgb, hsl(258, calc(10% * var(--saturation-factor)), 14.15%) 90%, hsl(258, calc(10% * var(--saturation-factor)), 2%) 10% )",@@ -1910,7 +1910,7 @@ export const THEME_STUDIO_DARK_DEFAULT_VARIABLE_VALUES: Readonly<Record<string,"--z-index-tooltip": "45000",};-export const THEME_STUDIO_LIGHT_DEFAULT_VARIABLE_VALUES: Readonly<Record<string, string>> = {+export const THEME_LIGHT_DEFAULT_VARIABLE_VALUES: Readonly<Record<string, string>> = {"--accent-danger": "hsl(359, calc(70% * var(--saturation-factor)), 50%)","--accent-info": "hsl(198, calc(92% * var(--saturation-factor)), 45%)","--accent-primary": "hsl(242, calc(70% * var(--saturation-factor)), 55%)",@@ -2262,7 +2262,7 @@ export const THEME_STUDIO_LIGHT_DEFAULT_VARIABLE_VALUES: Readonly<Record<string,"--message-unknown-warning-color": "#ff9933","--messages-bottom-clearance": "1.5rem","--mobile-bottom-nav-height": "3.75rem",- "--native-titlebar-height": "2rem",+ "--native-titlebar-height": "32px","--outline-frame-border-width": "0.0625rem","--outline-frame-radius-native": "clamp(0.5rem, 1.2vw, 0.875rem)","--panel-control-bg": "color-mix(in srgb, hsl(220, calc(10% * var(--saturation-factor)), 92.84%) 65%, hsl(0, 0%, 100%) 35%)",