diff --git a/frontend b/frontend deleted file mode 160000 index 98facaf..0000000 --- a/frontend +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 98facaf720f880740e68615fbc2938d7f99dcc35 diff --git a/frontend/.gitignore b/frontend/.gitignore new file mode 100644 index 0000000..d8535c5 --- /dev/null +++ b/frontend/.gitignore @@ -0,0 +1,6 @@ +node_modules/ +dist-ssr/ +.vite/ +*.local +# Logs +*.log \ No newline at end of file diff --git a/frontend/App.tsx b/frontend/App.tsx new file mode 100644 index 0000000..cc500c3 --- /dev/null +++ b/frontend/App.tsx @@ -0,0 +1,508 @@ +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('landing'); + const [currentPlan, setCurrentPlan] = useState(null); + const [goal, setGoal] = useState(''); + const [error, setError] = useState(null); + const [currentUser, setCurrentUser] = useState(null); + const [isLoading, setIsLoading] = useState(true); + const [cascadeCompleted, setCascadeCompleted] = useState([]); + 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(); + 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(); + 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 ; + case 'login': + return setView('signup')} />; + case 'signup': + return setView('login')} />; + case 'input': + if (!currentUser) { setView('login'); return null; } + return ; + case 'planner': + if (!currentUser || !currentPlan) { setView('login'); return null; } + return ( + { + cascadeConsumedRef.current += 1; + if (cascadeConsumedRef.current >= cascadeCompleted.length) { + setCascadeCompleted([]); + } + }} + /> + ); + case 'history': + if (!currentUser) { setView('login'); return null; } + return ( + setView('input')} + /> + ); + case 'error': + return ( +
+ Oops! Something went wrong. +

{error}

