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
+44
View File
@@ -0,0 +1,44 @@
# Dependencies
node_modules/
/.pnp
.pnp.js
.yarn/install-state.gz
# Build
/.next/
/out/
/build
dist/
*.tsbuildinfo
# Environment
.env
.env*.local
# Debug logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Testing
/coverage
# OS
.DS_Store
Thumbs.db
# IDE
.idea/
.vscode/
*.swp
*.swo
# Certificates
*.pem
# Vercel
.vercel
# Misc
*.log
+49
View File
@@ -0,0 +1,49 @@
import NextAuth, { NextAuthOptions } from "next-auth";
import DiscordProvider from "next-auth/providers/discord";
const ALLOWED_DISCORD_IDS =
process.env.ALLOWED_DISCORD_IDS?.split(",").map((id) => id.trim()) || [];
const ADMIN_DISCORD_IDS =
process.env.ADMIN_DISCORD_IDS?.split(",").map((id) => id.trim()) || [];
export const authOptions: NextAuthOptions = {
providers: [
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID!,
clientSecret: process.env.DISCORD_CLIENT_SECRET!,
}),
],
callbacks: {
async signIn({ profile }) {
if (profile?.id && ALLOWED_DISCORD_IDS.includes(profile.id)) {
return true;
}
return "/unauthorized";
},
async jwt({ token, profile }) {
if (profile) {
token.discordId = profile.id;
token.isAdmin = ADMIN_DISCORD_IDS.includes(
profile.id as string
);
}
return token;
},
async session({ session, token }) {
if (session.user) {
session.user.discordId = token.discordId as string;
session.user.isAdmin = token.isAdmin as boolean;
}
return session;
},
},
pages: {
signIn: "/login",
error: "/unauthorized",
},
secret: process.env.NEXTAUTH_SECRET,
};
const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };
+171
View File
@@ -0,0 +1,171 @@
import { initDatabase, query } from "@/lib/db";
import { getServerSession } from "next-auth";
import { NextRequest, NextResponse } from "next/server";
import { authOptions } from "../auth/[...nextauth]/route";
async function isAdmin() {
const session = await getServerSession(authOptions);
return session?.user?.isAdmin === true;
}
export async function GET(request: NextRequest) {
try {
await initDatabase();
const { searchParams } = new URL(request.url);
const mode = searchParams.get("mode");
let result;
if (mode) {
result = await query(
"SELECT * FROM questions WHERE mode = $1 ORDER BY order_index ASC, id ASC",
[mode]
);
} else {
result = await query(
"SELECT * FROM questions ORDER BY mode, order_index ASC, id ASC"
);
}
return NextResponse.json(result.rows);
} catch (error) {
console.error("Error fetching questions:", error);
return NextResponse.json(
{ error: "Failed to fetch questions" },
{ status: 500 }
);
}
}
export async function POST(request: NextRequest) {
try {
if (!(await isAdmin())) {
return NextResponse.json(
{ error: "Unauthorized" },
{ status: 403 }
);
}
await initDatabase();
const body = await request.json();
const { category, question, mode } = body;
if (!category || !question || !mode) {
return NextResponse.json(
{ error: "Missing required fields" },
{ status: 400 }
);
}
const maxOrder = await query(
"SELECT COALESCE(MAX(order_index), -1) as max_order FROM questions WHERE mode = $1",
[mode]
);
const newOrder = parseInt(maxOrder.rows[0].max_order) + 1;
const result = await query(
"INSERT INTO questions (category, question, mode, order_index) VALUES ($1, $2, $3, $4) RETURNING *",
[category, question, mode, newOrder]
);
return NextResponse.json(result.rows[0], { status: 201 });
} catch (error) {
console.error("Error creating question:", error);
return NextResponse.json(
{ error: "Failed to create question" },
{ status: 500 }
);
}
}
export async function PATCH(request: NextRequest) {
try {
if (!(await isAdmin())) {
return NextResponse.json(
{ error: "Unauthorized" },
{ status: 403 }
);
}
const body = await request.json();
const { id, category, question, order_index } = body;
if (!id) {
return NextResponse.json(
{ error: "Missing question id" },
{ status: 400 }
);
}
const updates: string[] = [];
const args: (string | number)[] = [];
let paramIndex = 1;
if (category !== undefined) {
updates.push(`category = $${paramIndex++}`);
args.push(category);
}
if (question !== undefined) {
updates.push(`question = $${paramIndex++}`);
args.push(question);
}
if (order_index !== undefined) {
updates.push(`order_index = $${paramIndex++}`);
args.push(order_index);
}
if (updates.length === 0) {
return NextResponse.json(
{ error: "No fields to update" },
{ status: 400 }
);
}
args.push(id);
const result = await query(
`UPDATE questions SET ${updates.join(
", "
)} WHERE id = $${paramIndex} RETURNING *`,
args
);
return NextResponse.json(result.rows[0]);
} catch (error) {
console.error("Error updating question:", error);
return NextResponse.json(
{ error: "Failed to update question" },
{ status: 500 }
);
}
}
export async function DELETE(request: NextRequest) {
try {
if (!(await isAdmin())) {
return NextResponse.json(
{ error: "Unauthorized" },
{ status: 403 }
);
}
const { searchParams } = new URL(request.url);
const id = searchParams.get("id");
if (!id) {
return NextResponse.json(
{ error: "Missing question id" },
{ status: 400 }
);
}
await query("DELETE FROM questions WHERE id = $1", [id]);
return NextResponse.json({ success: true });
} catch (error) {
console.error("Error deleting question:", error);
return NextResponse.json(
{ error: "Failed to delete question" },
{ status: 500 }
);
}
}
+104
View File
@@ -0,0 +1,104 @@
import { initDatabase, query } from "@/lib/db";
import { SessionAnswer } from "@/types";
import { NextRequest, NextResponse } from "next/server";
export async function GET() {
try {
await initDatabase();
const sessionsResult = await query(
"SELECT * FROM sessions ORDER BY created_at DESC"
);
const sessions = await Promise.all(
sessionsResult.rows.map(async (session: any) => {
const answersResult = await query(
"SELECT * FROM session_answers WHERE session_id = $1 ORDER BY question_index",
[session.id]
);
return {
id: session.id,
mode: session.mode,
created_at: session.created_at,
exported_at: session.exported_at,
answers: answersResult.rows.map((a: any) => ({
questionIndex: a.question_index,
category: a.category,
question: a.question,
answer: a.answer,
})),
};
})
);
return NextResponse.json(sessions);
} catch (error) {
console.error("Error fetching sessions:", error);
return NextResponse.json(
{ error: "Failed to fetch sessions" },
{ status: 500 }
);
}
}
export async function POST(request: NextRequest) {
try {
await initDatabase();
const body = await request.json();
const { mode, answers } = body;
if (!mode || !answers) {
return NextResponse.json(
{ error: "Missing required fields" },
{ status: 400 }
);
}
const sessionResult = await query(
"INSERT INTO sessions (mode) VALUES ($1) RETURNING *",
[mode]
);
const sessionId = sessionResult.rows[0].id;
for (const answer of answers as SessionAnswer[]) {
if (answer.answer.trim()) {
await query(
"INSERT INTO session_answers (session_id, question_index, category, question, answer) VALUES ($1, $2, $3, $4, $5)",
[
sessionId,
answer.questionIndex,
answer.category,
answer.question,
answer.answer,
]
);
}
}
const answersData = await query(
"SELECT * FROM session_answers WHERE session_id = $1 ORDER BY question_index",
[sessionId]
);
const newSession = {
id: sessionResult.rows[0].id,
mode: sessionResult.rows[0].mode,
created_at: sessionResult.rows[0].created_at,
answers: answersData.rows.map((a: any) => ({
questionIndex: a.question_index,
category: a.category,
question: a.question,
answer: a.answer,
})),
};
return NextResponse.json(newSession, { status: 201 });
} catch (error) {
console.error("Error creating session:", error);
return NextResponse.json(
{ error: "Failed to create session" },
{ status: 500 }
);
}
}
+135
View File
@@ -0,0 +1,135 @@
import { initDatabase, query } from "@/lib/db";
import { NextRequest, NextResponse } from "next/server";
export async function GET() {
try {
await initDatabase();
const result = await query(
"SELECT * FROM tasks ORDER BY created_at DESC"
);
return NextResponse.json(result.rows);
} catch (error) {
console.error("Error fetching tasks:", error);
return NextResponse.json(
{ error: "Failed to fetch tasks" },
{ status: 500 }
);
}
}
export async function POST(request: NextRequest) {
try {
await initDatabase();
const body = await request.json();
const { text, category, description } = body;
if (!text || !category) {
return NextResponse.json(
{ error: "Missing required fields" },
{ status: 400 }
);
}
const added = new Date().toLocaleDateString("fr-FR");
const result = await query(
"INSERT INTO tasks (text, description, checklist, category, status, added) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *",
[text, description || null, "[]", category, "todo", added]
);
return NextResponse.json(result.rows[0], { status: 201 });
} catch (error) {
console.error("Error creating task:", error);
return NextResponse.json(
{ error: "Failed to create task" },
{ status: 500 }
);
}
}
export async function PATCH(request: NextRequest) {
try {
const body = await request.json();
const { id, status, category, text, description, checklist } = body;
if (!id) {
return NextResponse.json(
{ error: "Missing task id" },
{ status: 400 }
);
}
const updates: string[] = [];
const args: (string | number | null)[] = [];
let paramIndex = 1;
if (status !== undefined) {
updates.push(`status = $${paramIndex++}`);
args.push(status);
}
if (category !== undefined) {
updates.push(`category = $${paramIndex++}`);
args.push(category);
}
if (text !== undefined) {
updates.push(`text = $${paramIndex++}`);
args.push(text);
}
if (description !== undefined) {
updates.push(`description = $${paramIndex++}`);
args.push(description);
}
if (checklist !== undefined) {
updates.push(`checklist = $${paramIndex++}`);
args.push(JSON.stringify(checklist));
}
if (updates.length === 0) {
return NextResponse.json(
{ error: "No fields to update" },
{ status: 400 }
);
}
args.push(id);
const result = await query(
`UPDATE tasks SET ${updates.join(
", "
)} WHERE id = $${paramIndex} RETURNING *`,
args
);
return NextResponse.json(result.rows[0]);
} catch (error) {
console.error("Error updating task:", error);
return NextResponse.json(
{ error: "Failed to update task" },
{ status: 500 }
);
}
}
export async function DELETE(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const id = searchParams.get("id");
if (!id) {
return NextResponse.json(
{ error: "Missing task id" },
{ status: 400 }
);
}
await query("DELETE FROM tasks WHERE id = $1", [id]);
return NextResponse.json({ success: true });
} catch (error) {
console.error("Error deleting task:", error);
return NextResponse.json(
{ error: "Failed to delete task" },
{ status: 500 }
);
}
}
+37
View File
@@ -0,0 +1,37 @@
@import "tailwindcss";
@layer base {
body {
background-color: #111827;
color: #ffffff;
overflow-x: hidden;
}
textarea {
scrollbar-width: thin;
scrollbar-color: #4b5563 #1f2937;
}
textarea::-webkit-scrollbar {
width: 8px;
}
textarea::-webkit-scrollbar-track {
background: #1f2937;
}
textarea::-webkit-scrollbar-thumb {
background: #4b5563;
border-radius: 4px;
}
textarea::-webkit-scrollbar-thumb:hover {
background: #6b7280;
}
}
@layer utilities {
.text-balance {
text-wrap: balance;
}
}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 669 B

