feat: complete tag management and UI integration

- Marked multiple tasks as completed in TODO.md related to tag management features.
- Replaced manual tag input with `TagInput` component in `CreateTaskForm`, `EditTaskForm`, and `QuickAddTask` for better UX.
- Updated `TaskCard` to display tags using `TagDisplay` with color support.
- Enhanced `TasksService` to manage task-tag relationships with CRUD operations.
- Integrated tag management into the global context for better accessibility across components.
This commit is contained in:
Julien Froidefond
2025-09-14 16:44:22 +02:00
parent edbd82e8ac
commit c5a7d16425
27 changed files with 2055 additions and 224 deletions

View File

@@ -0,0 +1,144 @@
import { NextRequest, NextResponse } from 'next/server';
import { tagsService } from '@/services/tags';
/**
* GET /api/tags/[id] - Récupère un tag par son ID
*/
export async function GET(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const tag = await tagsService.getTagById(params.id);
if (!tag) {
return NextResponse.json(
{ error: 'Tag non trouvé' },
{ status: 404 }
);
}
return NextResponse.json({
data: tag,
message: 'Tag récupéré avec succès'
});
} catch (error) {
console.error('Erreur lors de la récupération du tag:', error);
return NextResponse.json(
{
error: 'Erreur lors de la récupération du tag',
message: error instanceof Error ? error.message : 'Erreur inconnue'
},
{ status: 500 }
);
}
}
/**
* PATCH /api/tags/[id] - Met à jour un tag
*/
export async function PATCH(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const body = await request.json();
const { name, color } = body;
// Validation
if (name !== undefined && (typeof name !== 'string' || !name.trim())) {
return NextResponse.json(
{ error: 'Le nom du tag doit être une chaîne non vide' },
{ status: 400 }
);
}
if (color !== undefined && (typeof color !== 'string' || !/^#[0-9A-F]{6}$/i.test(color))) {
return NextResponse.json(
{ error: 'La couleur doit être au format hexadécimal (#RRGGBB)' },
{ status: 400 }
);
}
const tag = await tagsService.updateTag(params.id, { name, color });
if (!tag) {
return NextResponse.json(
{ error: 'Tag non trouvé' },
{ status: 404 }
);
}
return NextResponse.json({
data: tag,
message: 'Tag mis à jour avec succès'
});
} catch (error) {
console.error('Erreur lors de la mise à jour du tag:', error);
if (error instanceof Error && error.message.includes('non trouvé')) {
return NextResponse.json(
{ error: error.message },
{ status: 404 }
);
}
if (error instanceof Error && error.message.includes('existe déjà')) {
return NextResponse.json(
{ error: error.message },
{ status: 409 }
);
}
return NextResponse.json(
{
error: 'Erreur lors de la mise à jour du tag',
message: error instanceof Error ? error.message : 'Erreur inconnue'
},
{ status: 500 }
);
}
}
/**
* DELETE /api/tags/[id] - Supprime un tag
*/
export async function DELETE(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
await tagsService.deleteTag(params.id);
return NextResponse.json({
message: 'Tag supprimé avec succès'
});
} catch (error) {
console.error('Erreur lors de la suppression du tag:', error);
if (error instanceof Error && error.message.includes('non trouvé')) {
return NextResponse.json(
{ error: error.message },
{ status: 404 }
);
}
if (error instanceof Error && error.message.includes('utilisé par')) {
return NextResponse.json(
{ error: error.message },
{ status: 409 }
);
}
return NextResponse.json(
{
error: 'Erreur lors de la suppression du tag',
message: error instanceof Error ? error.message : 'Erreur inconnue'
},
{ status: 500 }
);
}
}

100
src/app/api/tags/route.ts Normal file
View File

