Files
goal-planner/frontend/components/PlannerView.tsx
T
2026-11-02 17:15:39 +08:00

580 lines
27 KiB
TypeScript

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';
import { useLanguage } from '../i18n/LanguageContext';
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<string, string> = {
'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<PlannerViewProps> = ({ goal, tasks, planId, onToggleTask, onSaveTask, onDeleteTask, onAddTask, onStatusChange, onReorderTasks, onStartOver, onMyPlans, cascadeCompleted, onCascadeConsumed }) => {
const { t } = useLanguage();
const [editingTask, setEditingTask] = useState<Task | null>(null);
const [addingTask, setAddingTask] = useState<AddTaskState | null>(null);
const [animationQueue, setAnimationQueue] = useState<AnimationState[]>([]);
const [currentAnim, setCurrentAnim] = useState<AnimationState | null>(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<Task | null>(null);
const [dragOverTask, setDragOverTask] = useState<Task | null>(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<AnimationState, 'key'>) => {
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<Task[]>((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<Task[]>((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 (
<div className="space-y-6">
<div className="relative overflow-hidden bg-white dark:bg-slate-800 p-5 sm:p-7 rounded-2xl shadow-sm border border-slate-200/80 dark:border-slate-700">
<div className="pointer-events-none absolute -right-16 -top-16 h-40 w-40 rounded-full bg-emerald-100/70 dark:bg-emerald-900/20 blur-2xl" />
<div className="relative flex flex-col sm:flex-row justify-between items-start gap-4">
<div className="min-w-0">
<p className="text-xs font-semibold uppercase tracking-wider text-emerald-600 dark:text-emerald-400">{t('yourGoal')}</p>
<h2 className="text-xl sm:text-2xl font-bold text-slate-800 dark:text-slate-100 mt-1.5 break-words leading-snug">{goal}</h2>
</div>
<div className="flex items-center gap-2 flex-shrink-0">
{onMyPlans && (
<button
onClick={onMyPlans}
className="bg-slate-100 dark:bg-slate-700 text-slate-700 dark:text-slate-200 font-semibold px-3 sm:px-4 py-2.5 rounded-xl hover:bg-slate-200 dark:hover:bg-slate-600 transition-colors text-sm flex items-center gap-1.5"
>
<svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" d="M3.75 12h16.5m-16.5 3.75h16.5M3.75 19.5h16.5M5.625 4.5h12.75a1.875 1.875 0 010 3.75H5.625a1.875 1.875 0 010-3.75z" />
</svg>
<span className="hidden sm:inline">{t('myPlans')}</span>
</button>
)}
<button
onClick={onStartOver}
className="bg-emerald-600 text-white font-semibold px-3 sm:px-4 py-2.5 rounded-xl hover:bg-emerald-700 transition-colors text-sm shadow-sm shadow-emerald-200 dark:shadow-none"
>
{t('newPlan')}
</button>
</div>
</div>
<div className="relative mt-6">
<div className="flex justify-between items-center mb-2">
<span className="text-sm font-medium text-slate-600 dark:text-slate-300">{t('progress')}</span>
<span className="text-sm font-bold text-emerald-600 dark:text-emerald-400">{t('tasksCount', { done: completedTasks, total: totalTasks })}</span>
</div>
<div className="w-full bg-slate-100 dark:bg-slate-700 rounded-full h-2.5">
<div className="bg-gradient-to-r from-emerald-500 to-teal-400 h-2.5 rounded-full transition-all duration-500" style={{ width: `${progress}%` }}></div>
</div>
<p className="text-xs text-slate-500 dark:text-slate-400 mt-2.5 text-right">
{t('totalTime', { hours: totalDuration.toFixed(1) })}
</p>
</div>
</div>
{/* Search & Filter Bar */}
<div className="bg-white dark:bg-slate-800 p-3 sm:p-4 rounded-2xl shadow-sm border border-slate-200/80 dark:border-slate-700">
<div className="flex flex-col sm:flex-row gap-2 sm:gap-3">
{/* Search */}
<div className="relative flex-grow">
<svg xmlns="http://www.w3.org/2000/svg" className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" />
</svg>
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder={t('searchTasks')}
className="w-full pl-9 pr-3 py-2.5 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-xl focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500 transition-shadow"
/>
</div>
{/* Status filter */}
<select
value={filterStatus}
onChange={(e) => setFilterStatus(e.target.value as 'all' | TaskStatus)}
className="px-3 py-2.5 text-sm bg-slate-50 dark:bg-slate-700 text-slate-700 dark:text-slate-200 border border-slate-200 dark:border-slate-600 rounded-xl focus:ring-2 focus:ring-emerald-500"
>
<option value="all">{t('statusAll')}</option>
<option value="todo">{t('statusTodo')}</option>
<option value="in_progress">{t('statusDoing')}</option>
<option value="done">{t('statusDone')}</option>
</select>
{/* Priority filter */}
<select
value={filterPriority}
onChange={(e) => setFilterPriority(e.target.value as 'all' | 'low' | 'medium' | 'high')}
className="px-3 py-2.5 text-sm bg-slate-50 dark:bg-slate-700 text-slate-700 dark:text-slate-200 border border-slate-200 dark:border-slate-600 rounded-xl focus:ring-2 focus:ring-emerald-500"
>
<option value="all">{t('priorityAll')}</option>
<option value="high">{t('priorityHighFull')}</option>
<option value="medium">{t('priorityMediumFull')}</option>
<option value="low">{t('priorityLowFull')}</option>
</select>
</div>
</div>
<div>
<h3 className="text-lg sm:text-xl font-bold text-slate-800 dark:text-slate-100 mb-4">{t('actionPlan')}</h3>
{filteredTasks.length === 0 ? (
<div className="text-center py-16 text-slate-400 dark:text-slate-500 bg-white dark:bg-slate-800 rounded-2xl border border-dashed border-slate-200 dark:border-slate-700">
<svg xmlns="http://www.w3.org/2000/svg" className="h-12 w-12 mx-auto mb-3 opacity-50" fill="none" viewBox="0 0 24 24" strokeWidth={1} stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" />
</svg>
<p className="text-sm">{t('noMatch')}</p>
</div>
) : (
<>
<TaskList
tasks={filteredTasks}
onToggleTask={handleToggleTask}
onEditTask={handleEditTask}
onDeleteTask={onDeleteTask}
onAddChildTask={handleAddChildTask}
onAddSiblingTask={handleAddSiblingTask}
onStatusChange={onStatusChange}
onDragStart={handleDragStart}
onDragOver={handleDragOver}
onDrop={handleDrop}
onDragEnd={handleDragEnd}
dragOverTask={dragOverTask}
onChildTaskCompleted={handleChildTaskCompleted}
onParentTaskCompleted={handleParentTaskCompleted}
/>
<div className="flex items-center gap-3 mt-6 pt-2">
<div className="flex-1 h-px bg-gradient-to-r from-transparent via-slate-300 dark:via-slate-600 to-transparent" />
<span className="text-[11px] font-medium text-slate-400 dark:text-slate-500 tracking-wider select-none">{t('goodLuck')}</span>
<div className="flex-1 h-px bg-gradient-to-r from-transparent via-slate-300 dark:via-slate-600 to-transparent" />
</div>
</>
)}
</div>
{editingTask && (
<EditTaskModal
task={editingTask}
allTasks={tasks}
onSave={handleSaveTask}
onCancel={handleCancelEdit}
/>
)}
{addingTask && (
<AddTaskModal
mode={addingTask.mode}
siblingTask={addingTask.task}
parentTask={addTaskParent || undefined}
allTasks={tasks}
planId={planId}
onSave={handleSaveNewTask}
onCancel={handleCancelAdd}
/>
)}
{/* Task Complete Modal */}
{completedTaskInfo && (
<TaskCompleteModal
task={completedTaskInfo.task}
level={completedTaskInfo.level}
onClose={() => setCompletedTaskInfo(null)}
/>
)}
{/* Congratulations Modal */}
{showCongrats && createPortal(
<div
className="fixed inset-0 z-[100] flex items-center justify-center"
onClick={() => setShowCongrats(false)}
>
<div className="absolute inset-0 bg-black/50 backdrop-blur-sm" style={{ animation: 'fadeIn 0.3s ease-out' }} />
<div
className="relative text-center px-8 py-10 sm:px-12 sm:py-14"
style={{ animation: 'congratsBounce 0.6s ease-out' }}
onClick={(e) => e.stopPropagation()}
>
{/* Confetti particles */}
<div className="absolute inset-0 pointer-events-none overflow-hidden">
{Array.from({ length: 40 }).map((_, i) => (
<div
key={i}
className="absolute w-2 h-2 rounded-full"
style={{
left: `${Math.random() * 100}%`,
top: '-5%',
backgroundColor: ['#f59e0b', '#ef4444', '#3b82f6', '#10b981', '#8b5cf6', '#ec4899', '#f97316'][i % 7],
animation: `confettiFall ${1.5 + Math.random() * 2}s ease-in ${Math.random() * 0.5}s forwards`,
transform: `rotate(${Math.random() * 360}deg)`,
width: `${6 + Math.random() * 8}px`,
height: `${6 + Math.random() * 8}px`,
borderRadius: Math.random() > 0.5 ? '50%' : '2px',
}}
/>
))}
</div>
{/* Trophy icon */}
<div className="text-6xl sm:text-7xl mb-4" style={{ animation: 'trophySpin 1s ease-out' }}>
🏆
</div>
{/* Title */}
<h2 className="text-2xl sm:text-3xl font-extrabold text-white mb-3 drop-shadow-lg">
{t('congratsTitle')}
</h2>
{/* Subtitle */}
<p className="text-base sm:text-lg text-white/80 mb-2">
{t('congratsSub')}
</p>
<p className="text-sm text-white/60 mb-8">
{t('congratsStats', { total: totalTasks, hours: totalDuration.toFixed(1) })}
</p>
{/* Close button */}
<button
onClick={() => setShowCongrats(false)}
className="bg-gradient-to-r from-amber-400 to-yellow-400 text-amber-900 font-bold px-8 py-3 rounded-xl hover:from-amber-500 hover:to-yellow-500 transition-all shadow-lg shadow-amber-400/30 active:scale-95"
>
{t('congratsBtn')}
</button>
</div>
{/* Side sparkles */}
<div className="absolute top-1/4 left-[15%] text-3xl" style={{ animation: 'sparkle 1.5s ease-in-out infinite' }}>✨</div>
<div className="absolute top-1/3 right-[15%] text-3xl" style={{ animation: 'sparkle 1.5s ease-in-out infinite 0.5s' }}>✨</div>
<div className="absolute bottom-1/3 left-[20%] text-2xl" style={{ animation: 'sparkle 1.5s ease-in-out infinite 0.3s' }}>🌟</div>
<div className="absolute bottom-1/4 right-[20%] text-2xl" style={{ animation: 'sparkle 1.5s ease-in-out infinite 0.8s' }}>🌟</div>
</div>,
document.body
)}
<style>{`
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes congratsBounce {
0% { opacity: 0; transform: scale(0.3); }
50% { transform: scale(1.05); }
70% { transform: scale(0.95); }
100% { opacity: 1; transform: scale(1); }
}
@keyframes trophySpin {
0% { opacity: 0; transform: scale(0) rotate(-180deg); }
60% { transform: scale(1.2) rotate(10deg); }
80% { transform: scale(0.95) rotate(-5deg); }
100% { opacity: 1; transform: scale(1) rotate(0deg); }
}
@keyframes confettiFall {
0% { transform: translateY(0) rotate(0deg); opacity: 1; }
100% { transform: translateY(85vh) rotate(720deg); opacity: 0; }
}
@keyframes sparkle {
0%, 100% { opacity: 0.3; transform: scale(0.8); }
50% { opacity: 1; transform: scale(1.3); }
}
`}</style>
</div>
);
};
export default PlannerView;