+22
View File
@@ -0,0 +1,22 @@
import AuthProvider from "@/components/AuthProvider";
import type { Metadata } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: "Brain Dump",
description: "Organise tes pensées avec Brain Dump",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="fr">
<body className="antialiased bg-gray-900 text-white">
<AuthProvider>{children}</AuthProvider>
</body>
</html>
);
}
+74
View File
@@ -0,0 +1,74 @@
"use client";
import { motion } from "framer-motion";
import { signIn, useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
export default function LoginPage() {
const { data: session, status } = useSession();
const router = useRouter();
useEffect(() => {
if (session) {
router.push("/");
}
}, [session, router]);
if (status === "loading") {
return (
<div className="min-h-screen bg-gray-900 flex items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-500"></div>
</div>
);
}
return (
<div className="min-h-screen bg-gray-900 flex items-center justify-center p-4">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
className="bg-gray-800 rounded-2xl p-8 max-w-md w-full shadow-2xl border border-gray-700"
>
<div className="text-center mb-8">
<motion.div
initial={{ scale: 0 }}
animate={{ scale: 1 }}
transition={{ type: "spring", duration: 0.6 }}
className="text-6xl mb-4"
>
🧠
</motion.div>
<h1 className="text-3xl font-bold text-white mb-2">
Brain Dump
</h1>
<p className="text-gray-400">
Connectez-vous pour accéder à l&apos;application
</p>
</div>
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
onClick={() => signIn("discord", { callbackUrl: "/" })}
className="w-full flex items-center justify-center gap-3 bg-[#5865F2] hover:bg-[#4752C4] text-white font-semibold py-4 px-6 rounded-xl transition-colors duration-200"
>
<svg
className="w-6 h-6"
viewBox="0 0 24 24"
fill="currentColor"
>
<path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028 14.09 14.09 0 0 0 1.226-1.994.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z" />
</svg>
Se connecter avec Discord
</motion.button>
<p className="text-center text-gray-500 text-sm mt-6">
Seuls les utilisateurs autorisés peuvent accéder à cette
application.
</p>
</motion.div>
</div>
);
}
+39
View File
@@ -0,0 +1,39 @@
"use client";
import { motion } from "framer-motion";
import Link from "next/link";
export default function NotFound() {
return (
<div className="min-h-screen bg-gray-900 flex items-center justify-center p-4">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
className="text-center"
>
<motion.div
initial={{ scale: 0 }}
animate={{ scale: 1 }}
transition={{ type: "spring", duration: 0.6 }}
className="text-8xl mb-6"
>
🤔
</motion.div>
<h1 className="text-4xl font-bold text-white mb-4">404</h1>
<p className="text-gray-400 mb-8">
Cette page n&apos;existe pas
</p>
<Link href="/">
<motion.button
whileHover={{ scale: 1.05 }}
whileTap={{ scale: 0.95 }}
className="bg-indigo-500 hover:bg-indigo-600 text-white font-semibold py-3 px-8 rounded-xl transition-colors"
>
Retour à l&apos;accueil
</motion.button>
</Link>
</motion.div>
</div>
);
}
+228
View File
@@ -0,0 +1,228 @@
"use client";
import CompletePage from "@/components/CompletePage";
import Confetti from "@/components/Confetti";
import HomePage from "@/components/HomePage";
import KanbanBoard from "@/components/KanbanBoard";
import Questionnaire from "@/components/Questionnaire";
import QuestionsDashboard from "@/components/QuestionsDashboard";
import { CRISIS_QUESTIONS, NORMAL_QUESTIONS } from "@/lib/constants";
import { Question, QuestionMode, SessionAnswer, TaskCategory } from "@/types";
import { signOut, useSession } from "next-auth/react";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
type Screen = "home" | "questions" | "complete" | "kanban" | "dashboard";
export default function Home() {
const { data: session, status } = useSession();
const router = useRouter();
const [screen, setScreen] = useState<Screen>("home");
const [mode, setMode] = useState<QuestionMode>("normal");
const [sessionAnswers, setSessionAnswers] = useState<SessionAnswer[]>([]);
const [showConfetti, setShowConfetti] = useState(false);
const [dbQuestions, setDbQuestions] = useState<Question[]>([]);
const [questionsLoaded, setQuestionsLoaded] = useState(false);
useEffect(() => {
if (status === "unauthenticated") {
router.push("/login");
}
}, [status, router]);
useEffect(() => {
if (status !== "authenticated") return;
const loadQuestions = async () => {
try {
const response = await fetch("/api/questions");
const data = await response.json();
setDbQuestions(data);
} catch (error) {
console.error("Error loading questions:", error);
} finally {
setQuestionsLoaded(true);
}
};
loadQuestions();
}, [status]);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === "Escape") {
if (screen === "questions") {
if (confirm("Abandonner le questionnaire ?")) {
setScreen("home");
}
} else if (screen !== "home") {
setScreen("home");
}
}
};
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [screen]);
const startQuestionnaire = (crisisMode: boolean) => {
setMode(crisisMode ? "crisis" : "normal");
setScreen("questions");
};
const handleAddTask = async (text: string, category: TaskCategory) => {
const response = await fetch("/api/tasks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text, category }),
});
if (!response.ok) {
throw new Error("Failed to add task");
}
};
const handleQuestionnaireComplete = async (answers: SessionAnswer[]) => {
setSessionAnswers(answers);
try {
await fetch("/api/sessions", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ mode, answers }),
});
} catch (error) {
console.error("Error saving session:", error);
}
setShowConfetti(true);
setTimeout(() => setShowConfetti(false), 3000);
setScreen("complete");
};
const exportSession = () => {
const now = new Date();
const date = now.toISOString().split("T")[0]; // 2026-01-02
const time = now.toTimeString().split(" ")[0].replace(/:/g, "-"); // 23-24-21
const modeLabel = mode === "crisis" ? "crise" : "normal";
const filename = `${date}_${time}_dump_${modeLabel}.md`;
const modeEmoji = mode === "crisis" ? "🆘" : "🌿";
let markdown = `# ${modeEmoji} Brain Dump - ${
mode === "crisis" ? "CRISE" : "NORMAL"
}\n\n`;
markdown += `📅 **Date:** ${now.toLocaleString("fr-FR")}\n\n`;
sessionAnswers.forEach((answer) => {
if (answer.answer.trim()) {
markdown += `## ${answer.category}\n**Q:** ${answer.question}\n**R:** ${answer.answer}\n\n`;
}
});
const blob = new Blob([markdown], { type: "text/markdown" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
};
const getQuestions = (questionMode: QuestionMode) => {
const modeQuestions = dbQuestions.filter(
(q) => q.mode === questionMode
);
if (modeQuestions.length > 0) {
return modeQuestions;
}
return questionMode === "crisis" ? CRISIS_QUESTIONS : NORMAL_QUESTIONS;
};
const questions = getQuestions(mode);
const handleDashboardBack = async () => {
try {
const response = await fetch("/api/questions");
const data = await response.json();
setDbQuestions(data);
} catch (error) {
console.error("Error reloading questions:", error);
}
setScreen("home");
};
return (
<>
{status === "loading" && (
<div className="min-h-screen bg-gray-900 flex items-center justify-center">
<div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-500"></div>
</div>
)}
{status === "authenticated" && (
<>
<div className="fixed top-4 right-4 z-50 flex items-center gap-3">
<div className="flex items-center gap-2 bg-gray-800/80 backdrop-blur-sm px-3 py-2 rounded-lg border border-gray-700">
{session?.user?.image && (
<img
src={session.user.image}
alt="Avatar"
className="w-6 h-6 rounded-full"
/>
)}
<span className="text-sm text-gray-300">
{session?.user?.name}
</span>
</div>
<button
onClick={() => signOut({ callbackUrl: "/login" })}
className="bg-red-500/20 hover:bg-red-500/30 text-red-400 px-3 py-2 rounded-lg text-sm transition-colors border border-red-500/30"
>
Déconnexion
</button>
</div>
<Confetti show={showConfetti} />
{screen === "home" && (
<HomePage
onStartNormal={() => startQuestionnaire(false)}
onStartCrisis={() => startQuestionnaire(true)}
onOpenKanban={() => setScreen("kanban")}
onOpenDashboard={() => setScreen("dashboard")}
isAdmin={session?.user?.isAdmin}
/>
)}
{screen === "questions" && (
<Questionnaire
questions={questions}
mode={mode}
onComplete={handleQuestionnaireComplete}
onBack={() => setScreen("home")}
onAddTask={handleAddTask}
/>
)}
{screen === "complete" && (
<CompletePage
answers={sessionAnswers}
mode={mode}
onGoHome={() => setScreen("home")}
onGoToKanban={() => setScreen("kanban")}
onExport={exportSession}
/>
)}
{screen === "kanban" && (
<KanbanBoard onBack={() => setScreen("home")} />
)}
{screen === "dashboard" && (
<QuestionsDashboard onBack={handleDashboardBack} />
)}
</>
)}
</>
);
}
+49
View File
@@ -0,0 +1,49 @@
"use client";
import { motion } from "framer-motion";
import Link from "next/link";
export default function UnauthorizedPage() {
return (
<div className="min-h-screen bg-gray-900 flex items-center justify-center p-4">
<motion.div
initial={{ opacity: 0, y: 20 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5 }}
className="bg-gray-800 rounded-2xl p-8 max-w-md w-full shadow-2xl border border-red-500/30"
>
<div className="text-center mb-8">
<motion.div
initial={{ scale: 0, rotate: -180 }}
animate={{ scale: 1, rotate: 0 }}
transition={{ type: "spring", duration: 0.8 }}
className="text-6xl mb-4"
>
🚫
</motion.div>
<h1 className="text-3xl font-bold text-red-400 mb-2">
Accès Refusé
</h1>
<p className="text-gray-400 mb-4">
Vous n&apos;êtes pas autorisé à accéder à cette
application.
</p>
<p className="text-gray-500 text-sm">
Cette application est réservée aux utilisateurs
autorisés uniquement.
</p>
</div>
<Link href="/login">
<motion.button
whileHover={{ scale: 1.02 }}
whileTap={{ scale: 0.98 }}
className="w-full bg-gray-700 hover:bg-gray-600 text-white font-semibold py-3 px-6 rounded-xl transition-colors duration-200"
>
Réessayer avec un autre compte
</motion.button>
</Link>
</motion.div>
</div>
);
}
+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>
);
}
+185
View File
@@ -0,0 +1,185 @@
import { CategoryConfig, Question, StatusConfig } from "@/types";
export const NORMAL_QUESTIONS: Question[] = [
{
category: "Brain",
question: "Qu'ai-je appris de nouveau aujourd'hui ?",
mode: "normal",
},
{
category: "Brain",
question: "Quel problème ai-je résolu et comment ?",
mode: "normal",
},
{
category: "Brain",
question: "Quelle pensée récurrente occupe mon esprit ?",
mode: "normal",
},
{
category: "Brain",
question: "Qu'est-ce qui m'a mentalement fatigué aujourd'hui ?",
mode: "normal",
},
{
category: "Émotions",
question: "Comment je me sens maintenant ? (en un mot)",
mode: "normal",
},
{
category: "Émotions",
question: "Quel événement a le plus impacté mon humeur aujourd'hui ?",
mode: "normal",
},
{
category: "Émotions",
question: "De quelle émotion ai-je besoin de me libérer ?",
mode: "normal",
},
{
category: "Corps",
question: "Quel est mon niveau d'énergie actuel ? (1-10)",
mode: "normal",
},
{
category: "Corps",
question: "Ai-je pris soin de mon corps aujourd'hui ? Comment ?",
mode: "normal",
},
{
category: "Actions",
question: "Quelle est ma priorité #1 pour demain matin ?",
mode: "normal",
},
{
category: "Actions",
question: "Qu'ai-je accompli aujourd'hui dont je suis fier·e ?",
mode: "normal",
},
{
category: "Relations",
question: "Quelle interaction m'a marqué aujourd'hui ?",
mode: "normal",
},
{
category: "Créativité",
question: "Quelle idée créative m'inspire en ce moment ?",
mode: "normal",
},
{
category: "Clôture",
question: "Pour quoi suis-je reconnaissant·e aujourd'hui ?",
mode: "normal",
},
{
category: "Clôture",
question: "Que puis-je lâcher avant de dormir ?",
mode: "normal",
},
];
export const CRISIS_QUESTIONS: Question[] = [
{
category: "Sécurité",
question: "Où suis-je en ce moment ? Suis-je en sécurité physique ?",
mode: "crisis",
},
{
category: "Sécurité",
question: "Suis-je en danger émotionnel ou psychologique immédiat ?",
mode: "crisis",
},
{
category: "Sécurité",
question: "Ai-je besoin d'aide médicale immédiate ?",
mode: "crisis",
},
{
category: "Ancrage",
question: "Nomme 5 choses que je vois autour de moi",
mode: "crisis",
},
{
category: "Ancrage",
question: "Nomme 3 sons que j'entends en ce moment",
mode: "crisis",
},
{
category: "Ancrage",
question: "Nomme 1 sensation physique (température, texture, contact)",
mode: "crisis",
},
{
category: "Besoins",
question: "Ai-je mangé dans les dernières 6 heures ?",
mode: "crisis",
},
{
category: "Besoins",
question: "Ai-je bu de l'eau récemment ?",
mode: "crisis",
},
{
category: "Émotions",
question: "Quelle émotion domine maintenant ? (en un mot)",
mode: "crisis",
},
{
category: "Émotions",
question: "Niveau de détresse : 1 (faible) à 10 (insupportable)",
mode: "crisis",
},
{
category: "Respiration",
question: "Peux-tu prendre 3 respirations lentes maintenant ?",
mode: "crisis",
},
{
category: "Action",
question:
"Quelle est la plus PETITE action que je peux faire maintenant ?",
mode: "crisis",
},
];
export const CATEGORIES: CategoryConfig[] = [
{
key: "urgent",
label: "Urgent",
color: "bg-red-500",
hover: "hover:bg-red-600",
border: "border-red-500",
},
{
key: "deadline",
label: "Deadline",
color: "bg-orange-500",
hover: "hover:bg-orange-600",
border: "border-orange-500",
},
{
key: "admin",
label: "Admin",
color: "bg-purple-500",
hover: "hover:bg-purple-600",
border: "border-purple-500",
},
{
key: "creative",
label: "Créatif",
color: "bg-teal-500",
hover: "hover:bg-teal-600",
border: "border-teal-500",
},
];
export const STATUSES: StatusConfig[] = [
{ key: "todo", label: "À faire", color: "bg-gray-600" },
{ key: "doing", label: "En cours", color: "bg-orange-500" },
{ key: "done", label: "Terminé", color: "bg-green-500" },
];
export const ALL_STATUSES: StatusConfig[] = [
...STATUSES,
{ key: "archived", label: "Archivé", color: "bg-slate-700" },
];
+76
View File
@@ -0,0 +1,76 @@
import { Pool } from "pg";
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl:
process.env.NODE_ENV === "production"
? { rejectUnauthorized: false }
: false,
});
export async function query(text: string, params?: any[]) {
const result = await pool.query(text, params);
return result;
}
export async function initDatabase() {
await query(`
CREATE TABLE IF NOT EXISTS tasks (
id SERIAL PRIMARY KEY,
text TEXT NOT NULL,
description TEXT,
checklist JSONB DEFAULT '[]',
category VARCHAR(20) NOT NULL CHECK(category IN ('urgent', 'deadline', 'admin', 'creative')),
status VARCHAR(20) NOT NULL DEFAULT 'todo' CHECK(status IN ('todo', 'doing', 'done', 'archived')),
added VARCHAR(50) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
await query(`
CREATE TABLE IF NOT EXISTS sessions (
id SERIAL PRIMARY KEY,
mode VARCHAR(20) NOT NULL CHECK(mode IN ('normal', 'crisis')),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
exported_at TIMESTAMP
)
`);
await query(`
CREATE TABLE IF NOT EXISTS session_answers (
id SERIAL PRIMARY KEY,
session_id INTEGER NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
question_index INTEGER NOT NULL,
category TEXT NOT NULL,
question TEXT NOT NULL,
answer TEXT NOT NULL
)
`);
await query(`
CREATE TABLE IF NOT EXISTS questions (
id SERIAL PRIMARY KEY,
category TEXT NOT NULL,
question TEXT NOT NULL,
mode VARCHAR(20) NOT NULL CHECK(mode IN ('normal', 'crisis')),
order_index INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
await query(
`CREATE INDEX IF NOT EXISTS idx_tasks_category ON tasks(category)`
);
await query(`CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status)`);
await query(
`CREATE INDEX IF NOT EXISTS idx_sessions_mode ON sessions(mode)`
);
await query(
`CREATE INDEX IF NOT EXISTS idx_session_answers_session_id ON session_answers(session_id)`
);
await query(
`CREATE INDEX IF NOT EXISTS idx_questions_mode ON questions(mode)`
);
}
export default { query, initDatabase };
+12
View File
@@ -0,0 +1,12 @@
import { initDatabase } from "@/lib/db";
(async () => {
try {
await initDatabase();
console.log("✅ Database initialized");
} catch (error) {
console.error("❌ Database initialization failed:", error);
}
})();
export {};
+6
View File
@@ -0,0 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/dev/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
+7
View File
@@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: "standalone",
};
export default nextConfig;
+37
View File
@@ -0,0 +1,37 @@
{
"name": "brain-dump",
"version": "1.0.0",
"author": "Jessy DAVID - https://jessy-david.dev",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
"build": "next build",
"start": "next start",
"lint": "eslint",
"db:init": "node scripts/init-db.js",
"db:seed": "node scripts/seed-questions.js"
},
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"dotenv": "^17.2.3",
"framer-motion": "^11.13.5",
"next": "16.1.1",
"next-auth": "^4.24.10",
"pg": "^8.13.1",
"react": "19.2.3",
"react-dom": "19.2.3"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/pg": "^8.11.10",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "16.1.1",
"tailwindcss": "^4",
"typescript": "^5"
}
}
+4353
View File
File diff suppressed because it is too large Load Diff
+5
View File
@@ -0,0 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};
export default config;
View File
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 669 B

