-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathApp.tsx
More file actions
268 lines (242 loc) · 9.98 KB
/
App.tsx
File metadata and controls
268 lines (242 loc) · 9.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import { useEffect, useRef, useCallback } from 'react';
import { ConfigProvider, App as AntdApp, Layout, theme } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import { useTranslation } from 'react-i18next';
import { Sidebar } from '@/components/layout/Sidebar';
import { TitleBar } from '@/components/layout/TitleBar';
import { ContentArea } from '@/components/layout/ContentArea';
import CommandPalette from '@/components/layout/CommandPalette';
import { GlobalCopyMenu } from '@/components/layout/GlobalCopyMenu';
import { useCommandPalette } from '@/hooks/useCommandPalette';
import { useUIStore, useSettingsStore, useConversationStore } from '@/stores';
import { useKeyboardShortcuts } from '@/hooks/useKeyboardShortcuts';
import { useGlobalShortcutManager } from '@/hooks/useGlobalShortcutManager';
import { useResolvedDarkMode } from '@/hooks/useResolvedDarkMode';
import { useGlobalOverlayScrollbars } from '@/hooks/useGlobalOverlayScrollbars';
import { useUpdateChecker } from '@/hooks/useUpdateChecker';
import { useProviderDeepLink } from '@/hooks/useProviderDeepLink';
import { useShadcnTheme } from '@/theme/shadcnTheme';
import { isTauri, invoke, listen } from '@/lib/invoke';
import { preloadChatRenderers } from '@/lib/preloadChatRenderers';
import { enableD2, setDefaultI18nMap } from 'markstream-react';
import './i18n';
const { Sider, Content } = Layout;
const { useToken } = theme;
/** Show the main window (it starts hidden to avoid white flash). */
async function showWindow() {
try {
const { getCurrentWebviewWindow } = await import('@tauri-apps/api/webviewWindow');
const window = getCurrentWebviewWindow();
await window.show();
await window.setFocus();
} catch (e) {
console.warn('Failed to show window:', e);
}
}
function AppInner() {
const { token } = useToken();
const { t } = useTranslation();
const { modal, message } = AntdApp.useApp();
const activePage = useUIStore((s) => s.activePage);
const { open: cmdOpen, setOpen: setCmdOpen } = useCommandPalette();
const isInSettings = activePage === 'settings';
useProviderDeepLink({ modal, message });
// Handle app close confirmation from backend
const handleCloseRequested = useCallback(() => {
modal.confirm({
title: t('desktop.closeConfirmTitle'),
content: t('desktop.closeConfirmContent'),
okText: t('desktop.closeConfirmOk'),
cancelText: t('desktop.closeConfirmCancel'),
okButtonProps: { danger: true },
onOk: () => invoke('force_quit'),
});
}, [modal, t]);
useEffect(() => {
if (!isTauri()) return;
const unlisten = listen('app-close-requested', handleCloseRequested);
return () => { unlisten.then((fn) => fn()); };
}, [handleCloseRequested]);
// Sync Ant Design tokens to CSS custom properties for global usage
useEffect(() => {
const root = document.documentElement;
root.style.setProperty('--border-color', token.colorBorderSecondary);
root.style.setProperty('--color-bg-container', token.colorBgContainer);
root.style.setProperty('--color-bg-elevated', token.colorBgElevated);
root.style.setProperty('--color-text', token.colorText);
root.style.setProperty('--color-text-secondary', token.colorTextSecondary);
root.style.setProperty('--color-primary', token.colorPrimary);
root.style.setProperty('--color-fill-alter', token.colorFillAlter);
// Markdown renderer (markstream-react) CSS variables
root.style.setProperty('--table-border', token.colorBorderSecondary);
root.style.setProperty('--hr-border-color', token.colorBorderSecondary);
root.style.setProperty('--blockquote-border-color', token.colorBorderSecondary);
}, [token]);
// Global stream event listeners — persist across page navigation
const startStreamListening = useConversationStore((s) => s.startStreamListening);
const stopStreamListening = useConversationStore((s) => s.stopStreamListening);
useEffect(() => {
startStreamListening();
return () => stopStreamListening();
}, [startStreamListening, stopStreamListening]);
// Auto-check for updates on startup and periodically
const { checkForUpdate } = useUpdateChecker();
const updateCheckInterval = useSettingsStore((s) => s.settings.update_check_interval ?? 60);
const updateIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
useEffect(() => {
if (!isTauri()) return;
// Initial check after 3s delay
const timer = setTimeout(() => checkForUpdate({ silent: true }), 3000);
return () => clearTimeout(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
if (!isTauri() || !updateCheckInterval) return;
if (updateIntervalRef.current) clearInterval(updateIntervalRef.current);
const intervalMs = Math.max(updateCheckInterval, 1) * 60 * 1000;
updateIntervalRef.current = setInterval(() => checkForUpdate({ silent: true }), intervalMs);
return () => {
if (updateIntervalRef.current) clearInterval(updateIntervalRef.current);
};
}, [updateCheckInterval, checkForUpdate]);
return (
<div className="flex flex-col h-screen" style={{ backgroundColor: token.colorBgContainer }}>
<TitleBar />
<CommandPalette open={cmdOpen} onClose={() => setCmdOpen(false)} />
<GlobalCopyMenu />
<Layout className="flex-1 overflow-hidden" style={{ backgroundColor: 'transparent' }}>
{!isInSettings && (
<Sider
width={48}
style={{
backgroundColor: 'transparent',
borderRight: '1px solid var(--border-color)',
}}
>
<Sidebar />
</Sider>
)}
<Content className="overflow-hidden">
<ContentArea activePage={activePage} />
</Content>
</Layout>
</div>
);
}
function AppRoot() {
const { i18n } = useTranslation();
const themeMode = useSettingsStore((s) => s.settings.theme_mode);
const primaryColor = useSettingsStore((s) => s.settings.primary_color);
const fontSize = useSettingsStore((s) => s.settings.font_size);
const fontWeight = useSettingsStore((s) => s.settings.font_weight);
const fontFamily = useSettingsStore((s) => s.settings.font_family);
const codeFontFamily = useSettingsStore((s) => s.settings.code_font_family);
const borderRadius = useSettingsStore((s) => s.settings.border_radius);
const language = useSettingsStore((s) => s.settings.language);
const isDark = useResolvedDarkMode(themeMode);
useEffect(() => {
document.documentElement.dataset.theme = isDark ? 'dark' : 'light';
}, [isDark]);
useEffect(() => {
enableD2(() => import('@terrastruct/d2'));
void preloadChatRenderers();
}, []);
useKeyboardShortcuts();
useGlobalShortcutManager();
useGlobalOverlayScrollbars();
// Load persisted settings from backend on startup, then apply native settings
useEffect(() => {
const init = async () => {
try {
await useSettingsStore.getState().fetchSettings();
} catch (e) {
console.warn('Failed to fetch settings:', e);
}
if (!isTauri()) return;
const settings = useSettingsStore.getState().settings;
// Apply native window settings
try {
await invoke('apply_startup_settings', {
alwaysOnTop: settings.always_on_top ?? false,
closeToTray: settings.minimize_to_tray ?? false,
releaseWebviewOnTray: settings.release_webview_on_tray ?? false,
});
} catch (e) {
console.warn('Failed to apply native settings:', e);
}
// Autostart
try {
const { enable, disable } = await import('@tauri-apps/plugin-autostart');
if (settings.auto_start) {
await enable();
} else {
await disable();
}
} catch (e) {
console.warn('Failed to set autostart:', e);
}
// Show window after initialization (window starts hidden to avoid white flash)
await showWindow();
};
init();
}, []);
// Sync i18n language with settings store
useEffect(() => {
if (i18n.language !== language) {
i18n.changeLanguage(language);
}
}, [i18n, language]);
useEffect(() => {
const t = i18n.getFixedT(i18n.language);
setDefaultI18nMap({
'common.close': t('common.close'),
'common.collapse': t('common.collapse'),
'common.copied': t('common.copied'),
'common.copy': t('common.copy'),
'common.decrease': t('common.decrease'),
'common.expand': t('common.expand'),
'common.export': t('common.export'),
'common.increase': t('common.increase'),
'common.minimize': t('common.minimize'),
'common.open': t('common.open'),
'common.preview': t('common.preview'),
'common.reset': t('common.reset'),
'common.resetZoom': t('common.resetZoom'),
'common.source': t('common.source'),
'common.zoomIn': t('common.zoomIn'),
'common.zoomOut': t('common.zoomOut'),
'image.loadError': t('image.loadError'),
'image.loading': t('image.loading'),
});
}, [i18n, i18n.language]);
// Sync font settings to CSS custom properties
useEffect(() => {
const root = document.documentElement;
root.style.setProperty('--font-weight', String(fontWeight));
if (fontFamily) {
root.style.setProperty('--font-family', fontFamily);
document.body.style.fontFamily = fontFamily;
} else {
root.style.removeProperty('--font-family');
document.body.style.removeProperty('font-family');
}
if (codeFontFamily) {
root.style.setProperty('--code-font-family', codeFontFamily);
} else {
root.style.removeProperty('--code-font-family');
}
}, [fontWeight, fontFamily, codeFontFamily]);
const themeConfig = useShadcnTheme(isDark, primaryColor, fontSize, borderRadius, fontFamily || undefined, codeFontFamily || undefined);
return (
<ConfigProvider
locale={i18n.language === 'zh-CN' ? zhCN : undefined}
theme={themeConfig}
modal={{ centered: true, styles: { mask: { backdropFilter: 'blur(4px)' } } }}
>
<AntdApp>
<AppInner />
</AntdApp>
</ConfigProvider>
);
}
export default AppRoot;