import React, { useState, useMemo, useEffect, useCallback, useRef } from 'react'; import { createPortal } from 'react-dom'; import { Task, CascadeCompletedTask, TaskStatus } from '../types'; import TaskList from './TaskList'; import EditTaskModal from './EditTaskModal'; import AddTaskModal from './AddTaskModal'; import TaskCompleteModal from './TaskCompleteModal'; import SvgaPlayer from './SvgaPlayer'; interface AnimationState { type: 'child' | 'parent' | 'allDone'; level: number; task: Task; key: number; } interface AddTaskState { mode: 'child' | 'sibling'; task: Task; } interface PlannerViewProps { goal: string; tasks: Task[]; planId: number; onToggleTask: (taskDbId: number) => void; onSaveTask: (updatedTask: Task) => void; onDeleteTask: (taskDbId: number) => void; onAddTask: (data: { task_id: string; title: string; description: string; parent_id?: number | null; dependencies: string[]; durationInHours: number; priority?: string; dueDate?: string | null; sortOrder?: number; }) => void; onStatusChange: (taskDbId: number, status: string) => void; onReorderTasks: (taskOrders: { id: number; sort_order: number }[]) => void; onStartOver: () => void; onMyPlans?: () => void; cascadeCompleted?: CascadeCompletedTask[]; onCascadeConsumed?: () => void; } const SVGA_BY_LEVEL: Record = { '0': '/svga/爱心直升机.svga', '1': '/svga/钻石.svga', '2': '/svga/666.svga', }; const SVGA_ALL_DONE = '/svga/紫色城堡.svga'; const findTaskInTree = (items: Task[], id: number): Task | null => { for (const t of items) { if (t.id === id) return t; if (t.children?.length) { const found = findTaskInTree(t.children, id); if (found) return found; } } return null; }; const findParentTask = (items: Task[], parentId: number): Task | null => { for (const t of items) { if (t.id === parentId) return t; if (t.children?.length) { const found = findParentTask(t.children, parentId); if (found) return found; } } return null; }; const ANIMATION_ENABLED = false; const PlannerView: React.FC = ({ goal, tasks, planId, onToggleTask, onSaveTask, onDeleteTask, onAddTask, onStatusChange, onReorderTasks, onStartOver, onMyPlans, cascadeCompleted, onCascadeConsumed }) => { const [editingTask, setEditingTask] = useState(null); const [addingTask, setAddingTask] = useState(null); const [animationQueue, setAnimationQueue] = useState([]); const [currentAnim, setCurrentAnim] = useState(null); const animKeyRef = useRef(0); const cascadeProcessedRef = useRef(0); // Search & filter const [searchQuery, setSearchQuery] = useState(''); const [filterStatus, setFilterStatus] = useState<'all' | TaskStatus>('all'); const [filterPriority, setFilterPriority] = useState<'all' | 'low' | 'medium' | 'high'>('all'); // Drag and drop const [draggedTask, setDraggedTask] = useState(null); const [dragOverTask, setDragOverTask] = useState(null); const [completedTaskInfo, setCompletedTaskInfo] = useState<{ task: Task; level: number } | null>(null); const handleToggleTask = (taskDbId: number) => { onToggleTask(taskDbId); }; const handleEditTask = (task: Task) => { setEditingTask(task); }; const handleSaveTask = (updatedTask: Task) => { onSaveTask(updatedTask); setEditingTask(null); }; const handleCancelEdit = () => { setEditingTask(null); }; const handleAddChildTask = (parentTask: Task) => { setAddingTask({ mode: 'child', task: parentTask }); }; const handleAddSiblingTask = (task: Task) => { setAddingTask({ mode: 'sibling', task }); }; const handleSaveNewTask = (data: { task_id: string; title: string; description: string; parent_id?: number | null; dependencies: string[]; durationInHours: number; priority?: string; dueDate?: string | null; sortOrder?: number; }) => { onAddTask(data); setAddingTask(null); }; const handleCancelAdd = () => { setAddingTask(null); }; const enqueueAnimation = useCallback((anim: Omit) => { if (!ANIMATION_ENABLED) return; animKeyRef.current += 1; const newAnim = { ...anim, key: animKeyRef.current } as AnimationState; setAnimationQueue(prev => [...prev, newAnim]); }, []); useEffect(() => { if (currentAnim || animationQueue.length === 0) return; setCurrentAnim(animationQueue[0]); setAnimationQueue(prev => prev.slice(1)); }, [currentAnim, animationQueue]); const handleAnimComplete = useCallback(() => { setCurrentAnim(null); }, []); const handleChildTaskCompleted = useCallback((task: Task, level: number) => { setCompletedTaskInfo({ task, level }); enqueueAnimation({ type: 'child', level, task }); }, [enqueueAnimation]); const handleParentTaskCompleted = useCallback((task: Task, level: number) => { enqueueAnimation({ type: 'parent', level, task }); }, [enqueueAnimation]); useEffect(() => { if (!cascadeCompleted || cascadeCompleted.length === 0) return; if (cascadeProcessedRef.current >= cascadeCompleted.length) return; for (let i = cascadeProcessedRef.current; i < cascadeCompleted.length; i++) { const ct = cascadeCompleted[i]; const task = findTaskInTree(tasks, ct.taskId); if (task) enqueueAnimation({ type: 'parent', level: ct.level, task }); onCascadeConsumed?.(); } cascadeProcessedRef.current = cascadeCompleted.length; }, [cascadeCompleted, tasks, enqueueAnimation, onCascadeConsumed]); useEffect(() => { if (!cascadeCompleted || cascadeCompleted.length === 0) { cascadeProcessedRef.current = 0; } }, [cascadeCompleted]); // Filter tasks const filteredTasks = useMemo(() => { const matchesQuery = (t: Task): boolean => { if (!searchQuery) return true; const q = searchQuery.toLowerCase(); return t.title.toLowerCase().includes(q) || t.description.toLowerCase().includes(q) || t.task_id.toLowerCase().includes(q); }; const matchesFilter = (t: Task): boolean => { if (filterStatus !== 'all' && t.status !== filterStatus) return false; if (filterPriority !== 'all' && t.priority !== filterPriority) return false; return true; }; const filterTree = (items: Task[]): Task[] => { return items.reduce((acc, t) => { const childMatch = filterTree(t.children || []); const selfMatch = matchesQuery(t) && matchesFilter(t); if (selfMatch || childMatch.length > 0) { acc.push({ ...t, children: childMatch }); } return acc; }, []); }; // If searching, show matching tasks and their parents; otherwise just filter if (searchQuery) { const filterWithParents = (items: Task[]): Task[] => { return items.reduce((acc, t) => { const childMatch = filterWithParents(t.children || []); const selfMatch = matchesQuery(t) && matchesFilter(t); if (selfMatch || childMatch.length > 0) { acc.push({ ...t, children: selfMatch ? (t.children || []) : childMatch }); } return acc; }, []); }; return filterWithParents(tasks); } return filterTree(tasks); }, [tasks, searchQuery, filterStatus, filterPriority]); const { completedTasks, totalTasks, totalDuration } = useMemo(() => { const countAll = (items: Task[]): { completed: number; total: number; duration: number } => { let completed = 0, total = 0, duration = 0; for (const t of items) { total += 1; if (t.status === 'done') completed += 1; duration += (t.durationInHours || 0); if (t.children?.length) { const childStats = countAll(t.children); completed += childStats.completed; total += childStats.total; duration += childStats.duration; } } return { completed, total, duration }; }; const stats = countAll(tasks); return { completedTasks: stats.completed, totalTasks: stats.total, totalDuration: stats.duration }; }, [tasks]); const progress = totalTasks > 0 ? (completedTasks / totalTasks) * 100 : 0; const allDone = totalTasks > 0 && completedTasks === totalTasks; const allDoneTriggeredRef = useRef(false); const [showCongrats, setShowCongrats] = useState(false); useEffect(() => { if (allDone && !allDoneTriggeredRef.current) { allDoneTriggeredRef.current = true; setShowCongrats(true); } if (!allDone) { allDoneTriggeredRef.current = false; } }, [allDone, tasks]); const getAnimSrc = (): string => { if (!currentAnim) return ''; if (currentAnim.type === 'allDone') return SVGA_ALL_DONE; return SVGA_BY_LEVEL[String(Math.min(currentAnim.level, 2))] || SVGA_BY_LEVEL['2']; }; const isAllDone = currentAnim?.type === 'allDone'; const animMaxDuration = (!isAllDone && currentAnim && currentAnim.level >= 1) ? 3 : undefined; const addTaskParent = addingTask?.task.parent_id ? findParentTask(tasks, addingTask.task.parent_id) : null; // Drag handlers const handleDragStart = (task: Task) => { setDraggedTask(task); }; const handleDragOver = (e: React.DragEvent, task: Task) => { e.preventDefault(); // Only allow drop on siblings (same parent_id) if (draggedTask && draggedTask.id !== task.id && draggedTask.parent_id === task.parent_id) { setDragOverTask(task); } }; const handleDragEnd = () => { setDraggedTask(null); setDragOverTask(null); }; // Find the sibling list (children of the same parent) for a task const findSiblings = (allTasks: Task[], task: Task): Task[] | null => { // Root-level task if (!task.parent_id) return allTasks; // Search recursively for the parent's children list const findInTree = (items: Task[]): Task[] | null => { for (const t of items) { if (t.id === task.parent_id && t.children) return t.children; if (t.children) { const found = findInTree(t.children); if (found) return found; } } return null; }; return findInTree(allTasks); }; const handleDrop = (e: React.DragEvent, targetTask: Task) => { e.preventDefault(); if (!draggedTask || draggedTask.id === targetTask.id) return; // Only allow reordering within the same parent if (draggedTask.parent_id !== targetTask.parent_id) return; const siblings = findSiblings(tasks, targetTask); if (!siblings) return; const draggedIdx = siblings.findIndex(t => t.id === draggedTask.id); const targetIdx = siblings.findIndex(t => t.id === targetTask.id); if (draggedIdx === -1 || targetIdx === -1) return; const orders = siblings.map((t, i) => ({ id: t.id, sort_order: i })); orders.splice(draggedIdx, 1); const newTargetIdx = orders.findIndex(o => o.id === targetTask.id); orders.splice(newTargetIdx, 0, { id: draggedTask.id, sort_order: newTargetIdx }); const finalOrders = orders.map((o, i) => ({ id: o.id, sort_order: i })); onReorderTasks(finalOrders); setDraggedTask(null); setDragOverTask(null); }; return (

Your Goal

{goal}

{onMyPlans && ( )}
Progress {completedTasks} / {totalTasks} Tasks

Total estimated time: {totalDuration.toFixed(1)} hours

{/* Search & Filter Bar */}
{/* Search */}
setSearchQuery(e.target.value)} placeholder="搜索任务..." className="w-full pl-9 pr-3 py-2 text-sm bg-slate-50 dark:bg-slate-700 text-slate-800 dark:text-slate-100 border border-slate-200 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 transition-shadow" />
{/* Status filter */} {/* Priority filter */}

Your Action Plan

{filteredTasks.length === 0 ? (

没有匹配的任务

) : ( <>
Good Luck 😊
)}
{editingTask && ( )} {addingTask && ( )} {/* Task Complete Modal */} {completedTaskInfo && ( setCompletedTaskInfo(null)} /> )} {/* Congratulations Modal */} {showCongrats && createPortal(
setShowCongrats(false)} >
e.stopPropagation()} > {/* Confetti particles */}
{Array.from({ length: 40 }).map((_, i) => (
0.5 ? '50%' : '2px', }} /> ))}
{/* Trophy icon */}
🏆
{/* Title */}

🎉 恭喜完成所有任务!

{/* Subtitle */}

你已经完成了整个计划的所有任务

总计 {totalTasks} 个任务 · 预估 {totalDuration.toFixed(1)} 小时

{/* Close button */}
{/* Side sparkles */}
✨
✨
🌟
🌟
, document.body )}
); }; export default PlannerView;