+78
View File
@@ -0,0 +1,78 @@
const { Pool } = require("pg");
require("dotenv").config({ path: ".env.local" });
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
async function init() {
try {
await pool.query(`
CREATE TABLE IF NOT EXISTS tasks (
id SERIAL PRIMARY KEY,
text TEXT NOT NULL,
description TEXT,
checklist JSONB DEFAULT '[]',
category VARCHAR(20) NOT NULL CHECK(category IN ('urgent', 'deadline', 'admin', 'creative')),
status VARCHAR(20) NOT NULL DEFAULT 'todo' CHECK(status IN ('todo', 'doing', 'done', 'archived')),
added VARCHAR(50) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS sessions (
id SERIAL PRIMARY KEY,
mode VARCHAR(20) NOT NULL CHECK(mode IN ('normal', 'crisis')),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
exported_at TIMESTAMP
)
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS session_answers (
id SERIAL PRIMARY KEY,
session_id INTEGER NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
question_index INTEGER NOT NULL,
category TEXT NOT NULL,
question TEXT NOT NULL,
answer TEXT NOT NULL
)
`);
await pool.query(`
CREATE TABLE IF NOT EXISTS questions (
id SERIAL PRIMARY KEY,
category TEXT NOT NULL,
question TEXT NOT NULL,
mode VARCHAR(20) NOT NULL CHECK(mode IN ('normal', 'crisis')),
order_index INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
await pool.query(
`CREATE INDEX IF NOT EXISTS idx_tasks_category ON tasks(category)`
);
await pool.query(
`CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status)`
);
await pool.query(
`CREATE INDEX IF NOT EXISTS idx_sessions_mode ON sessions(mode)`
);
await pool.query(
`CREATE INDEX IF NOT EXISTS idx_session_answers_session_id ON session_answers(session_id)`
);
await pool.query(
`CREATE INDEX IF NOT EXISTS idx_questions_mode ON questions(mode)`
);
console.log("✅ Database initialized successfully");
process.exit(0);
} catch (error) {
console.error("❌ Error initializing database:", error);
process.exit(1);
}
}
init();
+139
View File
@@ -0,0 +1,139 @@
const { Pool } = require("pg");
require("dotenv").config({ path: ".env.local" });
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
const NORMAL_QUESTIONS = [
["Brain", "Qu'ai-je appris de nouveau aujourd'hui ?"],
["Brain", "Quel problème ai-je résolu et comment ?"],
["Brain", "Quelle pensée récurrente occupe mon esprit ?"],
["Brain", "Qu'est-ce qui m'a mentalement fatigué aujourd'hui ?"],
["Brain", "Qu'est-ce qui m'a mentalement apaisé aujourd'hui ?"],
["Brain", "Ai-je trop optimisé ou itéré sur quelque chose ?"],
["Émotions", "Comment je me sens maintenant ? (en un mot)"],
["Émotions", "Quel événement a le plus impacté mon humeur aujourd'hui ?"],
["Émotions", "De quelle émotion ai-je besoin de me libérer ?"],
["Émotions", "De quoi aurais-je eu besoin émotionnellement aujourd'hui ?"],
["Émotions", "Ai-je été dur·e avec moi-même aujourd'hui ?"],
["Corps", "Quel est mon niveau d'énergie actuel ? (1-10)"],
["Corps", "Ai-je pris soin de mon corps aujourd'hui ? Comment ?"],
["Corps", "Quelle tension ou douleur physique je ressens ?"],
["Corps", "Qu'est-ce qui a soulagé mon corps aujourd'hui ?"],
["Corps", "Qu'est-ce qui a aggravé mes douleurs ?"],
["Corps", "Ai-je respecté mes limites physiques ?"],
["Actions", "Quelle est ma priorité #1 pour demain matin ?"],
["Actions", "Qu'ai-je accompli aujourd'hui dont je suis fier·e ?"],
["Actions", "Qu'est-ce qui bloque ma productivité actuellement ?"],
["Actions", "À quel rythme ai-je réellement avancé aujourd'hui ?"],
["Actions", "Ai-je le droit de ne rien faire ce soir ?"],
["Relations", "Quelle interaction m'a marqué aujourd'hui ?"],
["Relations", "De qui ai-je besoin de me rapprocher ?"],
["Relations", "Quel besoin relationnel n'est pas comblé en ce moment ?"],
["Relations", "Me suis-je senti·e respecté·e aujourd'hui ?"],
["Relations", "Ai-je posé ou identifié une limite importante ?"],
["Sécurité", "Mon environnement actuel est-il sain et sûr ?"],
[
"Sécurité",
"Quelles substances ai-je consommées ? (alcool, café, médicaments)",
],
["Sécurité", "De quelles ressources matérielles ai-je besoin ?"],
["Créativité", "Quelle idée créative m'inspire en ce moment ?"],
["Créativité", "Sur quel projet personnel ai-je envie d'avancer ?"],
["Créativité", "Qu'est-ce qui a stimulé mon imagination aujourd'hui ?"],
["Créativité", "Ai-je créé sans objectif ou rendement aujourd'hui ?"],
["Créativité", "Qu'est-ce qui m'inspire sans me fatiguer ?"],
["Clôture", "Pour quoi suis-je reconnaissant·e aujourd'hui ?"],
["Clôture", "Quelle petite victoire mérite d'être célébrée ?"],
["Clôture", "Que puis-je lâcher avant de dormir ?"],
["Clôture", "De quoi mon corps a-t-il besoin cette nuit ?"],
["Clôture", "Puis-je m'autoriser à m'arrêter maintenant ?"],
[
"Clôture",
"Qu'est-ce que je peux faire à 1 % pour me lancer sur autre chose ?",
],
];
const CRISIS_QUESTIONS = [
["Sécurité", "Où suis-je en ce moment ? Suis-je en sécurité physique ?"],
["Sécurité", "Suis-je en danger émotionnel ou psychologique immédiat ?"],
["Sécurité", "Ai-je besoin d'aide médicale immédiate ?"],
["Sécurité", "Qui peut venir m'aider maintenant ? (nom et numéro)"],
["Ancrage", "Nomme 5 choses que je vois autour de moi"],
["Ancrage", "Nomme 3 sons que j'entends en ce moment"],
["Ancrage", "Nomme 1 sensation physique (température, texture, contact)"],
["Besoins", "Ai-je mangé dans les dernières 6 heures ?"],
["Besoins", "Ai-je bu de l'eau récemment ?"],
["Besoins", "Ai-je dormi ces dernières 24 heures ?"],
["Émotions", "Quelle émotion domine maintenant ? (en un mot)"],
["Émotions", "Niveau de détresse : 1 (faible) à 10 (insupportable)"],
["Respiration", "Peux-tu prendre 3 respirations lentes maintenant ?"],
["Respiration", "Comment te sens-tu après ces respirations ?"],
["Pensées", "Quelle pensée est la plus intense en ce moment ?"],
["Pensées", "Cette pensée est-elle un FAIT ou une INTERPRÉTATION ?"],
["Pensées", "Cette situation sera-t-elle encore aussi intense dans 24h ?"],
["Pensées", "Que dirais-je à un·e ami·e dans la même situation ?"],
[
"Soutien",
"Ai-je quelqu'un avec qui je peux être vulnérable maintenant ?",
],
[
"Soutien",
"Qu'est-ce qui me réconforte habituellement dans ces moments ?",
],
[
"Action",
"Quelle est la plus PETITE action que je peux faire maintenant ?",
],
["Action", "Qui puis-je appeler si ça empire ? (nom + numéro à portée)"],
[
"Ressources",
"Numéros d'urgence : 15 (SAMU), 112 (Urgences EU), 3114 (Suicide)",
],
["Ressources", "Y a-t-il un lieu sûr où je peux aller maintenant ?"],
[
"Récupération",
"Puis-je me reposer sans résoudre le problème maintenant ?",
],
];
async function seedQuestions() {
console.log("🌱 Importation des questions...");
try {
const existing = await pool.query(
"SELECT COUNT(*) as count FROM questions"
);
if (parseInt(existing.rows[0].count) > 0) {
console.log("⚠️ Des questions existent déjà. Suppression...");
await pool.query("DELETE FROM questions");
}
for (let i = 0; i < NORMAL_QUESTIONS.length; i++) {
const [category, question] = NORMAL_QUESTIONS[i];
await pool.query(
"INSERT INTO questions (category, question, mode, order_index) VALUES ($1, $2, $3, $4)",
[category, question, "normal", i]
);
}
console.log(`${NORMAL_QUESTIONS.length} questions NORMAL importées`);
for (let i = 0; i < CRISIS_QUESTIONS.length; i++) {
const [category, question] = CRISIS_QUESTIONS[i];
await pool.query(
"INSERT INTO questions (category, question, mode, order_index) VALUES ($1, $2, $3, $4)",
[category, question, "crisis", i]
);
}
console.log(`${CRISIS_QUESTIONS.length} questions CRISIS importées`);
console.log("🎉 Importation terminée !");
process.exit(0);
} catch (error) {
console.error("❌ Erreur lors de l'importation:", error);
process.exit(1);
}
}
seedQuestions();
+41
View File
@@ -0,0 +1,41 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": [
"./*"
]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": [
"node_modules"
]
}
+81
View File
@@ -0,0 +1,81 @@
import { DefaultSession } from "next-auth";
declare module "next-auth" {
interface Session {
user: {
id: string;
discordId: string;
isAdmin: boolean;
} & DefaultSession["user"];
}
interface Profile {
id: string;
}
}
declare module "next-auth/jwt" {
interface JWT {
discordId?: string;
isAdmin?: boolean;
}
}
export type TaskStatus = "todo" | "doing" | "done" | "archived";
export type TaskCategory = "urgent" | "deadline" | "admin" | "creative";
export type QuestionMode = "normal" | "crisis";
export type KanbanView = "category" | "status";
export interface ChecklistItem {
id: string;
text: string;
checked: boolean;
}
export interface Task {
id: number;
text: string;
description?: string;
checklist?: ChecklistItem[];
category: TaskCategory;
status: TaskStatus;
added: string;
created_at: string;
}
export interface Question {
id?: number;
category: string;
question: string;
mode: QuestionMode;
order_index?: number;
}
export interface Session {
id: number;
mode: QuestionMode;
answers: SessionAnswer[];
created_at: string;
exported_at?: string;
}
export interface SessionAnswer {
questionIndex: number;
category: string;
question: string;
answer: string;
}
export interface CategoryConfig {
key: TaskCategory;
label: string;
color: string;
hover: string;
border: string;
}
export interface StatusConfig {
key: TaskStatus;
label: string;
color: string;
}