refactor: Context 与 Provider 合并 — 消除 contexts/ 目录,一文件一状态单元
- ThemeContext + useTheme → ThemeProvider.tsx(原 hooks/use-theme.ts 删除) - AppContext + useAppContext → AppProvider.tsx(原 contexts/app-context.ts 删除) - SettingsContext + useSettings → SettingsProvider.tsx(原 contexts/settings-context.ts 删除) - HomeContext + useHomeContext → HomeContent.tsx(原 contexts/home-context.ts 删除) - 删除空的 contexts/ 目录,20+ 导入路径同步更新 - TypeScript 编译通过(npx tsc --noEmit 零错误) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -1,14 +1,17 @@
|
||||
// ============================================================
|
||||
// AppProvider — 应用状态 Provider 组件
|
||||
// AppProvider — 全局应用状态 Context + Provider + Hook
|
||||
//
|
||||
// 导出:
|
||||
// AppContext, useAppContext() — Context + Consumer Hook
|
||||
// AppContextValue — 类型
|
||||
// AppProvider — Provider 组件
|
||||
// ============================================================
|
||||
|
||||
import { useState, useMemo, useCallback, useEffect, type ReactNode } from 'react';
|
||||
import { createContext, useContext, useState, useMemo, useCallback, useEffect, type ReactNode } from 'react';
|
||||
import type { Platform, Edition } from '@shared/types';
|
||||
|
||||
import { getPlatform, isDev } from '@/utils/platform';
|
||||
import { safeIpcOn, safeIpcOff } from '@/utils/ipc';
|
||||
import { AppContext } from '@/contexts/app-context';
|
||||
import type { AppContextValue } from '@/contexts/app-context';
|
||||
import type { LoginResponseBody } from '@/services/modules';
|
||||
import { setToken, clearToken, initTokenStore } from '@/services/request';
|
||||
import { emit, EVENTS } from '@/utils/event-bus';
|
||||
@@ -23,6 +26,39 @@ import {
|
||||
initRefreshTokenStore,
|
||||
} from '@/services/auth-token';
|
||||
|
||||
// ---------- Context 类型 ----------
|
||||
|
||||
export interface AppContextValue {
|
||||
/** 当前操作系统平台 */
|
||||
platform: Platform;
|
||||
/** 产品版本(个人版 / 企业版) */
|
||||
edition: Edition;
|
||||
/** 用户是否已登录 */
|
||||
isLoggedIn: boolean;
|
||||
/** 当前登录用户信息(未登录时为 null,结构与 LoginResponseBody 一致) */
|
||||
user: LoginResponseBody | null;
|
||||
/** 登录:保存 Token 并更新登录态(auth 为登录接口返回值,异步加密存储) */
|
||||
login: (auth: LoginResponseBody) => Promise<void>;
|
||||
/** 退出登录:清除 Token 和用户状态 */
|
||||
logout: () => void;
|
||||
/** 是否为开发环境 */
|
||||
isDevMode: boolean;
|
||||
}
|
||||
|
||||
export const AppContext = createContext<AppContextValue | null>(null);
|
||||
|
||||
// ---------- Consumer Hook ----------
|
||||
|
||||
export function useAppContext(): AppContextValue {
|
||||
const ctx = useContext(AppContext);
|
||||
if (!ctx) {
|
||||
throw new Error('useAppContext() 必须在 <AppProvider> 内部调用');
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
|
||||
// ---------- Provider 组件 ----------
|
||||
|
||||
interface AppProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user