Improve tasks

This commit is contained in:
Louis Knight-Webb
2025-06-17 20:25:52 -04:00
parent 79a45b141f
commit 81c78fa072

View File

@@ -1,217 +1,245 @@
import { useState, useEffect } from 'react' import { useState, useEffect } from "react";
import { useParams, useNavigate } from 'react-router-dom' import { useParams, useNavigate } from "react-router-dom";
import { Button } from '@/components/ui/button' import { Button } from "@/components/ui/button";
import { Card, CardContent } from '@/components/ui/card' import { Card, CardContent } from "@/components/ui/card";
import { ArrowLeft, Plus } from 'lucide-react' import { ArrowLeft, Plus } from "lucide-react";
import { makeRequest } from '@/lib/api' import { makeRequest } from "@/lib/api";
import { TaskCreateDialog } from '@/components/tasks/TaskCreateDialog' import { TaskCreateDialog } from "@/components/tasks/TaskCreateDialog";
import { TaskEditDialog } from '@/components/tasks/TaskEditDialog' import { TaskEditDialog } from "@/components/tasks/TaskEditDialog";
import { TaskKanbanBoard } from '@/components/tasks/TaskKanbanBoard' import { TaskKanbanBoard } from "@/components/tasks/TaskKanbanBoard";
import type { TaskStatus, TaskWithAttemptStatus } from 'shared/types' import type { TaskStatus, TaskWithAttemptStatus } from "shared/types";
import type { DragEndEvent } from '@/components/ui/shadcn-io/kanban' import type { DragEndEvent } from "@/components/ui/shadcn-io/kanban";
type Task = TaskWithAttemptStatus type Task = TaskWithAttemptStatus;
interface Project { interface Project {
id: string id: string;
name: string name: string;
owner_id: string owner_id: string;
created_at: string created_at: string;
updated_at: string updated_at: string;
} }
interface ApiResponse<T> { interface ApiResponse<T> {
success: boolean success: boolean;
data: T | null data: T | null;
message: string | null message: string | null;
} }
export function ProjectTasks() { export function ProjectTasks() {
const { projectId } = useParams<{ projectId: string }>() const { projectId } = useParams<{ projectId: string }>();
const navigate = useNavigate() const navigate = useNavigate();
const [tasks, setTasks] = useState<Task[]>([]) const [tasks, setTasks] = useState<Task[]>([]);
const [project, setProject] = useState<Project | null>(null) const [project, setProject] = useState<Project | null>(null);
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null);
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false) const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
const [editingTask, setEditingTask] = useState<Task | null>(null) const [editingTask, setEditingTask] = useState<Task | null>(null);
const [isEditDialogOpen, setIsEditDialogOpen] = useState(false) const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
useEffect(() => { useEffect(() => {
if (projectId) { if (projectId) {
fetchProject() fetchProject();
fetchTasks() fetchTasks();
// Set up polling to refresh tasks every 5 seconds
const interval = setInterval(() => {
fetchTasks(true); // Skip loading spinner for polling
}, 2000);
// Cleanup interval on unmount
return () => clearInterval(interval);
} }
}, [projectId]) }, [projectId]);
const fetchProject = async () => { const fetchProject = async () => {
try { try {
const response = await makeRequest(`/api/projects/${projectId}`) const response = await makeRequest(`/api/projects/${projectId}`);
if (response.ok) { if (response.ok) {
const result: ApiResponse<Project> = await response.json() const result: ApiResponse<Project> = await response.json();
if (result.success && result.data) { if (result.success && result.data) {
setProject(result.data) setProject(result.data);
} }
} else if (response.status === 404) { } else if (response.status === 404) {
setError('Project not found') setError("Project not found");
navigate('/projects') navigate("/projects");
} }
} catch (err) { } catch (err) {
setError('Failed to load project') setError("Failed to load project");
}
} }
};
const fetchTasks = async () => { const fetchTasks = async (skipLoading = false) => {
try { try {
setLoading(true) if (!skipLoading) {
const response = await makeRequest(`/api/projects/${projectId}/tasks`) setLoading(true);
}
const response = await makeRequest(`/api/projects/${projectId}/tasks`);
if (response.ok) { if (response.ok) {
const result: ApiResponse<Task[]> = await response.json() const result: ApiResponse<Task[]> = await response.json();
if (result.success && result.data) { if (result.success && result.data) {
setTasks(result.data) // Only update if data has actually changed
setTasks(prevTasks => {
const newTasks = result.data!;
if (JSON.stringify(prevTasks) === JSON.stringify(newTasks)) {
return prevTasks; // Return same reference to prevent re-render
}
return newTasks;
});
} }
} else { } else {
setError('Failed to load tasks') setError("Failed to load tasks");
} }
} catch (err) { } catch (err) {
setError('Failed to load tasks') setError("Failed to load tasks");
} finally { } finally {
setLoading(false) if (!skipLoading) {
setLoading(false);
} }
} }
};
const handleCreateTask = async (title: string, description: string) => { const handleCreateTask = async (title: string, description: string) => {
try { try {
const response = await makeRequest(`/api/projects/${projectId}/tasks`, { const response = await makeRequest(`/api/projects/${projectId}/tasks`, {
method: 'POST', method: "POST",
body: JSON.stringify({ body: JSON.stringify({
project_id: projectId, project_id: projectId,
title, title,
description: description || null description: description || null,
}) }),
}) });
if (response.ok) { if (response.ok) {
await fetchTasks() await fetchTasks();
} else { } else {
setError('Failed to create task') setError("Failed to create task");
} }
} catch (err) { } catch (err) {
setError('Failed to create task') setError("Failed to create task");
}
} }
};
const handleUpdateTask = async (title: string, description: string, status: TaskStatus) => { const handleUpdateTask = async (
if (!editingTask) return title: string,
description: string,
status: TaskStatus
) => {
if (!editingTask) return;
try { try {
const response = await makeRequest(`/api/projects/${projectId}/tasks/${editingTask.id}`, { const response = await makeRequest(
method: 'PUT', `/api/projects/${projectId}/tasks/${editingTask.id}`,
{
method: "PUT",
body: JSON.stringify({ body: JSON.stringify({
title, title,
description: description || null, description: description || null,
status status,
}) }),
}) }
);
if (response.ok) { if (response.ok) {
await fetchTasks() await fetchTasks();
setEditingTask(null) setEditingTask(null);
} else { } else {
setError('Failed to update task') setError("Failed to update task");
} }
} catch (err) { } catch (err) {
setError('Failed to update task') setError("Failed to update task");
}
} }
};
const handleDeleteTask = async (taskId: string) => { const handleDeleteTask = async (taskId: string) => {
if (!confirm('Are you sure you want to delete this task?')) return if (!confirm("Are you sure you want to delete this task?")) return;
try { try {
const response = await makeRequest(`/api/projects/${projectId}/tasks/${taskId}`, { const response = await makeRequest(
method: 'DELETE', `/api/projects/${projectId}/tasks/${taskId}`,
}) {
method: "DELETE",
}
);
if (response.ok) { if (response.ok) {
await fetchTasks() await fetchTasks();
} else { } else {
setError('Failed to delete task') setError("Failed to delete task");
} }
} catch (err) { } catch (err) {
setError('Failed to delete task') setError("Failed to delete task");
}
} }
};
const handleEditTask = (task: Task) => { const handleEditTask = (task: Task) => {
setEditingTask(task) setEditingTask(task);
setIsEditDialogOpen(true) setIsEditDialogOpen(true);
} };
const handleViewTaskDetails = (task: Task) => { const handleViewTaskDetails = (task: Task) => {
navigate(`/projects/${projectId}/tasks/${task.id}`) navigate(`/projects/${projectId}/tasks/${task.id}`);
} };
const handleDragEnd = async (event: DragEndEvent) => { const handleDragEnd = async (event: DragEndEvent) => {
const { active, over } = event const { active, over } = event;
if (!over || !active.data.current) return if (!over || !active.data.current) return;
const taskId = active.id as string const taskId = active.id as string;
const newStatus = over.id as Task['status'] const newStatus = over.id as Task["status"];
const task = tasks.find(t => t.id === taskId) const task = tasks.find((t) => t.id === taskId);
if (!task || task.status === newStatus) return if (!task || task.status === newStatus) return;
// Optimistically update the UI immediately // Optimistically update the UI immediately
const previousStatus = task.status const previousStatus = task.status;
setTasks(prev => prev.map(t => setTasks((prev) =>
t.id === taskId ? { ...t, status: newStatus } : t prev.map((t) => (t.id === taskId ? { ...t, status: newStatus } : t))
)) );
try { try {
const response = await makeRequest(`/api/projects/${projectId}/tasks/${taskId}`, { const response = await makeRequest(
method: 'PUT', `/api/projects/${projectId}/tasks/${taskId}`,
{
method: "PUT",
body: JSON.stringify({ body: JSON.stringify({
title: task.title, title: task.title,
description: task.description, description: task.description,
status: newStatus status: newStatus,
}) }),
}) }
);
if (!response.ok) { if (!response.ok) {
// Revert the optimistic update if the API call failed // Revert the optimistic update if the API call failed
setTasks(prev => prev.map(t => setTasks((prev) =>
prev.map((t) =>
t.id === taskId ? { ...t, status: previousStatus } : t t.id === taskId ? { ...t, status: previousStatus } : t
)) )
setError('Failed to update task status') );
setError("Failed to update task status");
} }
} catch (err) { } catch (err) {
// Revert the optimistic update if the API call failed // Revert the optimistic update if the API call failed
setTasks(prev => prev.map(t => setTasks((prev) =>
prev.map((t) =>
t.id === taskId ? { ...t, status: previousStatus } : t t.id === taskId ? { ...t, status: previousStatus } : t
)) )
setError('Failed to update task status') );
setError("Failed to update task status");
} }
} };
if (loading) { if (loading) {
return <div className="text-center py-8">Loading tasks...</div> return <div className="text-center py-8">Loading tasks...</div>;
} }
if (error) { if (error) {
return <div className="text-center py-8 text-red-600">{error}</div> return <div className="text-center py-8 text-red-600">{error}</div>;
} }
return ( return (
@@ -222,7 +250,7 @@ export function ProjectTasks() {
<Button <Button
variant="ghost" variant="ghost"
size="sm" size="sm"
onClick={() => navigate('/projects')} onClick={() => navigate("/projects")}
className="flex items-center" className="flex items-center"
> >
<ArrowLeft className="h-4 w-4 mr-2" /> <ArrowLeft className="h-4 w-4 mr-2" />
@@ -230,7 +258,7 @@ export function ProjectTasks() {
</Button> </Button>
<div> <div>
<h1 className="text-2xl font-bold"> <h1 className="text-2xl font-bold">
{project?.name || 'Project'} Tasks {project?.name || "Project"} Tasks
</h1> </h1>
<p className="text-muted-foreground"> <p className="text-muted-foreground">
Manage tasks for this project Manage tasks for this project
@@ -254,7 +282,9 @@ export function ProjectTasks() {
{tasks.length === 0 ? ( {tasks.length === 0 ? (
<Card> <Card>
<CardContent className="text-center py-8"> <CardContent className="text-center py-8">
<p className="text-muted-foreground">No tasks found for this project.</p> <p className="text-muted-foreground">
No tasks found for this project.
</p>
<Button <Button
className="mt-4" className="mt-4"
onClick={() => setIsCreateDialogOpen(true)} onClick={() => setIsCreateDialogOpen(true)}
@@ -280,8 +310,6 @@ export function ProjectTasks() {
task={editingTask} task={editingTask}
onUpdateTask={handleUpdateTask} onUpdateTask={handleUpdateTask}
/> />
</div> </div>
) );
} }