Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(mobile): 设置里加入外观显示模式(跟随系统 / 浅色 / 深色)
kirozeng4bfaf35ea59b
diff --git a/apps/mobile/app/settings.tsx b/apps/mobile/app/settings.tsxindex 2ac4bf8a1c..51cde98e3e 100644--- a/apps/mobile/app/settings.tsx+++ b/apps/mobile/app/settings.tsx@@ -113,7 +113,7 @@ import { SheetModal } from '@/session/SheetModal';import { SheetSurface } from '@/session/SheetSurface';import { computeContextSheetSnapHeights, type ContextSheetSnap } from '@/session/contextSheetModel';import type { MobileChoiceOption } from '@/session/agentCapabilities';-import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';+import { THEME_PREFERENCES, useTheme, useThemedStyles, type ThemeColors } from '@/theme';import { fontWeight, iconSize, iconStroke, lineHeight, radius, spacing, typeScale } from '@/theme/tokens';type UpdatePhase = 'idle' | 'checking' | 'downloading' | 'uptodate' | 'error';@@ -131,7 +131,7 @@ const LANGUAGE_OPTIONS: readonly LocalePreference[] = [export default function SettingsScreen() {const styles = useThemedStyles(makeStyles);- const { colors } = useTheme();+ const { colors, preference: themePreference, setPreference: setThemePreference } = useTheme();const router = useRouter();const auth = useAuth();const { t } = useTranslation();@@ -188,6 +188,8 @@ export default function SettingsScreen() {const [debugExpanded, setDebugExpanded] = useState(false);const [languagePickerOpen, setLanguagePickerOpen] = useState(false);const [languagePickerSnap, setLanguagePickerSnap] = useState<ContextSheetSnap>('half');+ const [appearancePickerOpen, setAppearancePickerOpen] = useState(false);+ const [appearancePickerSnap, setAppearancePickerSnap] = useState<ContextSheetSnap>('half');const [updatePhase, setUpdatePhase] = useState<UpdatePhase>('idle');const [updateOutcome, setUpdateOutcome] = useState<ManualUpdateCheckOutcome | null>(null);const [pushEnabled, setPushEnabled] = useState(false);@@ -293,7 +295,7 @@ export default function SettingsScreen() {})),[t],);- const languagePickerHeights = useMemo(+ const choicePickerHeights = useMemo(() => computeContextSheetSnapHeights({safeAreaTopInset: safeAreaInsets.top,screenHeight: windowDimensions.height,@@ -310,6 +312,23 @@ export default function SettingsScreen() {setLocale(nextLocale);setLanguagePickerOpen(false);}, [setLocale]);+ const appearancePickerOptions = useMemo<readonly MobileChoiceOption[]>(+ () => THEME_PREFERENCES.map((option) => ({+ id: option,+ label: t(`settings.appearance.options.${option}`),+ })),+ [t],+ );+ const openAppearancePicker = useCallback(() => {+ setAppearancePickerSnap('half');+ setAppearancePickerOpen(true);+ }, []);+ const selectAppearance = useCallback((next: string) => {+ const nextPreference = THEME_PREFERENCES.find((option) => option === next);+ if (!nextPreference) return;+ setThemePreference(nextPreference);+ setAppearancePickerOpen(false);+ }, [setThemePreference]);useEffect(() => {if (!auth.isAuthenticated || !auth.deviceId) {@@ -1120,6 +1139,26 @@ export default function SettingsScreen() {]}</SettingsGroup>+ {/* 显示模式:默认跟随系统,手动选择浅色 / 深色即持久化 override(恢复跟随系统 = 清除 override) */}+ <SettingsGroup title={t('settings.appearance.title')}>+ <NativePullDownMenu+ actions={THEME_PREFERENCES.map((option) => ({+ id: option,+ state: option === themePreference ? 'on' : 'off',+ title: t(`settings.appearance.options.${option}`),+ }))}+ onAction={selectAppearance}+ >+ <ChoicePickerRow+ expanded={appearancePickerOpen}+ label={t('settings.appearance.modeLabel')}+ onPress={usesNativePullDownMenu() ? () => undefined : openAppearancePicker}+ testID="settings.appearance.picker"+ value={t(`settings.appearance.options.${themePreference}`)}+ />+ </NativePullDownMenu>+ </SettingsGroup>+{/* 显示语言:默认跟随系统,手动选择即持久化 override(恢复跟随系统 = 清除 override) */}<SettingsGroupfooter={t('settings.language.hint')}@@ -1133,7 +1172,7 @@ export default function SettingsScreen() {}))}onAction={selectLanguage}>- <LanguagePickerRow+ <ChoicePickerRowexpanded={languagePickerOpen}label={t('settings.language.title')}onPress={usesNativePullDownMenu() ? () => undefined : openLanguagePicker}@@ -1393,6 +1432,29 @@ export default function SettingsScreen() {) : null}</View></ScrollView>+ <SheetModal+ backdropTestID="settings.appearancePicker.backdrop"+ onBackdropPress={() => setAppearancePickerOpen(false)}+ onRequestClose={() => setAppearancePickerOpen(false)}+ visible={appearancePickerOpen}+ >+ <SheetSurface+ bottomInset={safeAreaInsets.bottom}+ heights={choicePickerHeights}+ onClose={() => setAppearancePickerOpen(false)}+ onSnapChange={setAppearancePickerSnap}+ snap={appearancePickerSnap}+ testID="settings.appearancePicker"+ title={t('settings.appearance.modeLabel')}+ >+ <MobileChoicePickerList+ activeId={themePreference}+ onSelect={selectAppearance}+ options={appearancePickerOptions}+ testID="settings.appearancePicker.option"+ />+ </SheetSurface>+ </SheetModal><SheetModalbackdropTestID="settings.languagePicker.backdrop"onBackdropPress={() => setLanguagePickerOpen(false)}@@ -1401,7 +1463,7 @@ export default function SettingsScreen() {><SheetSurfacebottomInset={safeAreaInsets.bottom}- heights={languagePickerHeights}+ heights={choicePickerHeights}onClose={() => setLanguagePickerOpen(false)}onSnapChange={setLanguagePickerSnap}snap={languagePickerSnap}@@ -1484,7 +1546,8 @@ function SettingsGroup({}/** 显示语言下拉入口:标签左、当前值右;选项在底部 sheet 中单选。 */-function LanguagePickerRow({+/** 设置项的单选入口行:iOS 由外层原生下拉菜单接管点击,其它平台打开选择面板。 */+function ChoicePickerRow({expanded,label,onPress,diff --git a/apps/mobile/src/__tests__/themePreferenceStore.test.ts b/apps/mobile/src/__tests__/themePreferenceStore.test.tsnew file mode 100644index 0000000000..fdcd58933b--- /dev/null+++ b/apps/mobile/src/__tests__/themePreferenceStore.test.ts@@ -0,0 +1,59 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const store = vi.hoisted(() => new Map<string, string>());++vi.mock('@react-native-async-storage/async-storage', () => ({+ default: {+ getItem: vi.fn(async (key: string) => store.get(key) ?? null),+ setItem: vi.fn(async (key: string, value: string) => {+ store.set(key, value);+ }),+ removeItem: vi.fn(async (key: string) => {+ store.delete(key);+ }),+ },+}));++import {+ __testing,+ readThemePreference,+ resolveThemeMode,+ saveThemePreference,+} from '@/theme/themePreferenceStore';++describe('themePreferenceStore', () => {+ beforeEach(() => {+ store.clear();+ vi.clearAllMocks();+ });++ it('未存储任何值时读出 system(跟随系统)', async () => {+ await expect(readThemePreference()).resolves.toBe('system');+ });++ it('保存浅色 / 深色后读出该模式', async () => {+ await saveThemePreference('dark');+ await expect(readThemePreference()).resolves.toBe('dark');+ expect(store.get(__testing.storageKey)).toBe('dark');+ });++ it('保存 system 即删除 override(默认 + override 模型)', async () => {+ await saveThemePreference('light');+ await saveThemePreference('system');+ expect(store.has(__testing.storageKey)).toBe(false);+ await expect(readThemePreference()).resolves.toBe('system');+ });++ it('存储里出现非法值时回退 system', async () => {+ store.set(__testing.storageKey, 'sepia');+ await expect(readThemePreference()).resolves.toBe('system');+ });++ it('有效模式 = override ?? 系统外观', () => {+ expect(resolveThemeMode('system', 'dark')).toBe('dark');+ expect(resolveThemeMode('system', 'light')).toBe('light');+ expect(resolveThemeMode('system', null)).toBe('light');+ expect(resolveThemeMode('light', 'dark')).toBe('light');+ expect(resolveThemeMode('dark', 'light')).toBe('dark');+ });+});diff --git a/apps/mobile/src/i18n/locales/en/settings.json b/apps/mobile/src/i18n/locales/en/settings.jsonindex abd4ca96a5..a81ce35dfa 100644--- a/apps/mobile/src/i18n/locales/en/settings.json+++ b/apps/mobile/src/i18n/locales/en/settings.json@@ -23,6 +23,15 @@"uploadSucceeded": "Uploaded. Code {{code}}."},"title": "Settings",+ "appearance": {+ "title": "Appearance",+ "modeLabel": "Appearance Mode",+ "options": {+ "system": "Auto (follow system)",+ "light": "Light",+ "dark": "Dark"+ }+ },"language": {"title": "Language","hint": "Affects the app UI only. Agent replies follow the agent's own language settings.",diff --git a/apps/mobile/src/i18n/locales/ja/settings.json b/apps/mobile/src/i18n/locales/ja/settings.jsonindex 8eafec3d8c..e979f36f81 100644--- a/apps/mobile/src/i18n/locales/ja/settings.json+++ b/apps/mobile/src/i18n/locales/ja/settings.json@@ -23,6 +23,15 @@"uploadSucceeded": "送信しました。番号 {{code}}。"},"title": "設定",+ "appearance": {+ "title": "外観",+ "modeLabel": "表示モード",+ "options": {+ "system": "自動 (システムに従う)",+ "light": "ライト",+ "dark": "ダーク"+ }+ },"language": {"title": "言語","hint": "アプリの UI のみに影響します。Agent の応答言語は Agent 側の設定に従います。",diff --git a/apps/mobile/src/i18n/locales/ko/settings.json b/apps/mobile/src/i18n/locales/ko/settings.jsonindex 3efb5df8de..8726f48e65 100644--- a/apps/mobile/src/i18n/locales/ko/settings.json+++ b/apps/mobile/src/i18n/locales/ko/settings.json@@ -23,6 +23,15 @@"uploadSucceeded": "업로드했습니다. 번호 {{code}}."},"title": "설정",+ "appearance": {+ "title": "외관",+ "modeLabel": "표시 모드",+ "options": {+ "system": "자동 (시스템 따르기)",+ "light": "라이트",+ "dark": "다크"+ }+ },"language": {"title": "언어","hint": "앱 UI에만 영향을 줍니다. Agent 응답 언어는 Agent 자체 설정에 따릅니다.",diff --git a/apps/mobile/src/i18n/locales/zh-CN/settings.json b/apps/mobile/src/i18n/locales/zh-CN/settings.jsonindex acae8db1dc..f7ab105374 100644--- a/apps/mobile/src/i18n/locales/zh-CN/settings.json+++ b/apps/mobile/src/i18n/locales/zh-CN/settings.json@@ -23,6 +23,15 @@"uploadSucceeded": "上传成功,编号 {{code}}。"},"title": "设置",+ "appearance": {+ "title": "外观",+ "modeLabel": "显示模式",+ "options": {+ "system": "跟随系统",+ "light": "浅色",+ "dark": "深色"+ }+ },"language": {"title": "语言","hint": "仅影响应用界面。Agent 回复语言由 Agent 自身决定。",diff --git a/apps/mobile/src/i18n/locales/zh-TW/settings.json b/apps/mobile/src/i18n/locales/zh-TW/settings.jsonindex 0e1381ddaa..72376c0b1a 100644--- a/apps/mobile/src/i18n/locales/zh-TW/settings.json+++ b/apps/mobile/src/i18n/locales/zh-TW/settings.json@@ -23,6 +23,15 @@"uploadSucceeded": "上傳成功,編號 {{code}}。"},"title": "設定",+ "appearance": {+ "title": "外觀",+ "modeLabel": "顯示模式",+ "options": {+ "system": "跟隨系統",+ "light": "淺色",+ "dark": "深色"+ }+ },"language": {"title": "語言","hint": "僅影響應用介面。Agent 回覆語言由 Agent 自身決定。",diff --git a/apps/mobile/src/theme/ThemeProvider.tsx b/apps/mobile/src/theme/ThemeProvider.tsxindex 3a7662f9d3..f84fd0ac33 100644--- a/apps/mobile/src/theme/ThemeProvider.tsx+++ b/apps/mobile/src/theme/ThemeProvider.tsx@@ -1,21 +1,74 @@-import { createContext, useContext, useMemo, type ReactNode } from 'react';-import { StyleSheet, useColorScheme } from 'react-native';+import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';+import { Appearance, StyleSheet, useColorScheme } from 'react-native';import { palettes, type ThemeColors, type ThemeMode } from './tokens';+import {+ readThemePreference,+ resolveThemeMode,+ saveThemePreference,+ type ThemePreference,+} from './themePreferenceStore';interface ThemeValue {mode: ThemeMode;colors: ThemeColors;+ /** 用户的显示模式偏好(含 'system');子树覆盖(ThemeOverrideProvider)不改变它。 */+ preference: ThemePreference;+ /** 设置显示模式偏好 —— 持久化 override、同步原生外观。 */+ setPreference: (next: ThemePreference) => void;}-const ThemeContext = createContext<ThemeValue>({ mode: 'light', colors: palettes.light });+const ThemeContext = createContext<ThemeValue>({+ mode: 'light',+ colors: palettes.light,+ preference: 'system',+ setPreference: () => undefined,+});/**- * 跟随系统 light / dark,向下提供当前主题色板。挂在 SafeAreaProvider 内、其它业务 Provider 之上。+ * 让系统绘制的部分(原生菜单 / 面板 / 键盘 / 状态栏 / 玻璃材质)与 Cindy 色板同一模式:+ * 'system' 还原为 unspecified,浅色 / 深色强制对应外观。只改 JS 调用,不动原生配置。+ * 强制期间 useColorScheme 读到的是被强制的外观;还原后下一次渲染即读回系统值。+ */+function applyNativeScheme(preference: ThemePreference): void {+ Appearance.setColorScheme(preference === 'system' ? 'unspecified' : preference);+}++/**+ * 按显示模式偏好(默认跟随系统)向下提供当前主题色板。挂在 SafeAreaProvider 内、其它业务+ * Provider 之上。偏好读出是异步的:先按系统外观渲染首帧,挂载后读出 override 再切换;+ * 启动期有 StartupSplashOverlay 顶着,不产生可见闪变。*/export function ThemeProvider({ children }: { children: ReactNode }) {- const scheme = useColorScheme();- const mode: ThemeMode = scheme === 'dark' ? 'dark' : 'light';- const value = useMemo<ThemeValue>(() => ({ mode, colors: palettes[mode] }), [mode]);+ const systemScheme = useColorScheme();+ const [preference, setPreferenceState] = useState<ThemePreference>('system');+ // 用户已手动选择过时置位:挂载期的异步读回不得覆盖更晚的手动选择。+ const userChoseRef = useRef(false);++ useEffect(() => {+ let cancelled = false;+ void readThemePreference().then((stored) => {+ if (cancelled || userChoseRef.current || stored === 'system') return;+ applyNativeScheme(stored);+ setPreferenceState(stored);+ });+ return () => {+ cancelled = true;+ };+ }, []);++ const setPreference = useCallback((next: ThemePreference) => {+ userChoseRef.current = true;+ applyNativeScheme(next);+ setPreferenceState(next);+ // 持久化失败不影响当前会话切换('system' = 删除 override)。+ void saveThemePreference(next);+ }, []);++ const mode = resolveThemeMode(preference, systemScheme);+ const value = useMemo<ThemeValue>(+ () => ({ mode, colors: palettes[mode], preference, setPreference }),+ [mode, preference, setPreference],+ );return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;}@@ -39,7 +92,7 @@ export function ThemeOverrideProvider({}) {const parent = useContext(ThemeContext);const value = useMemo<ThemeValue>(- () => (mode == null ? parent : { mode, colors: palettes[mode] }),+ () => (mode == null ? parent : { ...parent, mode, colors: palettes[mode] }),[mode, parent],);return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;diff --git a/apps/mobile/src/theme/index.ts b/apps/mobile/src/theme/index.tsindex 1ee6b2cb50..20b6f75fe8 100644--- a/apps/mobile/src/theme/index.ts+++ b/apps/mobile/src/theme/index.ts@@ -22,3 +22,4 @@ export {} from './tokens';export { monoFont } from './monoFont';export { ThemeOverrideProvider, ThemeProvider, useTheme, useThemedStyles } from './ThemeProvider';+export { THEME_PREFERENCES, type ThemePreference } from './themePreferenceStore';diff --git a/apps/mobile/src/theme/themePreferenceStore.ts b/apps/mobile/src/theme/themePreferenceStore.tsnew file mode 100644index 0000000000..e4407a274f--- /dev/null+++ b/apps/mobile/src/theme/themePreferenceStore.ts@@ -0,0 +1,47 @@+/**+ * 显示模式偏好存储(AsyncStorage,版本化 key)。+ *+ * 遵循「默认 + override」模型(docs/dev-rules/configuration-and-overrides.md),与+ * 显示语言偏好同构:只持久化用户显式选择的「浅色 / 深色」;「跟随系统」是没有+ * override 这个状态本身——恢复跟随系统 = 删除存储项。+ */++import AsyncStorage from '@react-native-async-storage/async-storage';++import type { ThemeMode } from './tokens';++export type ThemePreference = 'system' | ThemeMode;++export const THEME_PREFERENCES: readonly ThemePreference[] = ['system', 'light', 'dark'];++const STORAGE_KEY = 'cindy.mobile.theme-preference.v1';++function isThemeOverride(value: unknown): value is ThemeMode {+ return value === 'light' || value === 'dark';+}++/** 有效模式 = 用户 override ?? 系统外观(系统未报告时按浅色)。 */+export function resolveThemeMode(+ preference: ThemePreference,+ systemScheme: string | null | undefined,+): ThemeMode {+ if (preference !== 'system') return preference;+ return systemScheme === 'dark' ? 'dark' : 'light';+}++export async function readThemePreference(): Promise<ThemePreference> {+ const raw = await AsyncStorage.getItem(STORAGE_KEY).catch(() => null);+ return isThemeOverride(raw) ? raw : 'system';+}++export async function saveThemePreference(preference: ThemePreference): Promise<void> {+ if (preference === 'system') {+ await AsyncStorage.removeItem(STORAGE_KEY).catch(() => undefined);+ return;+ }+ await AsyncStorage.setItem(STORAGE_KEY, preference).catch(() => undefined);+}++export const __testing = {+ storageKey: STORAGE_KEY,+};