509 lines
20 KiB
TypeScript
509 lines
20 KiB
TypeScript
import React, { useState, useCallback, useEffect, useRef } from 'react';
|
||
import { loginUser, registerUser, getCurrentUser, generatePlan, updateTask, updateTaskStatus, createTask, deleteTask as apiDeleteTask, reorderTasks, logout as apiLogout, User, Plan, StatusUpdateResult, GenerateProgressEvent } from './services/apiService';
|
||
import { CascadeCompletedTask } from './types';
|
||
import LandingPage from './components/LandingPage';
|
||
import GoalInputForm from './components/GoalInputForm';
|
||
import PlannerView from './components/PlannerView';
|
||
import PlanHistory from './components/PlanHistory';
|
||
import Loader from './components/Loader';
|
||
import GenerationProgress from './components/GenerationProgress';
|
||
import Header from './components/Header';
|
||
import Footer from './components/Footer';
|
||
import LoginPage from './components/LoginPage';
|
||
import SignUpPage from './components/SignUpPage';
|
||
import ToastProvider, { toast } from './components/Toast';
|
||
|
||
type View = 'landing' | 'input' | 'loading' | 'planner' | 'error' | 'login' | 'signup' | 'history';
|
||
|
||
const App: React.FC = () => {
|
||
const [view, setView] = useState<View>('landing');
|
||
const [currentPlan, setCurrentPlan] = useState<Plan | null>(null);
|
||
const [goal, setGoal] = useState('');
|
||
const [error, setError] = useState<string | null>(null);
|
||
const [currentUser, setCurrentUser] = useState<User | null>(null);
|
||
const [isLoading, setIsLoading] = useState(true);
|
||
const [cascadeCompleted, setCascadeCompleted] = useState<CascadeCompletedTask[]>([]);
|
||
const cascadeConsumedRef = useRef(0);
|
||
const [lastXpGain, setLastXpGain] = useState(0);
|
||
const [levelUpInfo, setLevelUpInfo] = useState<{ oldLevel: number; newLevel: number } | null>(null);
|
||
const [darkMode, setDarkMode] = useState(() => {
|
||
const saved = localStorage.getItem('darkMode');
|
||
return saved === 'true';
|
||
});
|
||
const [genProgress, setGenProgress] = useState<{ progress: number; message: string; step: string } | null>(null);
|
||
|
||
// Apply dark mode
|
||
useEffect(() => {
|
||
document.documentElement.classList.toggle('dark', darkMode);
|
||
localStorage.setItem('darkMode', String(darkMode));
|
||
}, [darkMode]);
|
||
|
||
useEffect(() => {
|
||
const checkAuth = async () => {
|
||
const user = await getCurrentUser();
|
||
if (user) {
|
||
setCurrentUser(user);
|
||
setView('input');
|
||
}
|
||
setIsLoading(false);
|
||
};
|
||
checkAuth();
|
||
}, []);
|
||
|
||
const handleGetStarted = () => {
|
||
if (currentUser) {
|
||
setView('input');
|
||
} else {
|
||
setView('login');
|
||
}
|
||
};
|
||
|
||
const handleLogin = async (email: string, password: string) => {
|
||
try {
|
||
const { user } = await loginUser(email, password);
|
||
setCurrentUser(user);
|
||
setView('input');
|
||
toast.success(`欢迎回来,${user.name}!`);
|
||
} catch (err) {
|
||
if (err instanceof Error) {
|
||
setError(err.message);
|
||
toast.error(err.message);
|
||
}
|
||
setView('login');
|
||
}
|
||
};
|
||
|
||
const handleSignUp = async (name: string, email: string, password: string) => {
|
||
try {
|
||
await registerUser(name, email, password);
|
||
const { user } = await loginUser(email, password);
|
||
setCurrentUser(user);
|
||
setView('input');
|
||
toast.success('注册成功!');
|
||
} catch (err) {
|
||
if (err instanceof Error) {
|
||
setError(err.message);
|
||
toast.error(err.message);
|
||
}
|
||
setView('signup');
|
||
}
|
||
};
|
||
|
||
const handleLogout = () => {
|
||
apiLogout();
|
||
setCurrentUser(null);
|
||
setCurrentPlan(null);
|
||
setGoal('');
|
||
setError(null);
|
||
setView('landing');
|
||
};
|
||
|
||
const handleGeneratePlan = async (userGoal: string, additionalInfo?: string) => {
|
||
setGoal(userGoal);
|
||
setView('loading');
|
||
setError(null);
|
||
setGenProgress({ progress: 5, message: '准备中...', step: 'analyzing' });
|
||
try {
|
||
const plan = await generatePlan(userGoal, additionalInfo, (event: GenerateProgressEvent) => {
|
||
setGenProgress({
|
||
progress: event.progress,
|
||
message: event.message,
|
||
step: event.step || 'analyzing',
|
||
});
|
||
});
|
||
setCurrentPlan(plan);
|
||
setGenProgress(null);
|
||
setView('planner');
|
||
toast.success('计划生成成功!');
|
||
} catch (err) {
|
||
setGenProgress(null);
|
||
if (err instanceof Error) {
|
||
setError(err.message);
|
||
toast.error(err.message);
|
||
} else {
|
||
setError("An unknown error occurred.");
|
||
toast.error("An unknown error occurred.");
|
||
}
|
||
setView('error');
|
||
}
|
||
};
|
||
|
||
const handleStartOver = () => {
|
||
setCurrentPlan(null);
|
||
setGoal('');
|
||
setError(null);
|
||
setView('input');
|
||
};
|
||
|
||
const handleResetToLanding = useCallback(() => {
|
||
setView('landing');
|
||
}, []);
|
||
|
||
const handleToggleTask = async (taskDbId: number) => {
|
||
if (!currentPlan) return;
|
||
|
||
const findTaskWithLevel = (items: Plan['tasks'], id: number, lvl: number = 0): { task: Plan['tasks'][0]; level: number } | null => {
|
||
for (const t of items) {
|
||
if (t.id === id) return { task: t, level: lvl };
|
||
if (t.children?.length) {
|
||
const found = findTaskWithLevel(t.children, id, lvl + 1);
|
||
if (found) return found;
|
||
}
|
||
}
|
||
return null;
|
||
};
|
||
|
||
const result = findTaskWithLevel(currentPlan.tasks, taskDbId);
|
||
if (!result) return;
|
||
|
||
const newStatus = result.task.status === 'done' ? 'todo' : 'done';
|
||
try {
|
||
const statusResult = await updateTaskStatus(currentPlan.id, taskDbId, newStatus);
|
||
const changeMap = new Map<number, string>();
|
||
for (const c of statusResult.changes) {
|
||
changeMap.set(c.id, c.status as 'todo' | 'in_progress' | 'done');
|
||
}
|
||
|
||
const cascadeParentTasks: CascadeCompletedTask[] = [];
|
||
for (const c of statusResult.changes) {
|
||
if (c.id !== taskDbId && c.status === 'done') {
|
||
const found = findTaskWithLevel(currentPlan.tasks, c.id);
|
||
if (found && found.task.children && found.task.children.length > 0) {
|
||
cascadeParentTasks.push({ taskId: c.id, level: found.level });
|
||
}
|
||
}
|
||
}
|
||
|
||
// Update XP state
|
||
if (statusResult.xp_change !== 0) {
|
||
setCurrentUser(prev => {
|
||
const updated = prev ? { ...prev, xp: statusResult.user_xp } : prev;
|
||
if (updated) localStorage.setItem('user', JSON.stringify(updated));
|
||
return updated;
|
||
});
|
||
setLastXpGain(statusResult.xp_change);
|
||
}
|
||
|
||
// Level up notification
|
||
if (statusResult.level_up) {
|
||
setLevelUpInfo({ oldLevel: statusResult.old_level, newLevel: statusResult.new_level });
|
||
setTimeout(() => setLevelUpInfo(null), 3000);
|
||
toast.success(`🎉 升级了!Lv.${statusResult.old_level} → Lv.${statusResult.new_level}`);
|
||
}
|
||
|
||
// All done bonus notification
|
||
if (statusResult.all_done_bonus > 0) {
|
||
toast.success(`🏆 所有任务完成!获得 ${statusResult.all_done_bonus} XP 奖励!`);
|
||
}
|
||
|
||
if (cascadeParentTasks.length > 0) {
|
||
cascadeConsumedRef.current = 0;
|
||
setCascadeCompleted(cascadeParentTasks);
|
||
}
|
||
|
||
setCurrentPlan(prev => {
|
||
if (!prev) return prev;
|
||
const applyChanges = (items: Plan['tasks']): Plan['tasks'] =>
|
||
items.map(t => {
|
||
const newStatusForTask = changeMap.get(t.id);
|
||
const updatedT = newStatusForTask ? { ...t, status: newStatusForTask } : t;
|
||
if (updatedT.children?.length) {
|
||
return { ...updatedT, children: applyChanges(updatedT.children) };
|
||
}
|
||
return updatedT;
|
||
});
|
||
return { ...prev, tasks: applyChanges(prev.tasks) };
|
||
});
|
||
} catch (err) {
|
||
if (err instanceof Error) {
|
||
toast.error(err.message);
|
||
}
|
||
}
|
||
};
|
||
|
||
const handleStatusChange = async (taskDbId: number, status: string) => {
|
||
if (!currentPlan) return;
|
||
try {
|
||
const statusResult = await updateTaskStatus(currentPlan.id, taskDbId, status);
|
||
const changeMap = new Map<number, string>();
|
||
for (const c of statusResult.changes) {
|
||
changeMap.set(c.id, c.status as 'todo' | 'in_progress' | 'done');
|
||
}
|
||
|
||
if (statusResult.xp_change !== 0) {
|
||
setCurrentUser(prev => {
|
||
const updated = prev ? { ...prev, xp: statusResult.user_xp } : prev;
|
||
if (updated) localStorage.setItem('user', JSON.stringify(updated));
|
||
return updated;
|
||
});
|
||
setLastXpGain(statusResult.xp_change);
|
||
}
|
||
|
||
if (statusResult.level_up) {
|
||
setLevelUpInfo({ oldLevel: statusResult.old_level, newLevel: statusResult.new_level });
|
||
setTimeout(() => setLevelUpInfo(null), 3000);
|
||
toast.success(`🎉 升级了!Lv.${statusResult.old_level} → Lv.${statusResult.new_level}`);
|
||
}
|
||
|
||
if (statusResult.all_done_bonus > 0) {
|
||
toast.success(`🏆 所有任务完成!获得 ${statusResult.all_done_bonus} XP 奖励!`);
|
||
}
|
||
|
||
setCurrentPlan(prev => {
|
||
if (!prev) return prev;
|
||
const applyChanges = (items: Plan['tasks']): Plan['tasks'] =>
|
||
items.map(t => {
|
||
const newStatusForTask = changeMap.get(t.id);
|
||
const updatedT = newStatusForTask ? { ...t, status: newStatusForTask } : t;
|
||
if (updatedT.children?.length) {
|
||
return { ...updatedT, children: applyChanges(updatedT.children) };
|
||
}
|
||
return updatedT;
|
||
});
|
||
return { ...prev, tasks: applyChanges(prev.tasks) };
|
||
});
|
||
} catch (err) {
|
||
if (err instanceof Error) {
|
||
toast.error(err.message);
|
||
}
|
||
}
|
||
};
|
||
|
||
const handleSaveTask = async (updatedTask: any) => {
|
||
if (!currentPlan) return;
|
||
try {
|
||
const task = await updateTask(currentPlan.id, updatedTask.id, {
|
||
title: updatedTask.title,
|
||
description: updatedTask.description,
|
||
dependencies: updatedTask.dependencies,
|
||
durationInHours: updatedTask.durationInHours,
|
||
priority: updatedTask.priority,
|
||
dueDate: updatedTask.dueDate,
|
||
});
|
||
setCurrentPlan(prev => {
|
||
if (!prev) return prev;
|
||
const updateTaskInTree = (items: Plan['tasks']): Plan['tasks'] =>
|
||
items.map(t =>
|
||
t.id === task.id
|
||
? { ...t, ...task, durationInHours: task.durationInHours, children: t.children }
|
||
: t.children?.length
|
||
? { ...t, children: updateTaskInTree(t.children) }
|
||
: t
|
||
);
|
||
return { ...prev, tasks: updateTaskInTree(prev.tasks) };
|
||
});
|
||
toast.success('任务已更新');
|
||
} catch (err) {
|
||
if (err instanceof Error) {
|
||
toast.error(err.message);
|
||
}
|
||
}
|
||
};
|
||
|
||
const handleDeleteTask = async (taskDbId: number) => {
|
||
if (!currentPlan) return;
|
||
try {
|
||
const result = await apiDeleteTask(currentPlan.id, taskDbId);
|
||
const deletedSet = new Set(result.deleted_ids);
|
||
setCurrentPlan(prev => {
|
||
if (!prev) return prev;
|
||
const removeTasks = (items: Plan['tasks']): Plan['tasks'] =>
|
||
items
|
||
.filter(t => !deletedSet.has(t.id))
|
||
.map(t => t.children?.length
|
||
? { ...t, children: removeTasks(t.children) }
|
||
: t
|
||
);
|
||
return { ...prev, tasks: removeTasks(prev.tasks) };
|
||
});
|
||
toast.success('任务已删除');
|
||
} catch (err) {
|
||
if (err instanceof Error) {
|
||
toast.error(err.message);
|
||
}
|
||
}
|
||
};
|
||
|
||
const handleAddTask = async (data: {
|
||
task_id: string;
|
||
title: string;
|
||
description: string;
|
||
parent_id?: number | null;
|
||
dependencies: string[];
|
||
durationInHours: number;
|
||
priority?: string;
|
||
dueDate?: string | null;
|
||
sortOrder?: number;
|
||
}) => {
|
||
if (!currentPlan) return;
|
||
try {
|
||
const newTask = await createTask(currentPlan.id, {
|
||
...data,
|
||
priority: data.priority as any,
|
||
dueDate: data.dueDate,
|
||
sortOrder: data.sortOrder,
|
||
});
|
||
setCurrentPlan(prev => {
|
||
if (!prev) return prev;
|
||
const addTaskToTree = (items: Plan['tasks']): Plan['tasks'] => {
|
||
if (data.parent_id === null || data.parent_id === undefined) {
|
||
return [...items, newTask];
|
||
}
|
||
return items.map(t => {
|
||
if (t.id === data.parent_id) {
|
||
return { ...t, children: [...(t.children || []), newTask] };
|
||
}
|
||
if (t.children?.length) {
|
||
return { ...t, children: addTaskToTree(t.children) };
|
||
}
|
||
return t;
|
||
});
|
||
};
|
||
return { ...prev, tasks: addTaskToTree(prev.tasks) };
|
||
});
|
||
toast.success('任务已添加');
|
||
} catch (err) {
|
||
if (err instanceof Error) {
|
||
toast.error(err.message);
|
||
}
|
||
}
|
||
};
|
||
|
||
const handleReorderTasks = async (taskOrders: { id: number; sort_order: number }[]) => {
|
||
if (!currentPlan) return;
|
||
try {
|
||
await reorderTasks(currentPlan.id, taskOrders);
|
||
// Update local state optimistically
|
||
const orderMap = new Map(taskOrders.map(o => [o.id, o.sort_order]));
|
||
setCurrentPlan(prev => {
|
||
if (!prev) return prev;
|
||
const reorderItems = (items: Plan['tasks']): Plan['tasks'] =>
|
||
items
|
||
.map(t => {
|
||
const newSortOrder = orderMap.get(t.id) ?? t.sortOrder;
|
||
return {
|
||
...t,
|
||
sortOrder: newSortOrder,
|
||
children: t.children?.length ? reorderItems(t.children) : t.children,
|
||
};
|
||
})
|
||
.sort((a, b) => a.sortOrder - b.sortOrder);
|
||
return { ...prev, tasks: reorderItems(prev.tasks) };
|
||
});
|
||
} catch (err) {
|
||
if (err instanceof Error) {
|
||
toast.error('排序更新失败');
|
||
}
|
||
}
|
||
};
|
||
|
||
const handleViewPlan = (plan: Plan) => {
|
||
setCurrentPlan(plan);
|
||
setView('planner');
|
||
};
|
||
|
||
const handleMyPlans = () => {
|
||
setView('history');
|
||
};
|
||
|
||
const renderContent = () => {
|
||
switch (view) {
|
||
case 'landing':
|
||
return <LandingPage onGetStarted={handleGetStarted} />;
|
||
case 'login':
|
||
return <LoginPage onLogin={handleLogin} onNavigateToSignUp={() => setView('signup')} />;
|
||
case 'signup':
|
||
return <SignUpPage onSignUp={handleSignUp} onNavigateToLogin={() => setView('login')} />;
|
||
case 'input':
|
||
if (!currentUser) { setView('login'); return null; }
|
||
return <GoalInputForm onGeneratePlan={handleGeneratePlan} />;
|
||
case 'planner':
|
||
if (!currentUser || !currentPlan) { setView('login'); return null; }
|
||
return (
|
||
<PlannerView
|
||
goal={currentPlan.goal}
|
||
tasks={currentPlan.tasks}
|
||
planId={currentPlan.id}
|
||
onToggleTask={handleToggleTask}
|
||
onSaveTask={handleSaveTask}
|
||
onDeleteTask={handleDeleteTask}
|
||
onAddTask={handleAddTask}
|
||
onStatusChange={handleStatusChange}
|
||
onReorderTasks={handleReorderTasks}
|
||
onStartOver={handleStartOver}
|
||
onMyPlans={handleMyPlans}
|
||
cascadeCompleted={cascadeCompleted}
|
||
onCascadeConsumed={() => {
|
||
cascadeConsumedRef.current += 1;
|
||
if (cascadeConsumedRef.current >= cascadeCompleted.length) {
|
||
setCascadeCompleted([]);
|
||
}
|
||
}}
|
||
/>
|
||
);
|
||
case 'history':
|
||
if (!currentUser) { setView('login'); return null; }
|
||
return (
|
||
<PlanHistory
|
||
onViewPlan={handleViewPlan}
|
||
onCreateNew={() => setView('input')}
|
||
/>
|
||
);
|
||
case 'error':
|
||
return (
|
||
<div className="bg-red-100 dark:bg-red-900/30 border border-red-400 dark:border-red-700 text-red-700 dark:text-red-300 px-4 py-3 rounded-lg text-center">
|
||
<strong className="font-bold">Oops! Something went wrong.</strong>
|
||
<p className="block sm:inline">{error}</p>
|
||
<button
|
||
onClick={handleStartOver}
|
||
className="mt-4 bg-red-600 text-white font-semibold px-4 py-2 rounded-lg hover:bg-red-700 transition-colors"
|
||
>
|
||
Try Again
|
||
</button>
|
||
</div>
|
||
);
|
||
default:
|
||
return null;
|
||
}
|
||
};
|
||
|
||
if (isLoading) {
|
||
return <Loader message="Loading..." />;
|
||
}
|
||
|
||
return (
|
||
<ToastProvider>
|
||
<div className="flex flex-col min-h-screen bg-slate-50 dark:bg-slate-900 transition-colors duration-200">
|
||
<Header
|
||
user={currentUser}
|
||
onLogout={handleLogout}
|
||
onLoginClick={() => setView('login')}
|
||
onSignUpClick={() => setView('signup')}
|
||
onLogoClick={handleResetToLanding}
|
||
onMyPlans={handleMyPlans}
|
||
xpGain={lastXpGain}
|
||
levelUpInfo={levelUpInfo}
|
||
darkMode={darkMode}
|
||
onToggleDarkMode={() => setDarkMode(!darkMode)}
|
||
/>
|
||
<main className="flex-grow container mx-auto px-3 sm:px-4 py-6 sm:py-8 md:py-12">
|
||
<div className="max-w-4xl mx-auto">
|
||
{renderContent()}
|
||
</div>
|
||
</main>
|
||
{view === 'landing' && <Footer />}
|
||
{view === 'loading' && !genProgress && <Loader message="Generating your plan with AI..." />}
|
||
{view === 'loading' && genProgress && (
|
||
<GenerationProgress
|
||
progress={genProgress.progress}
|
||
message={genProgress.message}
|
||
step={genProgress.step}
|
||
/>
|
||
)}
|
||
</div>
|
||
</ToastProvider>
|
||
);
|
||
};
|
||
|
||
export default App;
|