+ +
+ ); + default: + return null; + } + }; + + if (isLoading) { + return ; + } + + return ( + +
+
setView('login')} + onSignUpClick={() => setView('signup')} + onLogoClick={handleResetToLanding} + onMyPlans={handleMyPlans} + xpGain={lastXpGain} + levelUpInfo={levelUpInfo} + darkMode={darkMode} + onToggleDarkMode={() => setDarkMode(!darkMode)} + /> +
+
+ {renderContent()} +
+
+ {view === 'landing' &&
} + {view === 'loading' && !genProgress && } + {view === 'loading' && genProgress && ( + + )} +
+
+ ); +}; + +export default App; diff --git a/frontend/Demo Video.mp4 b/frontend/Demo Video.mp4 new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/frontend/Demo Video.mp4 @@ -0,0 +1 @@ + diff --git a/frontend/README.md b/frontend/README.md new file mode 100644 index 0000000..d12af09 --- /dev/null +++ b/frontend/README.md @@ -0,0 +1,152 @@ +# Smart Task Planner + +[![React](https://img.shields.io/badge/React-19-blue?style=for-the-badge&logo=react)](https://react.dev/) +[![TypeScript](https://img.shields.io/badge/TypeScript-5.x-blue?style=for-the-badge&logo=typescript)](https://www.typescriptlang.org/) +[![Vercel](https://img.shields.io/badge/Vercel-Edge-black?style=for-the-badge&logo=vercel)](https://vercel.com/docs/functions/edge-functions) +[![Tailwind CSS](https://img.shields.io/badge/Tailwind_CSS-3.x-38B2AC?style=for-the-badge&logo=tailwind-css)](https://tailwindcss.com/) + +An intelligent web application that turns your ambitious goals into actionable, step-by-step plans using the power of Google's Gemini AI. + +--- + +## Live & Demo + +Experience the live application and see how your goals are transformed into a manageable project plan in seconds. + +Live link: +**[https://goal-planner-liart.vercel.app/](https://goal-planner-liart.vercel.app/)** + +Demo Video: +**[https://drive.google.com/file/d/1SefadZbCxVUL7FB8phFoG5xJ3eoPevrj/view?usp=drive_link](https://drive.google.com/file/d/1SefadZbCxVUL7FB8phFoG5xJ3eoPevrj/view?usp=drive_link)** + + +--- + + +## About The Project + +Smart Task Planner bridges the gap between vision and execution. It leverages Google's advanced Gemini API to analyze a user's high-level goal and intelligently generate a comprehensive roadmap. The result is a detailed list of tasks, complete with descriptions, time estimates, and dependencies, giving users a clear and actionable path to success. + +This project was built to demonstrate a modern, secure, and performant full-stack application using a serverless backend architecture, ensuring both a great user experience and robust security. + +--- +## Application Screenshots + + +**Landing Page:** +image + + + +**Planner View:** +image + + + +**Task Editing Modal:** +image + + + +--- + +## Core Features & Application Logic + +This application integrates several key technical features to deliver a seamless and powerful planning experience. + +### AI-Powered Plan Generation +- **Logic**: The core of the application resides in the `/api/generate-plan.ts` Vercel Edge Function. When a user submits a goal, the frontend sends a request to this secure backend endpoint. The function then constructs a detailed prompt, instructing the Gemini AI to act as an expert project manager. +- **Structured Output**: To ensure a reliable and predictable response from the AI, the backend enforces a strict JSON schema via the `responseSchema` configuration. This forces the Gemini model to return a perfectly formatted JSON array of tasks, which the frontend can parse and render without requiring complex data manipulation. + +### Dynamic Task Dependency System +- **Logic**: The AI generates a `dependencies` array for each task (e.g., `["task-1", "task-3"]`). On the frontend, the `TaskList` component maintains a `Set` of completed task IDs for efficient lookups. +- **User Experience**: Before rendering each task, the application checks if all of its prerequisite tasks have been completed. A task is visually "locked" (greyed out and non-interactive) if any of its dependencies are not yet met. Once all dependencies are finished, the task automatically unlocks, creating an intuitive and logical workflow for the user. + +### Interactive Progress Tracking +- **Logic**: The `PlannerView` component uses React's `useMemo` hook to efficiently calculate progress metrics whenever the `tasks` array changes. It counts completed tasks versus the total and sums the `durationInHours` for all tasks to provide a total project estimate. +- **User Experience**: Users get immediate visual feedback via a dynamic progress bar, a "X / Y Tasks" counter, and a total estimated project duration, keeping them motivated and informed. + +### Secure Serverless Architecture +- **Logic**: The frontend **never** communicates directly with the Gemini API. All API calls are proxied through the `/api/generate-plan` serverless function. The `API_KEY` is stored securely as an environment variable on Vercel's servers and is never exposed to the client's browser. This is a critical security best practice that prevents key leakage. + +### Simulated Authentication Flow +- **Logic**: The application uses React state to manage a `currentUser` object, simulating a complete login/signup flow. Views are conditionally rendered based on whether a user object exists in the state, protecting the main planner view from unauthenticated access. This demonstrates state management for a typical user-gated application. + +--- + +## Tech Stack + +This project is built with a modern web development stack: + +- **Frontend:** + - **React**: For building the component-based user interface. + - **TypeScript**: For static typing, improved code quality, and developer experience. + - **Tailwind CSS**: For rapid, utility-first styling and a responsive design. +- **Backend (Serverless):** + - **Vercel Edge Functions**: To create a secure, scalable backend proxy for API calls. +- **Core API:** + - **Google Gemini API**: The AI engine for intelligent plan generation. +- **Deployment:** + - **Vercel**: For seamless, Git-based deployment and hosting. + +--- + +## Local Development Setup + +To get a local copy up and running, follow these steps. + +### Prerequisites + +- Node.js (v18 or later recommended) +- npm, yarn, or pnpm +- A Google Gemini API Key. You can get one for free from [Google AI Studio](https://makersuite.google.com/). + +### Installation & Configuration + +1. **Clone the repository:** + ```sh + git clone https://github.com/AbhinayManikanti/goal-planner.git + cd goal-planner + ``` + +2. **Install the Vercel CLI:** + ```sh + npm install -g vercel + ``` + +3. **Create an environment file:** + Create a new file named `.env` in the root of your project and add your Gemini API key: + ``` + API_KEY="YOUR_GEMINI_API_KEY_HERE" + ``` + +4. **Run the development server:** + Use the Vercel CLI to run the project. This is the best method as it correctly serves both the React frontend and the serverless function in the `/api` directory. + ```sh + vercel dev + ``` + +Your application should now be running at `http://localhost:3000`. + +--- + +## Deployment + +This application is optimized for deployment on [Vercel](https://vercel.com/). + +1. Push your code to a Git repository (GitHub, GitLab, etc.). +2. Import the repository into Vercel. +3. **Configure the Environment Variable (Crucial Step):** + - In your Vercel project settings, navigate to **Settings > Environment Variables**. + - Add a variable with the name `API_KEY` and paste your Gemini API key as the value. +4. Deploy. Vercel will automatically handle the build process for both the frontend and the serverless function. + +--- + +## Author + +**Abhinay Manikanti** + +- **GitHub**: [@AbhinayManikanti](https://github.com/abhinay-07) +- **LinkedIn**: [Abhinay Manikanti](https://www.linkedin.com/in/abhinay-manikanti) +- **Project Link**: [https://github.com/AbhinayManikanti/goal-planner](https://github.com/AbhinayManikanti/goal-planner) diff --git a/frontend/api/generate-plan.ts b/frontend/api/generate-plan.ts new file mode 100644 index 0000000..e39000a --- /dev/null +++ b/frontend/api/generate-plan.ts @@ -0,0 +1,86 @@ +// This file should be placed in the `api` directory (e.g., `api/generate-plan.ts`) +// Vercel automatically deploys files in the /api directory as Serverless Functions. + +// Using the Vercel Edge-compatible Request and Response +export default async function handler(request: Request) { + if (request.method !== 'POST') { + return new Response(`Method ${request.method} Not Allowed`, { status: 405, headers: { 'Allow': 'POST' } }); + } + + try { + const { goal } = await request.json(); + + if (!goal || typeof goal !== 'string') { + return new Response(JSON.stringify({ error: 'Goal is required and must be a string.' }), { status: 400, headers: { 'Content-Type': 'application/json' } }); + } + + const API_KEY = process.env.API_KEY; + if (!API_KEY) { + console.error("API_KEY environment variable not set."); + return new Response(JSON.stringify({ error: 'Server configuration error.' }), { status: 500, headers: { 'Content-Type': 'application/json' } }); + } + + const prompt = `You are an expert project manager. Your task is to take a user's goal and break it down into a detailed, step-by-step plan. Create a list of tasks required to achieve the following goal. For each task, provide a unique ID (a short, URL-friendly slug), a clear title, a concise description, an estimated duration in hours to complete the task, and list the IDs of any tasks that must be completed before this one can start (dependencies). Ensure the tasks are in a logical order. The final output must be a JSON array of these tasks. + +Goal: "${goal}"`; + + const generatePlanSchema = { + type: "ARRAY", + items: { + type: "OBJECT", + properties: { + id: { type: "STRING", description: 'A unique identifier for the task, preferably a short, URL-friendly slug (e.g., "setup-project").' }, + title: { type: "STRING", description: 'A short, clear title for the task.' }, + description: { type: "STRING", description: 'A detailed description of what needs to be done for this task.' }, + dependencies: { type: "ARRAY", items: { type: "STRING" }, description: 'An array of task IDs that this task depends on. Leave empty if there are no dependencies.' }, + durationInHours: { type: "NUMBER", description: 'The estimated number of hours required to complete this task. Can be a decimal for partial hours.' } + }, + required: ['id', 'title', 'description', 'dependencies', 'durationInHours'], + }, + }; + + const GEMINI_API_ENDPOINT = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${API_KEY}`; + + const geminiReqBody = { + contents: [{ parts: [{ text: prompt }] }], + generationConfig: { + responseMimeType: "application/json", + responseSchema: generatePlanSchema, + } + }; + + const geminiRes = await fetch(GEMINI_API_ENDPOINT, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(geminiReqBody), + }); + + if (!geminiRes.ok) { + const errorBody = await geminiRes.text(); + console.error("Gemini API Error:", geminiRes.status, errorBody); + return new Response(JSON.stringify({ error: `Gemini API request failed with status ${geminiRes.status}` }), { status: 502, headers: { 'Content-Type': 'application/json' } }); + } + + const geminiData = await geminiRes.json(); + const jsonText = geminiData?.candidates?.[0]?.content?.parts?.[0]?.text; + + if (!jsonText) { + console.error("Invalid response structure from Gemini API:", geminiData); + return new Response(JSON.stringify({ error: "Failed to parse the plan from the AI's response." }), { status: 502, headers: { 'Content-Type': 'application/json' } }); + } + + // The response from the REST API is a string, so we return it directly. + // The client-side service will parse it. + return new Response(jsonText, { status: 200, headers: { 'Content-Type': 'application/json' } }); + + } catch (error) { + console.error('Error in generate-plan handler:', error); + const message = error instanceof Error ? error.message : 'An internal server error occurred.'; + return new Response(JSON.stringify({ error: message }), { status: 500, headers: { 'Content-Type': 'application/json' } }); + } +} + +// Vercel specific configuration to ensure this runs on a Node.js runtime. +export const config = { + runtime: 'edge', +}; diff --git a/frontend/components/3d/HeroAnimation.tsx b/frontend/components/3d/HeroAnimation.tsx new file mode 100644 index 0000000..42f2d2e --- /dev/null +++ b/frontend/components/3d/HeroAnimation.tsx @@ -0,0 +1,44 @@ +import React, { useState, useRef } from 'react'; +import { Canvas, useFrame } from '@react-three/fiber'; +import { Points, PointMaterial } from '@react-three/drei'; +import * as random from 'maath/random'; +import type { Points as PointsType } from 'three'; + +const Starfield: React.FC = () => { + const ref = useRef(null); + const [sphere] = useState(() => random.inSphere(new Float32Array(5000), { radius: 1.5 })); + + useFrame((state, delta) => { + if (ref.current) { + ref.current.rotation.x -= delta / 10; + ref.current.rotation.y -= delta / 15; + } + }); + + return ( + // FIX: Replaced with a rotation property on the component. + // This resolves the "Property 'group' does not exist on type 'JSX.IntrinsicElements'" error + // by avoiding the problematic element while keeping the same visual transformation. + + + + ); +}; + +const HeroAnimation: React.FC = () => { + return ( + + + + + + ); +}; + +export default HeroAnimation; \ No newline at end of file diff --git a/frontend/components/AddTaskModal.tsx b/frontend/components/AddTaskModal.tsx new file mode 100644 index 0000000..360b31a --- /dev/null +++ b/frontend/components/AddTaskModal.tsx @@ -0,0 +1,298 @@ +import React, { useState, useEffect, useRef } from 'react'; +import { Task, TaskPriority } from '../types'; + +interface AddTaskModalProps { + mode: 'child' | 'sibling'; + parentTask?: Task; + siblingTask: Task; + allTasks: Task[]; + planId: number; + onSave: (data: { + task_id: string; + title: string; + description: string; + parent_id?: number | null; + dependencies: string[]; + durationInHours: number; + priority?: string; + dueDate?: string | null; + sortOrder?: number; + }) => void; + onCancel: () => void; +} + +const AddTaskModal: React.FC = ({ mode, parentTask, siblingTask, allTasks, planId, onSave, onCancel }) => { + const [title, setTitle] = useState(''); + const [description, setDescription] = useState(''); + const [taskId, setTaskId] = useState(''); + const [selectedDeps, setSelectedDeps] = useState([]); + const [duration, setDuration] = useState('0'); + const [priority, setPriority] = useState('medium'); + const [dueDate, setDueDate] = useState(''); + const [dropdownOpen, setDropdownOpen] = useState(false); + const dropdownRef = useRef(null); + + const flattenTasksWithDepth = (items: Task[], depth: number = 0): { task: Task; depth: number }[] => { + const result: { task: Task; depth: number }[] = []; + for (const t of items) { + result.push({ task: t, depth }); + if (t.children?.length) { + result.push(...flattenTasksWithDepth(t.children, depth + 1)); + } + } + return result; + }; + + const availableTasks = flattenTasksWithDepth(allTasks); + + const toggleDep = (depTaskId: string) => { + setSelectedDeps(prev => + prev.includes(depTaskId) + ? prev.filter(id => id !== depTaskId) + : [...prev, depTaskId] + ); + }; + + const handleSave = (e: React.FormEvent) => { + e.preventDefault(); + const parentId = mode === 'child' ? siblingTask.id : siblingTask.parent_id; + onSave({ + task_id: taskId || `task-${Date.now()}`, + title, + description, + parent_id: parentId, + dependencies: selectedDeps, + durationInHours: parseFloat(duration) || 0, + priority, + dueDate: dueDate || null, + }); + }; + + useEffect(() => { + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape') onCancel(); + }; + window.addEventListener('keydown', handleKeyDown); + return () => window.removeEventListener('keydown', handleKeyDown); + }, [onCancel]); + + useEffect(() => { + const handleClickOutside = (event: MouseEvent) => { + if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) { + setDropdownOpen(false); + } + }; + document.addEventListener('mousedown', handleClickOutside); + return () => document.removeEventListener('mousedown', handleClickOutside); + }, []); + + const modeLabel = mode === 'child' ? '子任务' : '同级任务'; + const parentLabel = mode === 'child' ? siblingTask.title : (parentTask?.title || '根级'); + + return ( +
+
e.stopPropagation()} + > + + +

添加{modeLabel}

+

+ {mode === 'child' ? `在 "${siblingTask.title}" 下添加子任务` : `与 "${siblingTask.title}" 同级添加任务`} + · + 归属于 {parentLabel} +

+ +
+
+ + setTaskId(e.target.value)} + className="w-full p-2 bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 border border-slate-300 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 transition-shadow" + placeholder="如: phase-2-design(留空自动生成)" + /> +
+
+ + setTitle(e.target.value)} + className="w-full p-2 bg-white dark:bg-slate-700 text-slate-900 dark:text-slate-100 border border-slate-300 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-green-500 focus:border-green-500 transition-shadow" + required + placeholder="任务标题" + /> +
+
+ +