App.tsx

4.4 KB v1.0
// 应用根组件:登录态、设置持久化、页面切换
import { useCallback, useEffect, useRef, useState } from 'react';
import { api } from './api';
import { I18nProvider } from './i18n';
import { Login } from './pages/Login';
import { MailPage } from './pages/Mail';
import { SettingsPage } from './pages/Settings';
import { applyAppearance, FALLBACK_SETTINGS } from './theme';
import { deepMerge } from './utils';
import type { AppSettings, SettingsSection, User } from './types';
import { Icon } from './components/Icon';
import { Spinner } from './components/ui';

type View = 'mail' | 'settings';

export default function App() {
  const [loading, setLoading] = useState(true);
  const [user, setUser] = useState<User | null>(null);
  const [settings, setSettings] = useState<AppSettings | null>(null);
  const [view, setView] = useState<View>('mail');
  const [settingsSection, setSettingsSection] = useState<SettingsSection | undefined>(undefined);

  const pendingRef = useRef<Record<string, unknown>>({});
  const timerRef = useRef<number | null>(null);
  const inflightRef = useRef<Promise<AppSettings | null> | null>(null);

  useEffect(() => {
    api.auth
      .me()
      .then((result) => {
        setUser(result.user);
        setSettings(result.settings);
        applyAppearance(result.settings.appearance);
      })
      .catch(() => {
        applyAppearance(FALLBACK_SETTINGS.appearance);
      })
      .finally(() => setLoading(false));
  }, []);

  /** 立即把待保存的设置发送到服务端 */
  const flushSettings = useCallback(async () => {
    if (timerRef.current) {
      window.clearTimeout(timerRef.current);
      timerRef.current = null;
    }
    const patch = pendingRef.current;
    pendingRef.current = {};
    if (!patch || Object.keys(patch).length === 0) {
      if (inflightRef.current) await inflightRef.current.catch(() => null);
      return;
    }
    const promise = api.settings
      .save(patch)
      .then((saved) => {
        setSettings(saved);
        return saved;
      })
      .catch(async (error) => {
        const fresh = await api.settings.get().catch(() => null);
        if (fresh) setSettings(fresh);
        throw error;
      })
      .finally(() => {
        inflightRef.current = null;
      });
    inflightRef.current = promise;
    await promise;
  }, []);

  /** 乐观更新设置,并在 350ms 后批量保存 */
  const updateSettings = useCallback(
    (patch: unknown) => {
      setSettings((prev) => {
        if (!prev) return prev;
        const next = deepMerge(prev, patch);
        applyAppearance(next.appearance);
        return next;
      });
      pendingRef.current = deepMerge(pendingRef.current, patch);
      if (timerRef.current) window.clearTimeout(timerRef.current);
      timerRef.current = window.setTimeout(() => {
        void flushSettings().catch(() => undefined);
      }, 350);
    },
    [flushSettings]
  );

  const handleLogin = (nextUser: User, nextSettings: AppSettings) => {
    setUser(nextUser);
    setSettings(nextSettings);
    applyAppearance(nextSettings.appearance);
    setView('mail');
  };

  const handleLogout = async () => {
    await api.auth.logout().catch(() => undefined);
    setUser(null);
    setSettings(null);
    setView('mail');
    setSettingsSection(undefined);
    applyAppearance(FALLBACK_SETTINGS.appearance);
  };

  /** 打开设置页,可指定默认显示的设置分区 */
  const openSettings = (section?: SettingsSection) => {
    setSettingsSection(section);
    setView('settings');
  };

  const lang = settings?.appearance.language || 'zh';

  if (loading) {
    return (
      <I18nProvider lang={lang}>
        <div className="splash">
          <div className="brand-logo large">
            <Icon name="mail" size={22} />
          </div>
          <Spinner size={20} />
        </div>
      </I18nProvider>
    );
  }

  return (
    <I18nProvider lang={lang}>
      {!user || !settings ? (
        <Login onSuccess={handleLogin} />
      ) : view === 'settings' ? (
        <SettingsPage
          user={user}
          settings={settings}
          updateSettings={updateSettings}
          flushSettings={flushSettings}
          onBack={() => setView('mail')}
          onLogout={handleLogout}
          initialSection={settingsSection}
        />
      ) : (
        <MailPage
          user={user}
          settings={settings}
          onOpenSettings={openSettings}
          onLogout={handleLogout}
        />
      )}
    </I18nProvider>
  );
}