Initial commit

This commit is contained in:
UltraLionFr
2026-01-02 17:52:07 +01:00
parent b29bd25170
commit 972bafc4e0
36 changed files with 8742 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
"use client";
import { SessionProvider } from "next-auth/react";
import { ReactNode } from "react";
interface AuthProviderProps {
children: ReactNode;
}
export default function AuthProvider({ children }: AuthProviderProps) {
return <SessionProvider>{children}</SessionProvider>;
}
+83
View File
@@ -0,0 +1,83 @@
"use client";
import { QuestionMode, SessionAnswer } from "@/types";
import { motion } from "framer-motion";
interface CompletePageProps {
answers: SessionAnswer[];
mode: QuestionMode;
onGoHome: () => void;
onGoToKanban: () => void;
onExport: () => void;
}
export default function CompletePage({
answers,
mode,
onGoHome,
onGoToKanban,
onExport,
}: CompletePageProps) {
const answeredCount = answers.filter((a) => a.answer.trim()).length;
return (
<div className="min-h-screen flex flex-col items-center justify-center p-4">
<motion.div
initial={{ opacity: 0, scale: 0.9 }}
animate={{ opacity: 1, scale: 1 }}
transition={{ duration: 0.5 }}
className="text-center max-w-md w-full"
>
<motion.div
initial={{ scale: 0 }}
animate={{ scale: 1 }}
transition={{ type: "spring", duration: 0.6, delay: 0.2 }}
className="text-7xl mb-6"
>
{mode === "crisis" ? "💪" : "✨"}
</motion.div>
<h1 className="text-3xl font-bold text-white mb-2">
{mode === "crisis"
? "Tu as fait le plus dur"
: "Session terminée !"}
</h1>
<p className="text-gray-400 mb-8">
{answeredCount} réponse{answeredCount > 1 ? "s" : ""}{" "}
enregistrée
{answeredCount > 1 ? "s" : ""}
</p>
<div className="space-y-3">
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
onClick={onExport}
className="w-full bg-green-500 hover:bg-green-600 text-white font-bold py-3 px-6 rounded-xl transition-colors"
>
📥 Exporter en Markdown
</motion.button>
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
onClick={onGoToKanban}
className="w-full bg-indigo-500 hover:bg-indigo-600 text-white font-bold py-3 px-6 rounded-xl transition-colors"
>
📋 Voir le Kanban
</motion.button>
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
onClick={onGoHome}
className="w-full bg-gray-700 hover:bg-gray-600 text-white font-semibold py-3 px-6 rounded-xl transition-colors"
>
🏠 Retour à l&apos;accueil
</motion.button>
</div>
</motion.div>
</div>
);
}
+59
View File
@@ -0,0 +1,59 @@
"use client";
import { AnimatePresence, motion } from "framer-motion";
import { useEffect, useState } from "react";
interface ConfettiProps {
show: boolean;
}
export default function Confetti({ show }: ConfettiProps) {
const [particles, setParticles] = useState<number[]>([]);
useEffect(() => {
if (show) {
setParticles(Array.from({ length: 50 }, (_, i) => i));
} else {
setParticles([]);
}
}, [show]);
return (
<AnimatePresence>
{show && (
<div className="fixed inset-0 pointer-events-none z-50 overflow-hidden">
{particles.map((i) => (
<motion.div
key={i}
initial={{
x: Math.random() * window.innerWidth,
y: -20,
rotate: 0,
scale: Math.random() * 0.5 + 0.5,
}}
animate={{
y: window.innerHeight + 20,
rotate: Math.random() * 720 - 360,
}}
exit={{ opacity: 0 }}
transition={{
duration: Math.random() * 2 + 2,
ease: "linear",
}}
className="absolute w-3 h-3 rounded-sm"
style={{
backgroundColor: [
"#f43f5e",
"#8b5cf6",
"#3b82f6",
"#10b981",
"#f59e0b",
][Math.floor(Math.random() * 5)],
}}
/>
))}
</div>
)}
</AnimatePresence>
);
}
+75
View File
@@ -0,0 +1,75 @@
"use client";
import { AnimatePresence, motion } from "framer-motion";
interface ConfirmModalProps {
isOpen: boolean;
title: string;
message: string;
confirmText?: string;
cancelText?: string;
confirmColor?: "red" | "green" | "blue";
onConfirm: () => void;
onCancel: () => void;
}
export default function ConfirmModal({
isOpen,
title,
message,
confirmText = "Confirmer",
cancelText = "Annuler",
confirmColor = "red",
onConfirm,
onCancel,
}: ConfirmModalProps) {
const colorClasses = {
red: "bg-red-500 hover:bg-red-600",
green: "bg-green-500 hover:bg-green-600",
blue: "bg-blue-500 hover:bg-blue-600",
}[confirmColor];
return (
<AnimatePresence>
{isOpen && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
className="fixed inset-0 bg-black/60 backdrop-blur-sm z-200 flex items-center justify-center p-4"
onClick={onCancel}
>
<motion.div
initial={{ opacity: 0, scale: 0.9, y: 20 }}
animate={{ opacity: 1, scale: 1, y: 0 }}
exit={{ opacity: 0, scale: 0.9, y: 20 }}
transition={{ type: "spring", duration: 0.3 }}
className="bg-gray-800 rounded-2xl p-6 max-w-sm w-full shadow-2xl border border-gray-700"
onClick={(e) => e.stopPropagation()}
>
<h3 className="text-xl font-bold text-white mb-2">
{title}
</h3>
<p className="text-gray-400 mb-6">{message}</p>
<div className="flex gap-3">
<button
onClick={onCancel}
className="flex-1 bg-gray-700 hover:bg-gray-600 text-white font-semibold py-3 px-4 rounded-xl transition-colors"
>
{cancelText}
</button>
<button
onClick={onConfirm}
className={`flex-1 ${colorClasses} text-white font-semibold py-3 px-4 rounded-xl transition-colors`}
>
{confirmText}
</button>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
);
}
+88
View File
@@ -0,0 +1,88 @@
"use client";
import { motion } from "framer-motion";
interface HomePageProps {
onStartNormal: () => void;
onStartCrisis: () => void;
onOpenKanban: () => void;
onOpenDashboard: () => void;
isAdmin?: boolean;
}
export default function HomePage({
onStartNormal,
onStartCrisis,
onOpenKanban,
onOpenDashboard,
isAdmin = false,
}: HomePageProps) {
return (
<div className="min-h-screen flex flex-col items-center justify-center p-4 relative">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
className="text-center max-w-md w-full"
>
<motion.div
initial={{ scale: 0 }}
animate={{ scale: 1 }}
transition={{ type: "spring", duration: 0.6 }}
className="text-7xl mb-6"
>
🧠
</motion.div>
<h1 className="text-4xl font-bold text-white mb-2">
Brain Dump
</h1>
<br />
<div className="space-y-4">
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
onClick={onStartNormal}
className="cursor-pointer w-full bg-linear-to-r from-green-400 to-emerald-500 hover:from-green-500 hover:to-emerald-600 text-white font-bold py-4 px-6 rounded-xl shadow-lg transition-all duration-200"
>
🌿 Commencer doucement
</motion.button>
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
onClick={onStartCrisis}
className="cursor-pointer w-full bg-linear-to-r from-red-500 to-orange-500 hover:from-red-600 hover:to-orange-600 text-white font-bold py-4 px-6 rounded-xl shadow-lg transition-all duration-200"
>
🆘 Je ne vais pas bien !
</motion.button>
<div className="flex gap-4 pt-4">
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
onClick={onOpenKanban}
className={`cursor-pointer ${
isAdmin ? "flex-1" : "w-full"
} bg-gray-700 hover:bg-gray-600 text-white font-semibold py-3 px-4 rounded-xl transition-colors`}
>
📋 Kanban
</motion.button>
{isAdmin && (
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
onClick={onOpenDashboard}
className="cursor-pointer flex-1 bg-gray-700 hover:bg-gray-600 text-white font-semibold py-3 px-4 rounded-xl transition-colors"
>
Questions
</motion.button>
)}
</div>
</div>
</motion.div>
</div>
);
}
+945
View File
@@ -0,0 +1,945 @@
"use client";
import { CATEGORIES, STATUSES } from "@/lib/constants";
import { KanbanView, Task, TaskCategory, TaskStatus } from "@/types";
import {
closestCorners,
DndContext,
DragEndEvent,
DragOverEvent,
DragOverlay,
DragStartEvent,
PointerSensor,
useDroppable,
useSensor,
useSensors,
} from "@dnd-kit/core";
import {
SortableContext,
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { AnimatePresence, motion } from "framer-motion";
import { useCallback, useEffect, useState } from "react";
import Confetti from "./Confetti";
import ConfirmModal from "./ConfirmModal";
import TaskDetailModal from "./TaskDetailModal";
import Toast, { ToastData } from "./Toast";
interface KanbanBoardProps {
onBack: () => void;
}
export default function KanbanBoard({ onBack }: KanbanBoardProps) {
const [tasks, setTasks] = useState<Task[]>([]);
const [view, setView] = useState<KanbanView>("category");
const [addingTask, setAddingTask] = useState(false);
const [newTask, setNewTask] = useState({
text: "",
category: "urgent" as TaskCategory,
});
const [loading, setLoading] = useState(true);
const [showConfetti, setShowConfetti] = useState(false);
const [showArchived, setShowArchived] = useState(false);
const [activeTask, setActiveTask] = useState<Task | null>(null);
const [originalTask, setOriginalTask] = useState<Task | null>(null);
const [selectedTask, setSelectedTask] = useState<Task | null>(null);
const [toasts, setToasts] = useState<ToastData[]>([]);
const [confirmModal, setConfirmModal] = useState<{
isOpen: boolean;
title: string;
message: string;
onConfirm: () => void;
}>({ isOpen: false, title: "", message: "", onConfirm: () => {} });
const addToast = useCallback(
(message: string, type: ToastData["type"] = "success") => {
const id = Date.now().toString();
setToasts((prev) => [...prev, { id, message, type }]);
},
[]
);
const removeToast = useCallback((id: string) => {
setToasts((prev) => prev.filter((t) => t.id !== id));
}, []);
const sensors = useSensors(
useSensor(PointerSensor, {
activationConstraint: {
distance: 8,
},
})
);
useEffect(() => {
fetchTasks();
}, []);
const fetchTasks = async () => {
try {
const response = await fetch("/api/tasks");
const data = await response.json();
setTasks(data);
} catch (error) {
console.error("Error fetching tasks:", error);
} finally {
setLoading(false);
}
};
const addTask = async () => {
if (!newTask.text.trim()) return;
try {
const response = await fetch("/api/tasks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(newTask),
});
if (response.ok) {
const createdTask = await response.json();
setTasks([createdTask, ...tasks]);
setNewTask({ text: "", category: "urgent" });
setAddingTask(false);
addToast("Tâche créée", "success");
}
} catch (error) {
console.error("Error adding task:", error);
addToast("Erreur lors de la création", "error");
}
};
const updateTaskStatus = async (taskId: number, status: TaskStatus) => {
try {
const response = await fetch("/api/tasks", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: taskId, status }),
});
if (response.ok) {
const updatedTask = await response.json();
setTasks(tasks.map((t) => (t.id === taskId ? updatedTask : t)));
}
} catch (error) {
console.error("Error updating task:", error);
}
};
const updateTaskCategory = async (
taskId: number,
category: TaskCategory
) => {
console.log("updateTaskCategory called:", { taskId, category });
try {
const response = await fetch("/api/tasks", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: taskId, category }),
});
console.log("Response status:", response.status);
if (response.ok) {
const updatedTask = await response.json();
console.log("Updated task:", updatedTask);
setTasks(tasks.map((t) => (t.id === taskId ? updatedTask : t)));
} else {
const error = await response.json();
console.error("API Error:", error);
}
} catch (error) {
console.error("Error updating task:", error);
}
};
const completeAndArchiveTask = async (taskId: number) => {
try {
const response = await fetch("/api/tasks", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: taskId, status: "archived" }),
});
if (response.ok) {
setShowConfetti(true);
setTimeout(() => setShowConfetti(false), 3000);
const updatedTask = await response.json();
setTasks(tasks.map((t) => (t.id === taskId ? updatedTask : t)));
addToast("Tâche archivée 🎉", "success");
}
} catch (error) {
console.error("Error archiving task:", error);
addToast("Erreur lors de l'archivage", "error");
}
};
const restoreTask = async (taskId: number) => {
try {
const response = await fetch("/api/tasks", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: taskId, status: "todo" }),
});
if (response.ok) {
const updatedTask = await response.json();
setTasks(tasks.map((t) => (t.id === taskId ? updatedTask : t)));
addToast("Tâche restaurée", "info");
}
} catch (error) {
console.error("Error restoring task:", error);
addToast("Erreur lors de la restauration", "error");
}
};
const deleteTask = async (taskId: number) => {
setConfirmModal({
isOpen: true,
title: "Supprimer la tâche",
message:
"Es-tu sûr de vouloir supprimer cette tâche ? Cette action est irréversible.",
onConfirm: async () => {
try {
const response = await fetch(`/api/tasks?id=${taskId}`, {
method: "DELETE",
});
if (response.ok) {
setTasks(tasks.filter((t) => t.id !== taskId));
addToast("Tâche supprimée", "success");
}
} catch (error) {
console.error("Error deleting task:", error);
addToast("Erreur lors de la suppression", "error");
}
setConfirmModal((prev) => ({ ...prev, isOpen: false }));
},
});
};
const handleDragStart = (event: DragStartEvent) => {
const { active } = event;
const task = tasks.find((t) => t.id === active.id);
if (task) {
setActiveTask(task);
setOriginalTask({ ...task });
}
};
const handleDragOver = (event: DragOverEvent) => {
const { active, over } = event;
if (!over) return;
const activeId = active.id as number;
const overId = over.id;
if (view === "category") {
const categories = CATEGORIES.map((c) => c.key);
let targetCategory: TaskCategory | null = null;
if (categories.includes(overId as TaskCategory)) {
targetCategory = overId as TaskCategory;
} else {
const overTask = tasks.find((t) => t.id === overId);
if (overTask) {
targetCategory = overTask.category;
}
}
if (targetCategory) {
const activeTask = tasks.find((t) => t.id === activeId);
if (activeTask && activeTask.category !== targetCategory) {
setTasks(
tasks.map((t) =>
t.id === activeId
? {
...t,
category: targetCategory as TaskCategory,
}
: t
)
);
}
}
} else {
const statuses = STATUSES.map((s) => s.key);
let targetStatus: TaskStatus | null = null;
if (statuses.includes(overId as TaskStatus)) {
targetStatus = overId as TaskStatus;
} else {
const overTask = tasks.find((t) => t.id === overId);
if (overTask) {
targetStatus = overTask.status;
}
}
if (targetStatus) {
const activeTask = tasks.find((t) => t.id === activeId);
if (activeTask && activeTask.status !== targetStatus) {
setTasks(
tasks.map((t) =>
t.id === activeId
? { ...t, status: targetStatus as TaskStatus }
: t
)
);
}
}
}
};
const handleDragEnd = async (event: DragEndEvent) => {
const { active, over } = event;
console.log("handleDragEnd:", {
activeId: active.id,
overId: over?.id,
originalTask,
});
setActiveTask(null);
if (!over || !originalTask) {
console.log("No over or originalTask, aborting");
setOriginalTask(null);
return;
}
const activeId = active.id as number;
const overId = over.id;
if (view === "category") {
const categories = CATEGORIES.map((c) => c.key);
let targetCategory: TaskCategory | null = null;
if (categories.includes(overId as TaskCategory)) {
targetCategory = overId as TaskCategory;
} else {
const overTask = tasks.find((t) => t.id === overId);
if (overTask) {
targetCategory = overTask.category;
}
}
console.log(
"Target category:",
targetCategory,
"Original:",
originalTask.category
);
if (targetCategory && originalTask.category !== targetCategory) {
console.log(
"Calling updateTaskCategory:",
activeId,
targetCategory
);
await updateTaskCategory(activeId, targetCategory);
}
} else {
const statuses = STATUSES.map((s) => s.key);
let targetStatus: TaskStatus | null = null;
if (statuses.includes(overId as TaskStatus)) {
targetStatus = overId as TaskStatus;
} else {
const overTask = tasks.find((t) => t.id === overId);
if (overTask) {
targetStatus = overTask.status;
}
}
if (targetStatus) {
if (targetStatus === "done") {
await completeAndArchiveTask(activeId);
} else if (originalTask.status !== targetStatus) {
await updateTaskStatus(activeId, targetStatus);
}
}
}
setOriginalTask(null);
};
const activeTasks = tasks.filter((t) => t.status !== "archived");
const archivedTasks = tasks.filter((t) => t.status === "archived");
const getTasksByCategory = (category: TaskCategory) =>
activeTasks.filter((t) => t.category === category);
const getTasksByStatus = (status: TaskStatus) =>
activeTasks.filter((t) => t.status === status);
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-2xl">Chargement...</div>
</div>
);
}
return (
<>
<Confetti show={showConfetti} />
<div className="min-h-screen p-4 md:p-8">
<div className="max-w-7xl mx-auto">
<div className="flex flex-col md:flex-row justify-between items-center mb-8 gap-4">
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
onClick={onBack}
className="bg-gray-700 hover:bg-gray-600 px-6 py-3 rounded-xl transition-colors"
>
Retour
</motion.button>
<h1 className="text-4xl font-bold">Ton Kanban</h1>
<div className="flex gap-3 flex-wrap justify-center">
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
onClick={() =>
setView(
view === "category"
? "status"
: "category"
)
}
className="bg-gray-700 hover:bg-gray-600 px-6 py-3 rounded-xl transition-colors"
>
Vue:{" "}
{view === "category" ? "Catégorie" : "Statut"}
</motion.button>
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
onClick={() => setShowArchived(!showArchived)}
className={`px-6 py-3 rounded-xl transition-colors ${
showArchived
? "bg-slate-600 hover:bg-slate-500"
: "bg-gray-700 hover:bg-gray-600"
}`}
>
📦 Archivées ({archivedTasks.length})
</motion.button>
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
onClick={() => setAddingTask(true)}
className="bg-blue-500 hover:bg-blue-600 px-6 py-3 rounded-xl transition-colors"
>
+ Ajouter
</motion.button>
</div>
</div>
<div className="text-center text-gray-500 text-sm mb-4">
💡 Glisse-dépose les tâches entre les colonnes
</div>
<AnimatePresence>
{showArchived && archivedTasks.length > 0 && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: "auto" }}
exit={{ opacity: 0, height: 0 }}
className="mb-8 overflow-hidden"
>
<div className="bg-slate-800/50 rounded-2xl p-6">
<h2 className="text-xl font-bold mb-4 text-slate-300">
📦 Tâches archivées
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3">
{archivedTasks.map((task) => {
const cat = CATEGORIES.find(
(c) => c.key === task.category
);
return (
<motion.div
key={task.id}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className={`bg-slate-700/50 rounded-xl p-4 border-l-4 ${cat?.border}`}
>
<p className="text-slate-300 line-through mb-2">
{task.text}
</p>
<p className="text-xs text-slate-500 mb-3">
{cat?.label} {" "}
{task.added}
</p>
<div className="flex gap-2">
<button
onClick={() =>
restoreTask(
task.id
)
}
className="flex-1 bg-blue-600 hover:bg-blue-500 text-white py-1 px-2 text-xs rounded transition"
>
Restaurer
</button>
<button
onClick={() =>
deleteTask(
task.id
)
}
className="flex-1 bg-red-900 hover:bg-red-800 text-red-200 py-1 px-2 text-xs rounded transition"
>
Supprimer
</button>
</div>
</motion.div>
);
})}
</div>
</div>
</motion.div>
)}
</AnimatePresence>
<DndContext
sensors={sensors}
collisionDetection={closestCorners}
onDragStart={handleDragStart}
onDragOver={handleDragOver}
onDragEnd={handleDragEnd}
>
{view === "category" ? (
<CategoryView
tasks={activeTasks}
getTasksByCategory={getTasksByCategory}
updateTaskStatus={updateTaskStatus}
completeAndArchiveTask={completeAndArchiveTask}
deleteTask={deleteTask}
onOpenDetail={setSelectedTask}
/>
) : (
<StatusView
tasks={activeTasks}
getTasksByStatus={getTasksByStatus}
updateTaskStatus={updateTaskStatus}
completeAndArchiveTask={completeAndArchiveTask}
deleteTask={deleteTask}
onOpenDetail={setSelectedTask}
/>
)}
<DragOverlay>
{activeTask ? (
<TaskCardOverlay task={activeTask} />
) : null}
</DragOverlay>
</DndContext>
{addingTask && (
<AddTaskModal
newTask={newTask}
setNewTask={setNewTask}
onAdd={addTask}
onCancel={() => {
setAddingTask(false);
setNewTask({ text: "", category: "urgent" });
}}
/>
)}
<AnimatePresence>
{selectedTask && (
<TaskDetailModal
task={selectedTask}
onClose={() => setSelectedTask(null)}
onUpdate={(updatedTask) => {
setTasks(
tasks.map((t) =>
t.id === updatedTask.id
? updatedTask
: t
)
);
setSelectedTask(updatedTask);
}}
onDelete={(taskId) => {
deleteTask(taskId);
setSelectedTask(null);
}}
onComplete={(taskId) => {
completeAndArchiveTask(taskId);
setSelectedTask(null);
}}
/>
)}
</AnimatePresence>
<Toast toasts={toasts} removeToast={removeToast} />
<ConfirmModal
isOpen={confirmModal.isOpen}
title={confirmModal.title}
message={confirmModal.message}
confirmText="Supprimer"
cancelText="Annuler"
confirmColor="red"
onConfirm={confirmModal.onConfirm}
onCancel={() =>
setConfirmModal((prev) => ({
...prev,
isOpen: false,
}))
}
/>
</div>
</div>
</>
);
}
function DroppableColumn({
id,
children,
color,
label,
count,
}: {
id: string;
children: React.ReactNode;
color: string;
label: string;
count: number;
}) {
const { setNodeRef, isOver } = useDroppable({ id });
return (
<div ref={setNodeRef}>
<div
className={`${color} rounded-xl p-3 mb-4 text-center font-bold transition-all ${
isOver ? "ring-2 ring-white ring-opacity-50 scale-105" : ""
}`}
>
{label} ({count})
</div>
<div
className={`space-y-3 min-h-25 rounded-xl p-2 transition-all ${
isOver ? "bg-gray-700/30" : ""
}`}
>
{children}
</div>
</div>
);
}
function SortableTaskCard({
task,
onUpdateStatus,
onComplete,
onDelete,
onOpenDetail,
}: {
task: Task;
onUpdateStatus: (taskId: number, status: TaskStatus) => void;
onComplete: (taskId: number) => void;
onDelete: (taskId: number) => void;
onOpenDetail: (task: Task) => void;
}) {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: task.id });
const style = {
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.5 : 1,
};
const cat = CATEGORIES.find((c) => c.key === task.category);
const checklistCount = task.checklist?.length || 0;
const checklistDone = task.checklist?.filter((i) => i.checked).length || 0;
return (
<div ref={setNodeRef} style={style} {...attributes}>
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
className={`bg-gray-800 rounded-xl p-4 border-l-4 ${
cat?.border
} ${
isDragging ? "shadow-2xl" : ""
} cursor-pointer hover:bg-gray-750 transition`}
onClick={() => onOpenDetail(task)}
>
<div
{...listeners}
onClick={(e) => e.stopPropagation()}
className="cursor-grab active:cursor-grabbing mb-2 text-gray-500 hover:text-gray-300 flex items-center gap-2"
>
<span className="text-lg"></span>
<span className="text-xs">Glisser</span>
</div>
<p className="mb-2 font-medium">{task.text}</p>
<div className="flex gap-2 mb-3 flex-wrap">
{task.description && (
<span className="text-xs bg-gray-700 px-2 py-1 rounded text-gray-400">
📝 Description
</span>
)}
{checklistCount > 0 && (
<span
className={`text-xs px-2 py-1 rounded ${
checklistDone === checklistCount
? "bg-green-500/20 text-green-400"
: "bg-gray-700 text-gray-400"
}`}
>
{checklistDone}/{checklistCount}
</span>
)}
</div>
<div
className="flex gap-1 mb-2"
onClick={(e) => e.stopPropagation()}
>
{STATUSES.map((status) => (
<button
key={status.key}
onClick={() => {
if (status.key === "done") {
onComplete(task.id);
} else {
onUpdateStatus(task.id, status.key);
}
}}
className={`flex-1 py-1 text-xs rounded transition ${
task.status === status.key
? `${status.color} text-white`
: "bg-gray-700 hover:bg-gray-600"
}`}
>
{status.key === "done" ? "✓ " : ""}
{status.label}
</button>
))}
</div>
<p className="text-xs text-gray-500 mb-2">{task.added}</p>
<button
onClick={(e) => {
e.stopPropagation();
onDelete(task.id);
}}
className="w-full bg-red-900 hover:bg-red-800 text-red-200 py-1 text-xs rounded transition"
>
Supprimer
</button>
</motion.div>
</div>
);
}
function TaskCardOverlay({ task }: { task: Task }) {
const cat = CATEGORIES.find((c) => c.key === task.category);
return (
<div
className={`bg-gray-800 rounded-xl p-4 border-l-4 ${cat?.border} shadow-2xl rotate-3 opacity-90`}
>
<p className="mb-3">{task.text}</p>
<p className="text-xs text-gray-500">{task.added}</p>
</div>
);
}
function CategoryView({
tasks,
getTasksByCategory,
updateTaskStatus,
completeAndArchiveTask,
deleteTask,
onOpenDetail,
}: {
tasks: Task[];
getTasksByCategory: (category: TaskCategory) => Task[];
updateTaskStatus: (taskId: number, status: TaskStatus) => void;
completeAndArchiveTask: (taskId: number) => void;
deleteTask: (taskId: number) => void;
onOpenDetail: (task: Task) => void;
}) {
return (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
{CATEGORIES.map((cat) => {
const categoryTasks = getTasksByCategory(cat.key);
return (
<SortableContext
key={cat.key}
items={categoryTasks.map((t) => t.id)}
strategy={verticalListSortingStrategy}
>
<DroppableColumn
id={cat.key}
color={cat.color}
label={cat.label}
count={categoryTasks.length}
>
{categoryTasks.map((task) => (
<SortableTaskCard
key={task.id}
task={task}
onUpdateStatus={updateTaskStatus}
onComplete={completeAndArchiveTask}
onDelete={deleteTask}
onOpenDetail={onOpenDetail}
/>
))}
</DroppableColumn>
</SortableContext>
);
})}
</div>
);
}
function StatusView({
tasks,
getTasksByStatus,
updateTaskStatus,
completeAndArchiveTask,
deleteTask,
onOpenDetail,
}: {
tasks: Task[];
getTasksByStatus: (status: TaskStatus) => Task[];
updateTaskStatus: (taskId: number, status: TaskStatus) => void;
completeAndArchiveTask: (taskId: number) => void;
deleteTask: (taskId: number) => void;
onOpenDetail: (task: Task) => void;
}) {
return (
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
{STATUSES.map((status) => {
const statusTasks = getTasksByStatus(status.key);
return (
<SortableContext
key={status.key}
items={statusTasks.map((t) => t.id)}
strategy={verticalListSortingStrategy}
>
<DroppableColumn
id={status.key}
color={status.color}
label={status.label}
count={statusTasks.length}
>
{statusTasks.map((task) => (
<SortableTaskCard
key={task.id}
task={task}
onUpdateStatus={updateTaskStatus}
onComplete={completeAndArchiveTask}
onDelete={deleteTask}
onOpenDetail={onOpenDetail}
/>
))}
</DroppableColumn>
</SortableContext>
);
})}
</div>
);
}
function AddTaskModal({
newTask,
setNewTask,
onAdd,
onCancel,
}: {
newTask: { text: string; category: TaskCategory };
setNewTask: (task: { text: string; category: TaskCategory }) => void;
onAdd: () => void;
onCancel: () => void;
}) {
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
className="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4"
onClick={onCancel}
>
<motion.div
initial={{ scale: 0.9 }}
animate={{ scale: 1 }}
onClick={(e) => e.stopPropagation()}
className="bg-gray-800 rounded-2xl p-6 w-full max-w-md"
>
<h2 className="text-2xl font-bold mb-4">Nouvelle tâche</h2>
<textarea
value={newTask.text}
onChange={(e) =>
setNewTask({ ...newTask, text: e.target.value })
}
placeholder="Décris ta tâche..."
className="w-full bg-gray-700 text-white p-3 rounded-xl outline-none resize-none mb-4"
rows={4}
autoFocus
onKeyDown={(e) => {
if (e.key === "Enter" && e.ctrlKey) {
onAdd();
}
}}
/>
<p className="text-sm text-gray-400 mb-2">Catégorie:</p>
<div className="grid grid-cols-2 gap-2 mb-4">
{CATEGORIES.map((cat) => (
<button
key={cat.key}
onClick={() =>
setNewTask({ ...newTask, category: cat.key })
}
className={`px-3 py-2 rounded-xl transition ${
newTask.category === cat.key
? `${cat.color} text-white`
: "bg-gray-700 hover:bg-gray-600"
}`}
>
{newTask.category === cat.key ? "[X]" : "[ ]"}{" "}
{cat.label}
</button>
))}
</div>
<div className="flex gap-3">
<button
onClick={onAdd}
className="flex-1 bg-green-500 hover:bg-green-600 py-2 rounded-xl transition font-bold"
>
Ajouter
</button>
<button
onClick={onCancel}
className="flex-1 bg-gray-700 hover:bg-gray-600 py-2 rounded-xl transition"
>
Annuler
</button>
</div>
</motion.div>
</motion.div>
);
}
+288
View File
@@ -0,0 +1,288 @@
"use client";
import { CATEGORIES } from "@/lib/constants";
import { Question, TaskCategory } from "@/types";
import { AnimatePresence, motion } from "framer-motion";
import { useEffect, useRef, useState } from "react";
interface QuestionnaireProps {
questions: Question[];
mode: "normal" | "crisis";
onComplete: (
answers: Array<{
questionIndex: number;
category: string;
question: string;
answer: string;
}>
) => void;
onBack: () => void;
onAddTask?: (text: string, category: TaskCategory) => Promise<void>;
}
interface KanbanSelection {
[questionIndex: number]: TaskCategory[];
}
export default function Questionnaire({
questions,
mode,
onComplete,
onBack,
onAddTask,
}: QuestionnaireProps) {
const [currentQ, setCurrentQ] = useState(0);
const [answers, setAnswers] = useState<string[]>(
new Array(questions.length).fill("")
);
const [direction, setDirection] = useState(1);
const [kanbanSelections, setKanbanSelections] = useState<KanbanSelection>(
{}
);
const [addingToKanban, setAddingToKanban] = useState<{
[key: string]: boolean;
}>({});
const textareaRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
textareaRef.current?.focus();
}, [currentQ]);
const handleNext = () => {
if (currentQ < questions.length - 1) {
setDirection(1);
setCurrentQ(currentQ + 1);
} else {
const formattedAnswers = answers
.map((answer, index) => ({
questionIndex: index,
category: questions[index].category,
question: questions[index].question,
answer,
}))
.filter((a) => a.answer.trim());
onComplete(formattedAnswers);
}
};
const handlePrev = () => {
if (currentQ > 0) {
setDirection(-1);
setCurrentQ(currentQ - 1);
}
};
const handleAnswer = (value: string) => {
const newAnswers = [...answers];
newAnswers[currentQ] = value;
setAnswers(newAnswers);
};
const toggleKanbanCategory = async (category: TaskCategory) => {
if (!answers[currentQ].trim()) return;
const currentSelections = kanbanSelections[currentQ] || [];
const isSelected = currentSelections.includes(category);
if (isSelected) {
setKanbanSelections({
...kanbanSelections,
[currentQ]: currentSelections.filter((c) => c !== category),
});
} else {
const key = `${currentQ}-${category}`;
setAddingToKanban({ ...addingToKanban, [key]: true });
try {
if (onAddTask) {
await onAddTask(answers[currentQ], category);
}
setKanbanSelections({
...kanbanSelections,
[currentQ]: [...currentSelections, category],
});
} catch (error) {
console.error("Error adding task:", error);
} finally {
setAddingToKanban({ ...addingToKanban, [key]: false });
}
}
};
const isKanbanSelected = (category: TaskCategory) => {
return (kanbanSelections[currentQ] || []).includes(category);
};
const progress = ((currentQ + 1) / questions.length) * 100;
const currentQuestion = questions[currentQ];
const hasAnswer = answers[currentQ].trim().length > 0;
return (
<div className="min-h-screen flex items-center justify-center p-4 md:p-8">
<div className="max-w-3xl w-full">
<div className="mb-8">
<div className="flex justify-between items-center mb-2">
<span className="text-sm text-gray-400">
Question {currentQ + 1} / {questions.length}
</span>
<span className="text-sm text-gray-400">
{Math.round(progress)}%
</span>
</div>
<div className="h-2 bg-gray-700 rounded-full overflow-hidden">
<motion.div
initial={{ width: 0 }}
animate={{ width: `${progress}%` }}
transition={{ duration: 0.3 }}
className={
mode === "crisis"
? "h-full bg-red-500"
: "h-full bg-green-500"
}
/>
</div>
</div>
<AnimatePresence mode="wait" custom={direction}>
<motion.div
key={currentQ}
custom={direction}
initial={{ opacity: 0, x: direction * 50 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: direction * -50 }}
transition={{ duration: 0.3 }}
className="bg-gray-800 rounded-3xl p-8 shadow-2xl"
>
<div className="mb-4">
<span
className={`inline-block px-4 py-1 rounded-full text-sm font-medium ${
mode === "crisis"
? "bg-red-500/20 text-red-400"
: "bg-green-500/20 text-green-400"
}`}
>
{currentQuestion.category}
</span>
</div>
<h2 className="text-2xl md:text-3xl font-bold mb-6 text-white">
{currentQuestion.question}
</h2>
<textarea
ref={textareaRef}
value={answers[currentQ]}
onChange={(e) => handleAnswer(e.target.value)}
placeholder="Écris ta réponse ici..."
className="w-full bg-gray-700 text-white p-4 rounded-xl outline-none resize-none min-h-37.5 focus:ring-2 focus:ring-blue-500 transition-all"
onKeyDown={(e) => {
if (e.key === "Enter" && e.ctrlKey) {
handleNext();
}
}}
/>
<div className="mt-4">
<p className="text-sm text-gray-400 mb-2">
Ajouter au kanban (optionnel) :
</p>
<div className="flex flex-wrap gap-2">
{CATEGORIES.map((cat) => {
const isSelected = isKanbanSelected(
cat.key
);
const isLoading =
addingToKanban[
`${currentQ}-${cat.key}`
];
return (
<motion.button
key={cat.key}
whileHover={{
scale: hasAnswer ? 1.05 : 1,
}}
whileTap={{
scale: hasAnswer ? 0.95 : 1,
}}
onClick={() =>
toggleKanbanCategory(cat.key)
}
disabled={!hasAnswer || isLoading}
className={`px-3 py-2 rounded-lg text-sm font-medium transition-all flex items-center gap-1 ${
!hasAnswer
? "bg-gray-700/50 text-gray-500 cursor-not-allowed"
: isSelected
? `${cat.color} text-white`
: "bg-gray-700 hover:bg-gray-600 text-gray-300"
}`}
>
{isLoading ? (
<span className="animate-spin">
</span>
) : (
<span>
[{isSelected ? "X" : " "}]
</span>
)}
{cat.label}
</motion.button>
);
})}
</div>
{(kanbanSelections[currentQ]?.length ?? 0) > 0 && (
<motion.p
initial={{ opacity: 0, y: -5 }}
animate={{ opacity: 1, y: 0 }}
className="text-xs text-green-400 mt-2"
>
Ajouté au kanban dans :{" "}
{kanbanSelections[currentQ]
.map(
(k) =>
CATEGORIES.find(
(c) => c.key === k
)?.label
)
.join(", ")}
</motion.p>
)}
</div>
<div className="mt-4 text-sm text-gray-400">
💡 Appuie sur Ctrl+Entrée pour continuer
</div>
</motion.div>
</AnimatePresence>
<div className="flex justify-between mt-8 gap-4">
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
onClick={currentQ === 0 ? onBack : handlePrev}
className="bg-gray-700 hover:bg-gray-600 px-6 py-3 rounded-xl transition-colors font-medium"
>
{currentQ === 0 ? "← Annuler" : "← Précédent"}
</motion.button>
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
onClick={handleNext}
className={`px-6 py-3 rounded-xl transition-colors font-medium ${
mode === "crisis"
? "bg-red-500 hover:bg-red-600"
: "bg-green-500 hover:bg-green-600"
}`}
>
{currentQ === questions.length - 1
? "✓ Terminer"
: "Suivant →"}
</motion.button>
</div>
</div>
</div>
);
}
+551
View File
@@ -0,0 +1,551 @@
"use client";
import { Question, QuestionMode } from "@/types";
import { AnimatePresence, motion } from "framer-motion";
import { useEffect, useState } from "react";
interface QuestionsDashboardProps {
onBack: () => void;
}
const NORMAL_CATEGORIES = [
"Brain",
"Émotions",
"Corps",
"Actions",
"Relations",
"Sécurité",
"Créativité",
"Clôture",
];
const CRISIS_CATEGORIES = [
"Sécurité",
"Ancrage",
"Besoins",
"Émotions",
"Respiration",
"Pensées",
"Soutien",
"Action",
"Ressources",
"Récupération",
];
export default function QuestionsDashboard({
onBack,
}: QuestionsDashboardProps) {
const [questions, setQuestions] = useState<Question[]>([]);
const [loading, setLoading] = useState(true);
const [activeMode, setActiveMode] = useState<QuestionMode>("normal");
const [editingQuestion, setEditingQuestion] = useState<Question | null>(
null
);
const [isAdding, setIsAdding] = useState(false);
const [newQuestion, setNewQuestion] = useState({
category: "",
question: "",
});
const [customCategory, setCustomCategory] = useState("");
useEffect(() => {
fetchQuestions();
}, []);
const fetchQuestions = async () => {
try {
const response = await fetch("/api/questions");
const data = await response.json();
setQuestions(data);
} catch (error) {
console.error("Error fetching questions:", error);
} finally {
setLoading(false);
}
};
const addQuestion = async () => {
const category =
newQuestion.category === "__custom__"
? customCategory
: newQuestion.category;
if (!category.trim() || !newQuestion.question.trim()) return;
try {
const response = await fetch("/api/questions", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
category,
question: newQuestion.question,
mode: activeMode,
}),
});
if (response.ok) {
const created = await response.json();
setQuestions([...questions, created]);
setNewQuestion({ category: "", question: "" });
setCustomCategory("");
setIsAdding(false);
}
} catch (error) {
console.error("Error adding question:", error);
}
};
const updateQuestion = async () => {
if (!editingQuestion) return;
try {
const response = await fetch("/api/questions", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
id: editingQuestion.id,
category: editingQuestion.category,
question: editingQuestion.question,
}),
});
if (response.ok) {
const updated = await response.json();
setQuestions(
questions.map((q) => (q.id === updated.id ? updated : q))
);
setEditingQuestion(null);
}
} catch (error) {
console.error("Error updating question:", error);
}
};
const deleteQuestion = async (id: number) => {
if (!confirm("Supprimer cette question ?")) return;
try {
const response = await fetch(`/api/questions?id=${id}`, {
method: "DELETE",
});
if (response.ok) {
setQuestions(questions.filter((q) => q.id !== id));
}
} catch (error) {
console.error("Error deleting question:", error);
}
};
const moveQuestion = async (id: number, direction: "up" | "down") => {
const modeQuestions = questions.filter((q) => q.mode === activeMode);
const index = modeQuestions.findIndex((q) => q.id === id);
if (direction === "up" && index === 0) return;
if (direction === "down" && index === modeQuestions.length - 1) return;
const swapIndex = direction === "up" ? index - 1 : index + 1;
const currentQuestion = modeQuestions[index];
const swapQuestion = modeQuestions[swapIndex];
try {
await fetch("/api/questions", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
id: currentQuestion.id,
order_index: swapQuestion.order_index,
}),
});
await fetch("/api/questions", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
id: swapQuestion.id,
order_index: currentQuestion.order_index,
}),
});
fetchQuestions();
} catch (error) {
console.error("Error moving question:", error);
}
};
const filteredQuestions = questions.filter((q) => q.mode === activeMode);
const categories =
activeMode === "normal" ? NORMAL_CATEGORIES : CRISIS_CATEGORIES;
const groupedQuestions = filteredQuestions.reduce((acc, q) => {
if (!acc[q.category]) acc[q.category] = [];
acc[q.category].push(q);
return acc;
}, {} as Record<string, Question[]>);
if (loading) {
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-2xl">Chargement...</div>
</div>
);
}
return (
<div className="min-h-screen p-4 md:p-8">
<div className="max-w-6xl mx-auto">
<div className="flex flex-col md:flex-row justify-between items-center mb-8 gap-4">
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
onClick={onBack}
className="bg-gray-700 hover:bg-gray-600 px-6 py-3 rounded-xl transition-colors"
>
Retour
</motion.button>
<h1 className="text-3xl md:text-4xl font-bold">
Gestion des Questions
</h1>
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
onClick={() => setIsAdding(true)}
className="bg-blue-500 hover:bg-blue-600 px-6 py-3 rounded-xl transition-colors"
>
+ Ajouter
</motion.button>
</div>
<div className="flex gap-4 mb-8 justify-center">
<button
onClick={() => setActiveMode("normal")}
className={`px-8 py-3 rounded-xl font-bold transition-all ${
activeMode === "normal"
? "bg-green-500 text-white"
: "bg-gray-700 hover:bg-gray-600"
}`}
>
🌿 Normal (
{questions.filter((q) => q.mode === "normal").length})
</button>
<button
onClick={() => setActiveMode("crisis")}
className={`px-8 py-3 rounded-xl font-bold transition-all ${
activeMode === "crisis"
? "bg-red-500 text-white"
: "bg-gray-700 hover:bg-gray-600"
}`}
>
🆘 Crise (
{questions.filter((q) => q.mode === "crisis").length})
</button>
</div>
<div className="space-y-6">
{Object.entries(groupedQuestions).map(
([category, categoryQuestions]) => (
<div
key={category}
className="bg-gray-800 rounded-2xl p-6"
>
<h2 className="text-xl font-bold mb-4 text-gray-300">
{category} ({categoryQuestions.length})
</h2>
<div className="space-y-3">
{categoryQuestions.map((q, idx) => (
<motion.div
key={q.id}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className="bg-gray-700 rounded-xl p-4 flex items-center gap-4"
>
<div className="flex flex-col gap-1">
<button
onClick={() =>
moveQuestion(
q.id!,
"up"
)
}
className="text-gray-400 hover:text-white text-sm"
disabled={idx === 0}
>
</button>
<button
onClick={() =>
moveQuestion(
q.id!,
"down"
)
}
className="text-gray-400 hover:text-white text-sm"
disabled={
idx ===
categoryQuestions.length -
1
}
>
</button>
</div>
<p className="flex-1 text-white">
{q.question}
</p>
<div className="flex gap-2">
<button
onClick={() =>
setEditingQuestion(q)
}
className="bg-blue-600 hover:bg-blue-500 px-3 py-1 rounded text-sm"
>
Modifier
</button>
<button
onClick={() =>
deleteQuestion(q.id!)
}
className="bg-red-600 hover:bg-red-500 px-3 py-1 rounded text-sm"
>
🗑 Supprimer
</button>
</div>
</motion.div>
))}
</div>
</div>
)
)}
{filteredQuestions.length === 0 && (
<div className="text-center py-12 text-gray-400">
<p className="text-xl mb-4">
Aucune question pour ce mode
</p>
<p>
Clique sur "+ Ajouter" pour créer ta première
question
</p>
</div>
)}
</div>
<AnimatePresence>
{isAdding && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4"
onClick={() => setIsAdding(false)}
>
<motion.div
initial={{ scale: 0.9 }}
animate={{ scale: 1 }}
exit={{ scale: 0.9 }}
onClick={(e) => e.stopPropagation()}
className="bg-gray-800 rounded-2xl p-6 w-full max-w-lg"
>
<h2 className="text-2xl font-bold mb-4">
Nouvelle Question
</h2>
<div className="mb-4">
<p className="text-sm text-gray-400 mb-2">
Mode :
</p>
<div className="flex gap-2">
<button
onClick={() =>
setActiveMode("normal")
}
className={`flex-1 py-2 rounded-xl ${
activeMode === "normal"
? "bg-green-500"
: "bg-gray-700"
}`}
>
🌿 Normal
</button>
<button
onClick={() =>
setActiveMode("crisis")
}
className={`flex-1 py-2 rounded-xl ${
activeMode === "crisis"
? "bg-red-500"
: "bg-gray-700"
}`}
>
🆘 Crise
</button>
</div>
</div>
<div className="mb-4">
<p className="text-sm text-gray-400 mb-2">
Catégorie :
</p>
<select
value={newQuestion.category}
onChange={(e) =>
setNewQuestion({
...newQuestion,
category: e.target.value,
})
}
className="w-full bg-gray-700 text-white p-3 rounded-xl outline-none"
>
<option value="">
Sélectionner une catégorie
</option>
{categories.map((cat) => (
<option key={cat} value={cat}>
{cat}
</option>
))}
<option value="__custom__">
+ Nouvelle catégorie
</option>
</select>
{newQuestion.category === "__custom__" && (
<input
type="text"
value={customCategory}
onChange={(e) =>
setCustomCategory(
e.target.value
)
}
placeholder="Nom de la nouvelle catégorie"
className="w-full bg-gray-700 text-white p-3 rounded-xl outline-none mt-2"
/>
)}
</div>
<div className="mb-4">
<p className="text-sm text-gray-400 mb-2">
Question :
</p>
<textarea
value={newQuestion.question}
onChange={(e) =>
setNewQuestion({
...newQuestion,
question: e.target.value,
})
}
placeholder="Écris ta question ici..."
className="w-full bg-gray-700 text-white p-3 rounded-xl outline-none resize-none"
rows={3}
/>
</div>
<div className="flex gap-3">
<button
onClick={addQuestion}
className="flex-1 bg-green-500 hover:bg-green-600 py-2 rounded-xl font-bold"
>
Ajouter
</button>
<button
onClick={() => {
setIsAdding(false);
setNewQuestion({
category: "",
question: "",
});
setCustomCategory("");
}}
className="flex-1 bg-gray-700 hover:bg-gray-600 py-2 rounded-xl"
>
Annuler
</button>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
<AnimatePresence>
{editingQuestion && (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50 p-4"
onClick={() => setEditingQuestion(null)}
>
<motion.div
initial={{ scale: 0.9 }}
animate={{ scale: 1 }}
exit={{ scale: 0.9 }}
onClick={(e) => e.stopPropagation()}
className="bg-gray-800 rounded-2xl p-6 w-full max-w-lg"
>
<h2 className="text-2xl font-bold mb-4">
Modifier la Question
</h2>
<div className="mb-4">
<p className="text-sm text-gray-400 mb-2">
Catégorie :
</p>
<input
type="text"
value={editingQuestion.category}
onChange={(e) =>
setEditingQuestion({
...editingQuestion,
category: e.target.value,
})
}
className="w-full bg-gray-700 text-white p-3 rounded-xl outline-none"
/>
</div>
<div className="mb-4">
<p className="text-sm text-gray-400 mb-2">
Question :
</p>
<textarea
value={editingQuestion.question}
onChange={(e) =>
setEditingQuestion({
...editingQuestion,
question: e.target.value,
})
}
className="w-full bg-gray-700 text-white p-3 rounded-xl outline-none resize-none"
rows={3}
/>
</div>
<div className="flex gap-3">
<button
onClick={updateQuestion}
className="flex-1 bg-blue-500 hover:bg-blue-600 py-2 rounded-xl font-bold"
>
Sauvegarder
</button>
<button
onClick={() => setEditingQuestion(null)}
className="flex-1 bg-gray-700 hover:bg-gray-600 py-2 rounded-xl"
>
Annuler
</button>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
</div>
</div>
);
}
+459
View File
@@ -0,0 +1,459 @@
"use client";
import { CATEGORIES, STATUSES } from "@/lib/constants";
import { ChecklistItem, Task, TaskCategory, TaskStatus } from "@/types";
import { AnimatePresence, motion } from "framer-motion";
import { useCallback, useEffect, useRef, useState } from "react";
interface TaskDetailModalProps {
task: Task;
onClose: () => void;
onUpdate: (task: Task) => void;
onDelete: (taskId: number) => void;
onComplete: (taskId: number) => void;
}
export default function TaskDetailModal({
task,
onClose,
onUpdate,
onDelete,
onComplete,
}: TaskDetailModalProps) {
const [title, setTitle] = useState(task.text);
const [description, setDescription] = useState(task.description || "");
const [checklist, setChecklist] = useState<ChecklistItem[]>(
task.checklist || []
);
const [newItemText, setNewItemText] = useState("");
const [isEditingTitle, setIsEditingTitle] = useState(false);
const [isEditingDescription, setIsEditingDescription] = useState(false);
const [saving, setSaving] = useState(false);
const titleInputRef = useRef<HTMLInputElement>(null);
const descriptionRef = useRef<HTMLTextAreaElement>(null);
const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const cat = CATEGORIES.find((c) => c.key === task.category);
const autoSave = useCallback(
async (updates: Partial<Task>) => {
if (saveTimeoutRef.current) {
clearTimeout(saveTimeoutRef.current);
}
saveTimeoutRef.current = setTimeout(async () => {
setSaving(true);
try {
const response = await fetch("/api/tasks", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: task.id, ...updates }),
});
if (response.ok) {
const updatedTask = await response.json();
onUpdate(updatedTask);
}
} catch (error) {
console.error("Error saving:", error);
} finally {
setSaving(false);
}
}, 500);
},
[task.id, onUpdate]
);
const handleTitleChange = (newTitle: string) => {
setTitle(newTitle);
if (newTitle.trim()) {
autoSave({ text: newTitle });
}
};
const handleDescriptionChange = (newDescription: string) => {
setDescription(newDescription);
autoSave({ description: newDescription });
};
const addChecklistItem = () => {
if (!newItemText.trim()) return;
const newItem: ChecklistItem = {
id: Date.now().toString(),
text: newItemText,
checked: false,
};
const newChecklist = [...checklist, newItem];
setChecklist(newChecklist);
setNewItemText("");
autoSave({ checklist: newChecklist });
};
const toggleChecklistItem = (itemId: string) => {
const newChecklist = checklist.map((item) =>
item.id === itemId ? { ...item, checked: !item.checked } : item
);
setChecklist(newChecklist);
autoSave({ checklist: newChecklist });
};
const deleteChecklistItem = (itemId: string) => {
const newChecklist = checklist.filter((item) => item.id !== itemId);
setChecklist(newChecklist);
autoSave({ checklist: newChecklist });
};
const updateChecklistItemText = (itemId: string, newText: string) => {
const newChecklist = checklist.map((item) =>
item.id === itemId ? { ...item, text: newText } : item
);
setChecklist(newChecklist);
autoSave({ checklist: newChecklist });
};
const handleCategoryChange = async (newCategory: TaskCategory) => {
try {
const response = await fetch("/api/tasks", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: task.id, category: newCategory }),
});
if (response.ok) {
const updatedTask = await response.json();
onUpdate(updatedTask);
}
} catch (error) {
console.error("Error updating category:", error);
}
};
const handleStatusChange = async (newStatus: TaskStatus) => {
try {
const response = await fetch("/api/tasks", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ id: task.id, status: newStatus }),
});
if (response.ok) {
const updatedTask = await response.json();
onUpdate(updatedTask);
}
} catch (error) {
console.error("Error updating status:", error);
}
};
useEffect(() => {
if (isEditingTitle && titleInputRef.current) {
titleInputRef.current.focus();
titleInputRef.current.select();
}
}, [isEditingTitle]);
useEffect(() => {
if (isEditingDescription && descriptionRef.current) {
descriptionRef.current.focus();
}
}, [isEditingDescription]);
useEffect(() => {
return () => {
if (saveTimeoutRef.current) {
clearTimeout(saveTimeoutRef.current);
}
};
}, []);
const completedCount = checklist.filter((item) => item.checked).length;
const progressPercent =
checklist.length > 0 ? (completedCount / checklist.length) * 100 : 0;
return (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 bg-black/80 flex items-start justify-center z-50 p-4 overflow-y-auto"
onClick={onClose}
>
<motion.div
initial={{ scale: 0.95, y: 20 }}
animate={{ scale: 1, y: 0 }}
exit={{ scale: 0.95, y: 20 }}
onClick={(e) => e.stopPropagation()}
className="bg-gray-800 rounded-2xl w-full max-w-2xl my-8 overflow-hidden"
>
<div
className={`${cat?.color} p-4 flex justify-between items-start`}
>
<div className="flex-1">
{isEditingTitle ? (
<input
ref={titleInputRef}
type="text"
value={title}
onChange={(e) =>
handleTitleChange(e.target.value)
}
onBlur={() => setIsEditingTitle(false)}
onKeyDown={(e) => {
if (e.key === "Enter")
setIsEditingTitle(false);
if (e.key === "Escape") {
setTitle(task.text);
setIsEditingTitle(false);
}
}}
className="w-full bg-white/20 text-white text-xl font-bold px-3 py-2 rounded-lg outline-none"
/>
) : (
<h2
onClick={() => setIsEditingTitle(true)}
className="text-xl font-bold text-white cursor-pointer hover:bg-white/10 px-3 py-2 rounded-lg transition"
>
{title}
</h2>
)}
<p className="text-white/70 text-sm mt-1 px-3">
dans {cat?.label} {task.added}
</p>
</div>
<button
onClick={onClose}
className="text-white/70 hover:text-white text-2xl p-2"
>
</button>
</div>
{saving && (
<div className="bg-blue-500/20 text-blue-400 text-sm px-4 py-2 flex items-center gap-2">
<span className="animate-spin"></span>{" "}
Enregistrement...
</div>
)}
<div className="p-6 space-y-6">
<div>
<h3 className="text-sm font-medium text-gray-400 mb-2">
Statut
</h3>
<div className="flex gap-2">
{STATUSES.map((status) => (
<button
key={status.key}
onClick={() =>
handleStatusChange(status.key)
}
className={`flex-1 py-2 px-3 rounded-lg text-sm font-medium transition ${
task.status === status.key
? `${status.color} text-white`
: "bg-gray-700 hover:bg-gray-600 text-gray-300"
}`}
>
{status.key === "done" ? "✓ " : ""}
{status.label}
</button>
))}
</div>
</div>
<div>
<h3 className="text-sm font-medium text-gray-400 mb-2">
Catégorie
</h3>
<div className="flex gap-2 flex-wrap">
{CATEGORIES.map((category) => (
<button
key={category.key}
onClick={() =>
handleCategoryChange(category.key)
}
className={`py-2 px-4 rounded-lg text-sm font-medium transition ${
task.category === category.key
? `${category.color} text-white`
: "bg-gray-700 hover:bg-gray-600 text-gray-300"
}`}
>
{category.label}
</button>
))}
</div>
</div>
<div>
<h3 className="text-sm font-medium text-gray-400 mb-2">
📝 Description
</h3>
{isEditingDescription ? (
<textarea
ref={descriptionRef}
value={description}
onChange={(e) =>
handleDescriptionChange(e.target.value)
}
onBlur={() => setIsEditingDescription(false)}
placeholder="Ajoute une description plus détaillée..."
className="w-full bg-gray-700 text-white p-4 rounded-xl outline-none resize-none min-h-30 focus:ring-2 focus:ring-blue-500"
/>
) : (
<div
onClick={() => setIsEditingDescription(true)}
className={`w-full bg-gray-700 p-4 rounded-xl cursor-pointer hover:bg-gray-600 transition min-h-20 ${
description ? "text-white" : "text-gray-500"
}`}
>
{description ||
"Ajoute une description plus détaillée..."}
</div>
)}
</div>
<div>
<div className="flex justify-between items-center mb-2">
<h3 className="text-sm font-medium text-gray-400">
Checklist
</h3>
{checklist.length > 0 && (
<span className="text-sm text-gray-500">
{completedCount}/{checklist.length}
</span>
)}
</div>
{checklist.length > 0 && (
<div className="h-2 bg-gray-700 rounded-full mb-4 overflow-hidden">
<motion.div
initial={{ width: 0 }}
animate={{ width: `${progressPercent}%` }}
className="h-full bg-green-500"
/>
</div>
)}
<div className="space-y-2 mb-4">
<AnimatePresence>
{checklist.map((item) => (
<motion.div
key={item.id}
initial={{ opacity: 0, x: -20 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 20 }}
className="flex items-center gap-3 group"
>
<button
onClick={() =>
toggleChecklistItem(item.id)
}
className={`w-5 h-5 rounded border-2 flex items-center justify-center transition ${
item.checked
? "bg-green-500 border-green-500 text-white"
: "border-gray-500 hover:border-gray-400"
}`}
>
{item.checked && "✓"}
</button>
<input
type="text"
value={item.text}
onChange={(e) =>
updateChecklistItemText(
item.id,
e.target.value
)
}
className={`flex-1 bg-transparent outline-none ${
item.checked
? "text-gray-500 line-through"
: "text-white"
}`}
/>
<button
onClick={() =>
deleteChecklistItem(item.id)
}
className="text-gray-500 hover:text-red-400 opacity-0 group-hover:opacity-100 transition"
>
</button>
</motion.div>
))}
</AnimatePresence>
</div>
<div className="flex gap-2">
<input
type="text"
value={newItemText}
onChange={(e) => setNewItemText(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") addChecklistItem();
}}
placeholder="Ajouter un élément..."
className="flex-1 bg-gray-700 text-white px-4 py-2 rounded-lg outline-none focus:ring-2 focus:ring-blue-500"
/>
<button
onClick={addChecklistItem}
disabled={!newItemText.trim()}
className="bg-blue-500 hover:bg-blue-600 disabled:bg-gray-600 disabled:cursor-not-allowed text-white px-4 py-2 rounded-lg transition"
>
+
</button>
</div>
</div>
<div className="flex gap-3 pt-4 border-t border-gray-700">
{task.status !== "done" &&
task.status !== "archived" && (
<button
onClick={async () => {
await handleStatusChange("done");
onClose();
}}
className="flex-1 bg-green-500 hover:bg-green-600 text-white py-3 rounded-xl font-bold transition"
>
Terminer
</button>
)}
{task.status === "done" && (
<button
onClick={() => {
onComplete(task.id);
onClose();
}}
className="flex-1 bg-slate-600 hover:bg-slate-700 text-white py-3 rounded-xl font-bold transition"
>
📦 Archiver
</button>
)}
{task.status === "done" && (
<button
onClick={async () => {
await handleStatusChange("todo");
onClose();
}}
className="flex-1 bg-orange-500 hover:bg-orange-600 text-white py-3 rounded-xl font-bold transition"
>
Réouvrir
</button>
)}
<button
onClick={() => {
onDelete(task.id);
onClose();
}}
className="bg-red-500/20 hover:bg-red-500/30 text-red-400 px-6 py-3 rounded-xl font-bold transition"
>
🗑
</button>
</div>
</div>
</motion.div>
</motion.div>
);
}
+210
View File
@@ -0,0 +1,210 @@
"use client";
import { AnimatePresence, motion, PanInfo } from "framer-motion";
import { useEffect, useRef, useState } from "react";
export interface ToastData {
id: string;
message: string;
type: "success" | "error" | "info" | "warning";
}
interface ToastProps {
toasts: ToastData[];
removeToast: (id: string) => void;
}
const TOAST_DURATION = 5000;
const SWIPE_THRESHOLD = 100;
export default function Toast({ toasts, removeToast }: ToastProps) {
return (
<div className="fixed bottom-4 right-4 z-100 flex flex-col gap-3 max-w-[320px]">
<AnimatePresence>
{toasts.map((toast) => (
<ToastItem
key={toast.id}
toast={toast}
onRemove={() => removeToast(toast.id)}
/>
))}
</AnimatePresence>
</div>
);
}
function ToastItem({
toast,
onRemove,
}: {
toast: ToastData;
onRemove: () => void;
}) {
const [isPaused, setIsPaused] = useState(false);
const [progress, setProgress] = useState(100);
const shouldRemoveRef = useRef(false);
useEffect(() => {
if (isPaused) return;
const interval = setInterval(() => {
setProgress((prev) => {
const newProgress = prev - 100 / (TOAST_DURATION / 10);
if (newProgress <= 0) {
shouldRemoveRef.current = true;
return 0;
}
return newProgress;
});
}, 10);
return () => clearInterval(interval);
}, [isPaused]);
useEffect(() => {
if (shouldRemoveRef.current) {
onRemove();
}
}, [progress, onRemove]);
const handleDragEnd = (_: unknown, info: PanInfo) => {
if (Math.abs(info.offset.x) > SWIPE_THRESHOLD) {
onRemove();
}
};
const config = {
success: {
icon: (
<svg className="w-5 h-5" viewBox="0 0 24 24" fill="none">
<path
d="M9 12l2 2 4-4"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
<circle
cx="12"
cy="12"
r="9"
stroke="currentColor"
strokeWidth="2"
/>
</svg>
),
color: "text-green-500",
progressColor: "bg-green-500",
},
error: {
icon: (
<svg className="w-5 h-5" viewBox="0 0 24 24" fill="none">
<circle
cx="12"
cy="12"
r="9"
stroke="currentColor"
strokeWidth="2"
/>
<path
d="M15 9l-6 6M9 9l6 6"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
/>
</svg>
),
color: "text-red-500",
progressColor: "bg-red-500",
},
info: {
icon: (
<svg className="w-5 h-5" viewBox="0 0 24 24" fill="none">
<circle
cx="12"
cy="12"
r="9"
stroke="currentColor"
strokeWidth="2"
/>
<path
d="M12 8v4M12 16h.01"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
/>
</svg>
),
color: "text-blue-500",
progressColor: "bg-blue-500",
},
warning: {
icon: (
<svg className="w-5 h-5" viewBox="0 0 24 24" fill="none">
<path
d="M12 9v4M12 17h.01"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
/>
<path
d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
),
color: "text-yellow-500",
progressColor: "bg-yellow-500",
},
}[toast.type];
return (
<motion.div
drag="x"
dragConstraints={{ left: 0, right: 0 }}
dragElastic={0.5}
onDragEnd={handleDragEnd}
initial={{ opacity: 0, x: 100, scale: 0.9 }}
animate={{ opacity: 1, x: 0, scale: 1 }}
exit={{ opacity: 0, x: 100, scale: 0.9 }}
transition={{ type: "spring", stiffness: 200, damping: 20 }}
onMouseEnter={() => setIsPaused(true)}
onMouseLeave={() => setIsPaused(false)}
className="relative bg-white dark:bg-gray-800 rounded-lg shadow-lg overflow-hidden border border-gray-200 dark:border-gray-700 cursor-grab active:cursor-grabbing"
>
<div className="flex items-start gap-3 p-4">
<div className={`shrink-0 ${config.color}`}>{config.icon}</div>
<p className="flex-1 text-sm text-gray-800 dark:text-gray-100 font-medium leading-snug select-none">
{toast.message}
</p>
<button
onClick={onRemove}
className="shrink-0 text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 transition-colors"
aria-label="Fermer"
>
<svg className="w-4 h-4" viewBox="0 0 24 24" fill="none">
<path
d="M18 6L6 18M6 6l12 12"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
/>
</svg>
</button>
</div>
{/* Progress bar */}
<div className="h-1 bg-gray-100 dark:bg-gray-700">
<div
className={`h-full ${config.progressColor} transition-none`}
style={{ width: `${progress}%` }}
/>
</div>
</motion.div>
);
}