@@ -0,0 +1,100 @@
import { NextRequest, NextResponse } from 'next/server';
import { tagsService } from '@/services/tags';
/**
* GET /api/tags - Récupère tous les tags ou recherche par query
*/
export async function GET(request: NextRequest) {
try {
const { searchParams } = new URL(request.url);
const query = searchParams.get('q');
const popular = searchParams.get('popular');
const limit = parseInt(searchParams.get('limit') || '10');
let tags;
if (popular === 'true') {
// Récupérer les tags les plus utilisés
tags = await tagsService.getPopularTags(limit);
} else if (query) {
// Recherche par nom (pour autocomplete)
tags = await tagsService.searchTags(query, limit);
} else {
// Récupérer tous les tags
tags = await tagsService.getTags();
}
return NextResponse.json({
data: tags,
message: 'Tags récupérés avec succès'
});
} catch (error) {
console.error('Erreur lors de la récupération des tags:', error);
return NextResponse.json(
{
error: 'Erreur lors de la récupération des tags',
message: error instanceof Error ? error.message : 'Erreur inconnue'
},
{ status: 500 }
);
}
}
/**
* POST /api/tags - Crée un nouveau tag
*/
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { name, color } = body;
// Validation
if (!name || typeof name !== 'string') {
return NextResponse.json(
{ error: 'Le nom du tag est requis' },
{ status: 400 }
);
}
if (!color || typeof color !== 'string') {
return NextResponse.json(
{ error: 'La couleur du tag est requise' },
{ status: 400 }
);
}
// Validation du format couleur (hex)
if (!/^#[0-9A-F]{6}$/i.test(color)) {
return NextResponse.json(
{ error: 'La couleur doit être au format hexadécimal (#RRGGBB)' },
{ status: 400 }
);
}
const tag = await tagsService.createTag({ name, color });
return NextResponse.json({
data: tag,
message: 'Tag créé avec succès'
}, { status: 201 });
} catch (error) {
console.error('Erreur lors de la création du tag:', error);
if (error instanceof Error && error.message.includes('existe déjà')) {
return NextResponse.json(
{ error: error.message },
{ status: 409 }
);
}
return NextResponse.json(
{
error: 'Erreur lors de la création du tag',
message: error instanceof Error ? error.message : 'Erreur inconnue'
},
{ status: 500 }
);
}
}

View File

@@ -0,0 +1,240 @@
'use client';
import { useState } from 'react';
import { Tag } from '@/lib/types';
import { useTags } from '@/hooks/useTags';
import { CreateTagData, UpdateTagData } from '@/clients/tags-client';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { TagList } from '@/components/ui/TagList';
import { TagForm } from '@/components/forms/TagForm';
import Link from 'next/link';
interface TagsPageClientProps {
initialTags: Tag[];
}
export function TagsPageClient({ initialTags }: TagsPageClientProps) {
const {
tags,
popularTags,
loading,
error,
createTag,
updateTag,
deleteTag,
getPopularTags,
searchTags
} = useTags();
const [searchQuery, setSearchQuery] = useState('');
const [searchResults, setSearchResults] = useState<Tag[]>([]);
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
const [editingTag, setEditingTag] = useState<Tag | null>(null);
const [showPopular, setShowPopular] = useState(false);
// Utiliser les tags initiaux si pas encore chargés
const displayTags = tags.length > 0 ? tags : initialTags;
const filteredTags = searchQuery ? searchResults : displayTags;
const handleSearch = async (query: string) => {
setSearchQuery(query);
if (query.trim()) {
const results = await searchTags(query);
setSearchResults(results);
} else {
setSearchResults([]);
}
};
const handleCreateTag = async (data: CreateTagData) => {
await createTag(data);
setIsCreateModalOpen(false);
};
const handleEditTag = (tag: Tag) => {
setEditingTag(tag);
};
const handleUpdateTag = async (data: { name: string; color: string }) => {
if (editingTag) {
await updateTag({
tagId: editingTag.id,
...data
});
setEditingTag(null);
}
};
const handleDeleteTag = async (tag: Tag) => {
if (confirm(`Êtes-vous sûr de vouloir supprimer le tag "${tag.name}" ?`)) {
try {
await deleteTag(tag.id);
} catch (error) {
// L'erreur est déjà gérée dans le hook
console.error('Erreur lors de la suppression:', error);
}
}
};
const handleShowPopular = async () => {
if (!showPopular) {
await getPopularTags(10);
}
setShowPopular(!showPopular);
};
return (
<div className="min-h-screen bg-slate-950">
{/* Header */}
<div className="bg-slate-900/80 backdrop-blur-sm border-b border-slate-700/50">
<div className="container mx-auto px-6 py-6">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div className="flex items-center gap-4">
{/* Bouton retour */}
<Link
href="/"
className="flex items-center justify-center w-10 h-10 rounded-lg bg-slate-800/50 border border-slate-700 hover:border-cyan-400/50 hover:bg-slate-700/50 transition-all duration-200 group"
title="Retour au Kanban"
>
<svg
className="w-5 h-5 text-slate-400 group-hover:text-cyan-400 transition-colors"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
</Link>
<div className="w-3 h-3 bg-purple-400 rounded-full animate-pulse shadow-purple-400/50 shadow-lg"></div>
<div>
<h1 className="text-2xl font-mono font-bold text-slate-100 tracking-wider">
Gestion des Tags
</h1>
<p className="text-slate-400 mt-1 font-mono text-sm">
Organisez et gérez vos étiquettes
</p>
</div>
</div>
<div className="flex items-center gap-3">
<Button
variant="secondary"
onClick={handleShowPopular}
disabled={loading}
>
{showPopular ? 'Tous les tags' : 'Tags populaires'}
</Button>
<Button
variant="primary"
onClick={() => setIsCreateModalOpen(true)}
disabled={loading}
>
+ Nouveau tag
</Button>
</div>
</div>
</div>
</div>
{/* Contenu principal */}
<div className="container mx-auto px-6 py-8">
<div className="max-w-4xl mx-auto space-y-8">
{/* Barre de recherche */}
<div className="space-y-2">
<label className="block text-sm font-mono font-medium text-slate-300 uppercase tracking-wider">
Rechercher des tags
</label>
<Input
type="text"
value={searchQuery}
onChange={(e) => handleSearch(e.target.value)}
placeholder="Tapez pour rechercher..."
className="max-w-md"
/>
</div>
{/* Statistiques */}
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<div className="bg-slate-800/50 rounded-lg p-4 border border-slate-700">
<div className="text-2xl font-mono font-bold text-slate-100">
{displayTags.length}
</div>
<div className="text-sm text-slate-400 font-mono uppercase tracking-wide">
Tags total
</div>
</div>
<div className="bg-slate-800/50 rounded-lg p-4 border border-slate-700">
<div className="text-2xl font-mono font-bold text-slate-100">
{popularTags.length > 0 ? popularTags[0]?.usage || 0 : 0}
</div>
<div className="text-sm text-slate-400 font-mono uppercase tracking-wide">
Plus utilisé
</div>
</div>
<div className="bg-slate-800/50 rounded-lg p-4 border border-slate-700">
<div className="text-2xl font-mono font-bold text-slate-100">
{searchQuery ? searchResults.length : displayTags.length}
</div>
<div className="text-sm text-slate-400 font-mono uppercase tracking-wide">
{searchQuery ? 'Résultats' : 'Affichés'}
</div>
</div>
</div>
{/* Messages d'état */}
{error && (
<div className="bg-red-900/20 border border-red-500/30 rounded-lg p-4">
<div className="text-red-400 text-sm">
Erreur : {error}
</div>
</div>
)}
{loading && (
<div className="text-center py-8">
<div className="text-slate-400">Chargement...</div>
</div>
)}
{/* Liste des tags */}
<div className="space-y-4">
<h2 className="text-lg font-mono font-bold text-slate-200 uppercase tracking-wider">
{showPopular
? 'Tags populaires'
: searchQuery
? `Résultats pour "${searchQuery}"`
: 'Tous les tags'
}
</h2>
<TagList
tags={showPopular ? popularTags : filteredTags}
onTagEdit={handleEditTag}
onTagDelete={handleDeleteTag}
showUsage={true}
/>
</div>
</div>
</div>
{/* Modals */}
<TagForm
isOpen={isCreateModalOpen}
onClose={() => setIsCreateModalOpen(false)}
onSubmit={handleCreateTag}
loading={loading}
/>
<TagForm
isOpen={!!editingTag}
onClose={() => setEditingTag(null)}
onSubmit={handleUpdateTag}
tag={editingTag}
loading={loading}
/>
</div>
);
}

