Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 22 additions & 23 deletions packages/web-ui/src/contexts/SettingsProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import {useCallback, useEffect, useRef, useState, type ReactNode} from 'react';
import {useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode} from 'react';
import {useTranslation} from 'react-i18next';
import {loadStartupConfig} from '@/utils/startupConfig';
import {detectAiDefaults} from '@/utils/aiDefaults';
import {SettingsContext, DEFAULT_SETTINGS, type Settings} from './SettingsContext';
import {applyResultFontToDocument, stripSessionFields, applyFontToDocument} from '@/utils/settings';
import {
applyResultFontToDocument,
stripSessionFields,
applyFontToDocument,
followsThemeFont,
getFontCSS,
} from '@/utils/settings';
import {useTabularisClient} from '@/hooks/useTabularisClient';
import {resolveAutoLanguage} from '@/i18n/language';
import {useTheme} from '@/hooks/useTheme';

const LANGUAGE_APPLICATION_TIMEOUT_MS = 3000;

Expand Down Expand Up @@ -41,6 +48,8 @@ function matchesAppliedLanguage(
export const SettingsProvider = ({children}: {children: ReactNode}) => {
const {i18n} = useTranslation();
const client = useTabularisClient();
const {currentTheme, isLoading: isThemeLoading} = useTheme();
const themeFontFamily = currentTheme.typography.fontFamily.base;
const [settings, setSettings] = useState<Settings>(DEFAULT_SETTINGS);
const [isLoading, setIsLoading] = useState(true);
const [languageState, setLanguageState] = useState<LanguageState>({
Expand Down Expand Up @@ -191,12 +200,6 @@ export const SettingsProvider = ({children}: {children: ReactNode}) => {
}
}

// IMMEDIATELY apply font settings from backend config BEFORE setting state
// This prevents flash if localStorage cache was stale. The default
// choice leaves the base font to the theme.
applyFontToDocument(finalSettings.fontFamily, finalSettings.fontSize || 14);
applyResultFontToDocument(finalSettings.resultFontFamily);

const languageAlreadyApplied = isLanguageApplied(finalSettings.language);
if (languageAlreadyApplied) {
appliedLanguageRef.current = finalSettings.language;
Expand Down Expand Up @@ -329,11 +332,19 @@ export const SettingsProvider = ({children}: {children: ReactNode}) => {
]);

// Apply font family
useLayoutEffect(() => {
const usesThemeFont = followsThemeFont(settings.fontFamily);
if (isLoading || (usesThemeFont && isThemeLoading)) return;
const resolvedFontFamily = usesThemeFont
? themeFontFamily
: getFontCSS(settings.fontFamily);
applyFontToDocument(resolvedFontFamily, settings.fontSize);
if (usesThemeFont) document.body.style.removeProperty('font-family');
}, [isLoading, isThemeLoading, settings.fontFamily, settings.fontSize, themeFontFamily]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Explicit font can be lost from --font-base after a theme change or preview

applyThemeToCSS unconditionally writes --font-base (themeUtils.ts:131). It runs from ThemeProvider's passive useEffect, which fires after this layout effect. With an explicit font such as Hack, selecting or previewing a theme overwrites --font-base with the theme font while body.style.fontFamily keeps the explicit one. This effect then does not re-run, because themeFontFamily is the only theme-derived dependency and it is not guaranteed to change between two themes that share a font. --font-base consumers (for example result cells using inherit) can silently diverge from the chosen font.

The PR's test only covers the System path across theme changes, not an explicit font across theme changes. Consider also depending on the current theme identity (not just its font string), or re-applying the explicit font after theme application, and add a test for that case.


// Cache for next startup
useEffect(() => {
if (isLoading) return;
applyFontToDocument(settings.fontFamily, settings.fontSize);

// Cache for next startup
try {
localStorage.setItem(
'tabularis_font_cache',
Expand All @@ -353,18 +364,6 @@ export const SettingsProvider = ({children}: {children: ReactNode}) => {
applyResultFontToDocument(settings.resultFontFamily);
}, [isLoading, settings.resultFontFamily]);

// Apply font size
useEffect(() => {
if (isLoading) return;
const size = settings.fontSize || 14;

// Apply to CSS variable
document.documentElement.style.setProperty('--font-size-base', `${size}px`);

// ALSO apply directly to body as fallback
document.body.style.fontSize = `${size}px`;
}, [isLoading, settings.fontSize]);

const updateSetting = <K extends keyof Settings>(
key: K,
valueOrUpdater: Settings[K] | ((prev: Settings[K]) => Settings[K]),
Expand Down
18 changes: 4 additions & 14 deletions packages/web-ui/src/utils/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,25 +183,15 @@ export function followsThemeFont(fontFamily: string | undefined): boolean {
return !fontFamily || fontFamily === DEFAULT_FONT_FAMILY;
}

/**
* Applies the UI font. With the default choice the theme owns `--font-base`
* (set by applyThemeToCSS) and the body inherits it from `:root`; an explicit
* font overrides the theme on both.
*/
export function applyFontToDocument(fontFamily: string, fontSize: number): void {
if (typeof document === 'undefined') return;

const root = document.documentElement;
const size = fontSize || DEFAULT_FONT_SIZE;
document.documentElement.style.setProperty('--font-size-base', `${size}px`);
root.style.setProperty('--font-base', fontFamily);
root.style.setProperty('--font-size-base', `${size}px`);
document.body.style.fontFamily = fontFamily;
document.body.style.fontSize = `${size}px`;

if (followsThemeFont(fontFamily)) {
document.body.style.removeProperty('font-family');
return;
}
const cssFont = getFontCSS(fontFamily);
document.documentElement.style.setProperty('--font-base', cssFont);
document.body.style.fontFamily = cssFont;
}

export function getLanguageForI18n(
Expand Down
18 changes: 17 additions & 1 deletion packages/web-ui/tests/contexts/SettingsProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ import {invoke} from '@tauri-apps/api/core';
import {listen, type EventCallback} from '@tauri-apps/api/event';
import React from 'react';
import type {Settings} from '@/contexts/SettingsContext';
import {themeRegistry} from '@/themes/themeRegistry';

vi.mock('@/hooks/useTheme', () => ({
useTheme: () => ({currentTheme: themeRegistry.getDefault(), isLoading: false}),
}));

vi.mock('@tauri-apps/api/core');
vi.mock('@tauri-apps/api/event', () => ({
Expand Down Expand Up @@ -537,6 +542,9 @@ describe('SettingsProvider', () => {
fontSize: 18,
});
}
if (cmd === 'save_config') {
return Promise.resolve(undefined);
}
if (cmd === 'check_ai_key') {
return Promise.resolve(false);
}
Expand All @@ -549,7 +557,7 @@ describe('SettingsProvider', () => {
const wrapper = ({children}: {children: React.ReactNode}) =>
React.createElement(SettingsProvider, null, children);

renderHook(() => useSettings(), {wrapper});
const {result} = renderHook(() => useSettings(), {wrapper});

await waitFor(() => {
const fontFamily = document.documentElement.style.getPropertyValue('--font-base');
Expand All @@ -558,6 +566,14 @@ describe('SettingsProvider', () => {
expect(fontFamily).toContain('JetBrains Mono');
expect(fontSize).toBe('18px');
});

await act(async () => {
await result.current.updateSetting('fontFamily', 'System');
});
expect(document.documentElement.style.getPropertyValue('--font-base')).toBe(
themeRegistry.getDefault().typography.fontFamily.base,
);
expect(document.body.style.fontFamily).toBe('');
});

it('should cache font settings to localStorage', async () => {
Expand Down
96 changes: 95 additions & 1 deletion packages/web-ui/tests/contexts/ThemeProvider.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {beforeEach, describe, expect, it, vi} from 'vitest';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {tauriBackedClient} from '../support/tauriBackedHooks';
import {registerActivePlatformCapabilities} from '@/platform/activeCapabilities';
import {TauriPlatformCapabilities} from '@/platform/tauriCapabilities';
Expand All @@ -7,6 +7,9 @@ import React from 'react';
import {invoke} from '@tauri-apps/api/core';
import {listen} from '@tauri-apps/api/event';
import {ThemeProvider} from '@/contexts/ThemeProvider';
import {SettingsProvider} from '@/contexts/SettingsProvider';
import {useSettings} from '@/hooks/useSettings';
import {FONT_MAP} from '@/utils/settings';
import {useTheme} from '@/hooks/useTheme';
import {themeRegistry} from '@/themes/themeRegistry';
import {applyThemeToCSS} from '@/themes/themeUtils';
Expand Down Expand Up @@ -818,3 +821,94 @@ describe('native and portal system theme compatibility', () => {
expect(result.current.settings.lightThemeId).toBe('tabularis-light');
});
});

describe('ThemeProvider interface font integration', () => {
const fontWrapper = ({children}: {children: React.ReactNode}) => (
<React.StrictMode>
<ThemeProvider>
<SettingsProvider>{children}</SettingsProvider>
</ThemeProvider>
</React.StrictMode>
);

beforeEach(async () => {
const actual =
await vi.importActual<typeof import('@/themes/themeUtils')>('@/themes/themeUtils');
vi.mocked(applyThemeToCSS).mockImplementation(actual.applyThemeToCSS);
document.documentElement.style.cssText = '';
document.body.style.cssText = '';
const entry = legacy('custom-font');
const theme = JSON.parse(entry.source) as Theme;
theme.typography.fontFamily.base = 'Georgia, serif';
personal = [{...entry, source: JSON.stringify(theme)}];
config = {theme: entry.id, fontFamily: 'System', language: 'en'};
});

afterEach(() => {
document.documentElement.style.cssText = '';
document.body.style.cssText = '';
});

it('restores System and follows theme selections, previews and cancellation', async () => {
const {result} = renderHook(() => ({theme: useTheme(), settings: useSettings()}), {
wrapper: fontWrapper,
});
await waitFor(() => {
expect(result.current.theme.isLoading).toBe(false);
expect(result.current.settings.isLoading).toBe(false);
});
expect(document.documentElement.style.getPropertyValue('--font-base')).toBe(
'Georgia, serif',
);
expect(document.body.style.fontFamily).toBe('');

await act(async () => {
await result.current.settings.updateSetting('fontFamily', 'Hack');
});
expect(document.documentElement.style.getPropertyValue('--font-base')).toBe(FONT_MAP.Hack);
await act(async () => {
await result.current.settings.updateSetting('fontFamily', 'System');
});
expect(document.documentElement.style.getPropertyValue('--font-base')).toBe(
'Georgia, serif',
);
expect(document.body.style.fontFamily).toBe('');

await act(async () => {
await result.current.theme.setTheme('tabularis-light');
});
const lightFont = themeRegistry.getPreset('tabularis-light')!.typography.fontFamily.base;
expect(document.documentElement.style.getPropertyValue('--font-base')).toBe(lightFont);
act(() => result.current.theme.previewTheme('custom-font'));
expect(document.documentElement.style.getPropertyValue('--font-base')).toBe(
'Georgia, serif',
);
act(() => result.current.theme.cancelPreview());
expect(document.documentElement.style.getPropertyValue('--font-base')).toBe(lightFont);
expect(document.body.style.fontFamily).toBe('');
});

it('does not apply the fallback font while the saved theme is still loading', async () => {
const catalog = deferred<NativeThemeCatalog>();
const native = vi.mocked(invoke).getMockImplementation()!;
vi.mocked(invoke).mockImplementation((command, args) =>
command === 'get_theme_catalog' ? catalog.promise : native(command, args),
);
const {result} = renderHook(() => ({theme: useTheme(), settings: useSettings()}), {
wrapper: fontWrapper,
});
await waitFor(() => expect(result.current.settings.isLoading).toBe(false));
expect(result.current.theme.isLoading).toBe(true);
expect(document.documentElement.style.getPropertyValue('--font-base')).toBe('');
expect(document.body.style.fontFamily).toBe('');

await act(async () => {
catalog.resolve(snapshot());
});
await waitFor(() => expect(result.current.theme.isLoading).toBe(false));
expect(document.documentElement.style.getPropertyValue('--font-base')).toBe(
'Georgia, serif',
);
expect(document.body.style.fontFamily).toBe('');
});
});
18 changes: 10 additions & 8 deletions packages/web-ui/tests/utils/settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,7 @@ describe('settings', () => {
});

it('should apply font CSS variables to document', () => {
applyFontToDocument('Roboto', 16);
applyFontToDocument(FONT_MAP['Roboto'], 16);

expect(document.documentElement.style.setProperty).toHaveBeenCalledWith(
'--font-base',
Expand All @@ -505,20 +505,22 @@ describe('settings', () => {
});

it('should apply an explicit font directly to body', () => {
applyFontToDocument('Roboto', 14);
applyFontToDocument(FONT_MAP['Roboto'], 14);

expect(document.body.style.fontFamily).toBe(FONT_MAP['Roboto']);
expect(document.body.style.fontSize).toBe('14px');
});

it('should leave the base font to the theme for the default choice', () => {
applyFontToDocument('System', 14);
it('should replace the previous font with a resolved theme font', () => {
const themeFont = 'Theme UI, sans-serif';
applyFontToDocument(FONT_MAP.Hack, 14);
applyFontToDocument(themeFont, 14);

expect(document.documentElement.style.setProperty).not.toHaveBeenCalledWith(
expect(document.documentElement.style.setProperty).toHaveBeenCalledWith(
'--font-base',
expect.anything(),
themeFont,
);
expect(document.body.style.removeProperty).toHaveBeenCalledWith('font-family');
expect(document.body.style.fontFamily).toBe(themeFont);
expect(document.body.style.fontSize).toBe('14px');
});

Expand All @@ -529,7 +531,7 @@ describe('settings', () => {
});

// Should not throw
expect(() => applyFontToDocument('System', 14)).not.toThrow();
expect(() => applyFontToDocument(FONT_MAP['System'], 14)).not.toThrow();
});
});

Expand Down