fa
This commit is contained in:
124
src/contexts/AuthContext.tsx
Normal file
124
src/contexts/AuthContext.tsx
Normal file
@@ -0,0 +1,124 @@
|
||||
'use client';
|
||||
|
||||
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react';
|
||||
|
||||
interface AuthContextType {
|
||||
isAuthenticated: boolean;
|
||||
showAuthModal: boolean;
|
||||
authenticate: (password: string) => Promise<boolean>;
|
||||
logout: () => void;
|
||||
requestAuth: () => void;
|
||||
closeAuthModal: () => void;
|
||||
getAuthHeaders: () => Record<string, string>;
|
||||
}
|
||||
|
||||
const AUTH_STORAGE_KEY = 'stark-todo-auth';
|
||||
const AUTH_PASSWORD_KEY = 'stark-todo-pwd';
|
||||
|
||||
// 默认值,用于 SSR
|
||||
const defaultContextValue: AuthContextType = {
|
||||
isAuthenticated: false,
|
||||
showAuthModal: false,
|
||||
authenticate: async () => false,
|
||||
logout: () => {},
|
||||
requestAuth: () => {},
|
||||
closeAuthModal: () => {},
|
||||
getAuthHeaders: () => ({}),
|
||||
};
|
||||
|
||||
const AuthContext = createContext<AuthContextType>(defaultContextValue);
|
||||
|
||||
export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
const [isAuthenticated, setIsAuthenticated] = useState(false);
|
||||
const [showAuthModal, setShowAuthModal] = useState(false);
|
||||
const [isClient, setIsClient] = useState(false);
|
||||
const [storedPassword, setStoredPassword] = useState<string | null>(null);
|
||||
|
||||
// 客户端初始化
|
||||
useEffect(() => {
|
||||
setIsClient(true);
|
||||
const savedAuth = localStorage.getItem(AUTH_STORAGE_KEY);
|
||||
const savedPwd = localStorage.getItem(AUTH_PASSWORD_KEY);
|
||||
if (savedAuth === 'true' && savedPwd) {
|
||||
setIsAuthenticated(true);
|
||||
setStoredPassword(savedPwd);
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 验证密码
|
||||
const authenticate = useCallback(async (password: string): Promise<boolean> => {
|
||||
try {
|
||||
const response = await fetch('/api/auth', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ password }),
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setIsAuthenticated(true);
|
||||
setStoredPassword(password);
|
||||
localStorage.setItem(AUTH_STORAGE_KEY, 'true');
|
||||
localStorage.setItem(AUTH_PASSWORD_KEY, password);
|
||||
setShowAuthModal(false);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} catch (error) {
|
||||
console.error('[Auth] Verification failed:', error);
|
||||
return false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 登出
|
||||
const logout = useCallback(() => {
|
||||
setIsAuthenticated(false);
|
||||
setStoredPassword(null);
|
||||
localStorage.removeItem(AUTH_STORAGE_KEY);
|
||||
localStorage.removeItem(AUTH_PASSWORD_KEY);
|
||||
}, []);
|
||||
|
||||
// 请求验证(显示弹窗)
|
||||
const requestAuth = useCallback(() => {
|
||||
if (!isAuthenticated) {
|
||||
setShowAuthModal(true);
|
||||
}
|
||||
}, [isAuthenticated]);
|
||||
|
||||
// 关闭弹窗
|
||||
const closeAuthModal = useCallback(() => {
|
||||
setShowAuthModal(false);
|
||||
}, []);
|
||||
|
||||
// 获取认证请求头
|
||||
const getAuthHeaders = useCallback((): Record<string, string> => {
|
||||
if (storedPassword) {
|
||||
return { 'X-API-Key': storedPassword };
|
||||
}
|
||||
return {};
|
||||
}, [storedPassword]);
|
||||
|
||||
// 始终提供 Context,确保子组件可以访问
|
||||
const contextValue: AuthContextType = isClient
|
||||
? {
|
||||
isAuthenticated,
|
||||
showAuthModal,
|
||||
authenticate,
|
||||
logout,
|
||||
requestAuth,
|
||||
closeAuthModal,
|
||||
getAuthHeaders,
|
||||
}
|
||||
: defaultContextValue;
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={contextValue}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
return useContext(AuthContext);
|
||||
}
|
||||
154
src/contexts/SettingsContext.tsx
Normal file
154
src/contexts/SettingsContext.tsx
Normal file
@@ -0,0 +1,154 @@
|
||||
'use client';
|
||||
|
||||
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
||||
|
||||
export interface Settings {
|
||||
language: 'zh' | 'en';
|
||||
logoText: string;
|
||||
timezone: string;
|
||||
theme: 'light' | 'dark' | 'system';
|
||||
}
|
||||
|
||||
interface SettingsContextType {
|
||||
settings: Settings;
|
||||
updateSettings: (newSettings: Partial<Settings>) => void;
|
||||
}
|
||||
|
||||
const defaultSettings: Settings = {
|
||||
language: 'zh',
|
||||
logoText: '蛋定-项目待办',
|
||||
timezone: 'Asia/Shanghai',
|
||||
theme: 'system',
|
||||
};
|
||||
|
||||
const SettingsContext = createContext<SettingsContextType | undefined>(undefined);
|
||||
|
||||
export function SettingsProvider({ children }: { children: ReactNode }) {
|
||||
const [settings, setSettings] = useState<Settings>(defaultSettings);
|
||||
const [isClient, setIsClient] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setIsClient(true);
|
||||
|
||||
// Load settings from localStorage
|
||||
const savedSettings = localStorage.getItem('stark-settings');
|
||||
if (savedSettings) {
|
||||
try {
|
||||
const parsed = JSON.parse(savedSettings);
|
||||
// Merge with default settings to ensure all fields exist
|
||||
const mergedSettings = { ...defaultSettings, ...parsed };
|
||||
setSettings(mergedSettings);
|
||||
console.log('[Settings] Loaded from localStorage:', mergedSettings);
|
||||
// Apply theme immediately after loading
|
||||
requestAnimationFrame(() => {
|
||||
applyTheme(mergedSettings.theme);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('[Settings] Failed to parse settings:', error);
|
||||
// Use default settings on error
|
||||
setSettings(defaultSettings);
|
||||
applyTheme(defaultSettings.theme);
|
||||
}
|
||||
} else {
|
||||
console.log('[Settings] No saved settings, using defaults:', defaultSettings);
|
||||
// Save default settings to localStorage
|
||||
localStorage.setItem('stark-settings', JSON.stringify(defaultSettings));
|
||||
applyTheme(defaultSettings.theme);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isClient) return;
|
||||
|
||||
// Save settings to localStorage whenever they change
|
||||
try {
|
||||
localStorage.setItem('stark-settings', JSON.stringify(settings));
|
||||
console.log('[Settings] Saved to localStorage:', settings);
|
||||
} catch (error) {
|
||||
console.error('[Settings] Failed to save settings:', error);
|
||||
}
|
||||
|
||||
// Apply theme
|
||||
applyTheme(settings.theme);
|
||||
}, [settings, isClient]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isClient) return;
|
||||
|
||||
// Listen to system theme changes
|
||||
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
|
||||
const handleChange = () => {
|
||||
if (settings.theme === 'system') {
|
||||
applyTheme('system');
|
||||
}
|
||||
};
|
||||
|
||||
mediaQuery.addEventListener('change', handleChange);
|
||||
|
||||
return () => mediaQuery.removeEventListener('change', handleChange);
|
||||
}, [settings.theme, isClient]);
|
||||
|
||||
const applyTheme = (theme: 'light' | 'dark' | 'system') => {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
const root = document.documentElement;
|
||||
|
||||
// 强制移除过渡效果,确保立即切换
|
||||
root.style.setProperty('transition', 'none');
|
||||
|
||||
if (theme === 'system') {
|
||||
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
|
||||
if (prefersDark) {
|
||||
root.classList.add('dark');
|
||||
} else {
|
||||
root.classList.remove('dark');
|
||||
}
|
||||
} else if (theme === 'dark') {
|
||||
root.classList.add('dark');
|
||||
} else {
|
||||
root.classList.remove('dark');
|
||||
}
|
||||
|
||||
// 强制重绘,确保立即生效
|
||||
void root.offsetHeight;
|
||||
|
||||
// 恢复过渡效果
|
||||
requestAnimationFrame(() => {
|
||||
root.style.removeProperty('transition');
|
||||
});
|
||||
|
||||
console.log(`[Theme] Applied theme: ${theme}, dark class: ${root.classList.contains('dark')}`);
|
||||
};
|
||||
|
||||
const updateSettings = (newSettings: Partial<Settings>) => {
|
||||
setSettings(prev => {
|
||||
const updated = { ...prev, ...newSettings };
|
||||
|
||||
console.log('[Settings] Updating settings:', { old: prev, new: newSettings, updated });
|
||||
|
||||
// 如果更新了主题,立即应用
|
||||
if (newSettings.theme !== undefined) {
|
||||
requestAnimationFrame(() => {
|
||||
applyTheme(newSettings.theme!);
|
||||
});
|
||||
}
|
||||
|
||||
return updated;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingsContext.Provider value={{ settings, updateSettings }}>
|
||||
{children}
|
||||
</SettingsContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useSettings() {
|
||||
const context = useContext(SettingsContext);
|
||||
if (!context) {
|
||||
throw new Error('useSettings must be used within SettingsProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
Reference in New Issue
Block a user