11
src/app/tags/page.tsx Normal file
View File

@@ -0,0 +1,11 @@
import { tagsService } from '@/services/tags';
import { TagsPageClient } from './TagsPageClient';
export default async function TagsPage() {
// SSR - Récupération des tags côté serveur
const initialTags = await tagsService.getTags();
return (
<TagsPageClient initialTags={initialTags} />
);
}

View File

@@ -2,7 +2,8 @@
import { createContext, useContext, ReactNode } from 'react';
import { useTasks } from '@/hooks/useTasks';
import { Task } from '@/lib/types';
import { useTags } from '@/hooks/useTags';
import { Task, Tag } from '@/lib/types';
import { CreateTaskData, UpdateTaskData, TaskFilters } from '@/clients/tasks-client';
interface TasksContextType {
@@ -23,6 +24,10 @@ interface TasksContextType {
deleteTask: (taskId: string) => Promise<void>;
refreshTasks: () => Promise<void>;
setFilters: (filters: TaskFilters) => void;
// Tags
tags: Tag[];
tagsLoading: boolean;
tagsError: string | null;
}
const TasksContext = createContext<TasksContextType | null>(null);
@@ -39,8 +44,17 @@ export function TasksProvider({ children, initialTasks, initialStats }: TasksPro
{ tasks: initialTasks, stats: initialStats }
);
const { tags, loading: tagsLoading, error: tagsError } = useTags();
const contextValue: TasksContextType = {
...tasksState,
tags,
tagsLoading,
tagsError
};
return (
<TasksContext.Provider value={tasksState}>
<TasksContext.Provider value={contextValue}>
{children}
</TasksContext.Provider>
);