feat: Implémentation de la pagination et mise à jour du devbook
- Ajout de la pagination pour les séries et les livres - Indicateurs de chargement pendant la navigation - Animations de transition entre les pages - Mise à jour du devbook pour refléter les fonctionnalités complétées - Amélioration de l'affichage des états de chargement (skeletons, spinners) - Optimisation des transitions de page
This commit is contained in:
@@ -13,7 +13,7 @@ Créer une application web moderne avec Next.js permettant de lire des fichiers
|
|||||||
- [x] Affichage des séries par bibliothèque
|
- [x] Affichage des séries par bibliothèque
|
||||||
- [x] Couvertures et informations des séries
|
- [x] Couvertures et informations des séries
|
||||||
- [ ] Filtres et recherche
|
- [ ] Filtres et recherche
|
||||||
- [ ] Pagination
|
- [x] Pagination
|
||||||
- [x] Lecteur de fichiers (CBZ, CBR)
|
- [x] Lecteur de fichiers (CBZ, CBR)
|
||||||
- [x] Navigation entre les pages
|
- [x] Navigation entre les pages
|
||||||
- [x] Mode plein écran
|
- [x] Mode plein écran
|
||||||
@@ -113,7 +113,7 @@ Créer une application web moderne avec Next.js permettant de lire des fichiers
|
|||||||
- [x] Page de détails de la série
|
- [x] Page de détails de la série
|
||||||
- [x] Couverture et informations
|
- [x] Couverture et informations
|
||||||
- [x] Liste des tomes
|
- [x] Liste des tomes
|
||||||
- [ ] Progression de lecture
|
- [x] Progression de lecture
|
||||||
- [x] Bouton de lecture contextuel
|
- [x] Bouton de lecture contextuel
|
||||||
- [x] Page de détails du tome
|
- [x] Page de détails du tome
|
||||||
- [x] Couverture et informations
|
- [x] Couverture et informations
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { cookies } from "next/headers";
|
|||||||
export async function GET(request: Request, { params }: { params: { seriesId: string } }) {
|
export async function GET(request: Request, { params }: { params: { seriesId: string } }) {
|
||||||
try {
|
try {
|
||||||
// Récupérer les credentials Komga depuis le cookie
|
// Récupérer les credentials Komga depuis le cookie
|
||||||
const configCookie = cookies().get("komga_credentials");
|
const configCookie = cookies().get("komgaCredentials");
|
||||||
if (!configCookie) {
|
if (!configCookie) {
|
||||||
return NextResponse.json({ error: "Configuration Komga manquante" }, { status: 401 });
|
return NextResponse.json({ error: "Configuration Komga manquante" }, { status: 401 });
|
||||||
}
|
}
|
||||||
@@ -24,6 +24,11 @@ export async function GET(request: Request, { params }: { params: { seriesId: st
|
|||||||
`${config.credentials.username}:${config.credentials.password}`
|
`${config.credentials.username}:${config.credentials.password}`
|
||||||
).toString("base64");
|
).toString("base64");
|
||||||
|
|
||||||
|
// Récupérer les paramètres de pagination depuis l'URL
|
||||||
|
const { searchParams } = new URL(request.url);
|
||||||
|
const page = searchParams.get("page") || "0";
|
||||||
|
const size = searchParams.get("size") || "24";
|
||||||
|
|
||||||
// Appel à l'API Komga pour récupérer les détails de la série
|
// Appel à l'API Komga pour récupérer les détails de la série
|
||||||
const [seriesResponse, booksResponse] = await Promise.all([
|
const [seriesResponse, booksResponse] = await Promise.all([
|
||||||
// Détails de la série
|
// Détails de la série
|
||||||
@@ -32,9 +37,9 @@ export async function GET(request: Request, { params }: { params: { seriesId: st
|
|||||||
Authorization: `Basic ${auth}`,
|
Authorization: `Basic ${auth}`,
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
// Liste des tomes (on récupère tous les tomes avec size=1000)
|
// Liste des tomes avec pagination
|
||||||
fetch(
|
fetch(
|
||||||
`${config.serverUrl}/api/v1/series/${params.seriesId}/books?page=0&size=1000&unpaged=true&sort=metadata.numberSort,asc`,
|
`${config.serverUrl}/api/v1/series/${params.seriesId}/books?page=${page}&size=${size}&sort=metadata.numberSort,asc`,
|
||||||
{
|
{
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Basic ${auth}`,
|
Authorization: `Basic ${auth}`,
|
||||||
@@ -55,10 +60,7 @@ export async function GET(request: Request, { params }: { params: { seriesId: st
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const [series, booksData] = await Promise.all([seriesResponse.json(), booksResponse.json()]);
|
const [series, books] = await Promise.all([seriesResponse.json(), booksResponse.json()]);
|
||||||
|
|
||||||
// On extrait la liste des tomes de la réponse paginée
|
|
||||||
const books = booksData.content;
|
|
||||||
|
|
||||||
return NextResponse.json({ series, books });
|
return NextResponse.json({ series, books });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -1,8 +1,14 @@
|
|||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
import { SeriesGrid } from "@/components/library/SeriesGrid";
|
import { PaginatedSeriesGrid } from "@/components/library/PaginatedSeriesGrid";
|
||||||
import { KomgaSeries } from "@/types/komga";
|
|
||||||
|
|
||||||
async function getLibrarySeries(libraryId: string) {
|
interface PageProps {
|
||||||
|
params: { libraryId: string };
|
||||||
|
searchParams: { page?: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
const PAGE_SIZE = 20;
|
||||||
|
|
||||||
|
async function getLibrarySeries(libraryId: string, page: number = 1) {
|
||||||
const configCookie = cookies().get("komgaCredentials");
|
const configCookie = cookies().get("komgaCredentials");
|
||||||
|
|
||||||
if (!configCookie) {
|
if (!configCookie) {
|
||||||
@@ -16,14 +22,10 @@ async function getLibrarySeries(libraryId: string) {
|
|||||||
throw new Error("Configuration Komga invalide ou incomplète");
|
throw new Error("Configuration Komga invalide ou incomplète");
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log("Config:", {
|
// Paramètres de pagination
|
||||||
serverUrl: config.serverUrl,
|
const pageIndex = page - 1; // L'API Komga utilise un index base 0
|
||||||
hasCredentials: !!config.credentials,
|
|
||||||
username: config.credentials.username,
|
|
||||||
});
|
|
||||||
|
|
||||||
const url = `${config.serverUrl}/api/v1/series?library_id=${libraryId}&page=0&size=100`;
|
const url = `${config.serverUrl}/api/v1/series?library_id=${libraryId}&page=${pageIndex}&size=${PAGE_SIZE}`;
|
||||||
console.log("URL de l'API:", url);
|
|
||||||
|
|
||||||
const credentials = `${config.credentials.username}:${config.credentials.password}`;
|
const credentials = `${config.credentials.username}:${config.credentials.password}`;
|
||||||
const auth = Buffer.from(credentials).toString("base64");
|
const auth = Buffer.from(credentials).toString("base64");
|
||||||
@@ -33,46 +35,44 @@ async function getLibrarySeries(libraryId: string) {
|
|||||||
Authorization: `Basic ${auth}`,
|
Authorization: `Basic ${auth}`,
|
||||||
Accept: "application/json",
|
Accept: "application/json",
|
||||||
},
|
},
|
||||||
cache: "no-store", // Désactiver le cache pour le debug
|
next: { revalidate: 300 }, // Cache de 5 minutes
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const errorText = await response.text();
|
|
||||||
console.error("Réponse de l'API non valide:", {
|
|
||||||
status: response.status,
|
|
||||||
statusText: response.statusText,
|
|
||||||
headers: Object.fromEntries(response.headers.entries()),
|
|
||||||
body: errorText,
|
|
||||||
});
|
|
||||||
throw new Error(`Erreur HTTP: ${response.status} ${response.statusText}`);
|
throw new Error(`Erreur HTTP: ${response.status} ${response.statusText}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
console.log("Données reçues:", {
|
|
||||||
totalElements: data.totalElements,
|
|
||||||
totalPages: data.totalPages,
|
|
||||||
numberOfElements: data.numberOfElements,
|
|
||||||
});
|
|
||||||
|
|
||||||
return { data, serverUrl: config.serverUrl };
|
return { data, serverUrl: config.serverUrl };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Erreur détaillée:", {
|
|
||||||
message: error instanceof Error ? error.message : "Erreur inconnue",
|
|
||||||
stack: error instanceof Error ? error.stack : undefined,
|
|
||||||
error,
|
|
||||||
});
|
|
||||||
throw error instanceof Error ? error : new Error("Erreur lors de la récupération des séries");
|
throw error instanceof Error ? error : new Error("Erreur lors de la récupération des séries");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async function LibraryPage({ params }: { params: { libraryId: string } }) {
|
export default async function LibraryPage({ params, searchParams }: PageProps) {
|
||||||
|
const currentPage = searchParams.page ? parseInt(searchParams.page) : 1;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { data: series, serverUrl } = await getLibrarySeries(params.libraryId);
|
const { data: series, serverUrl } = await getLibrarySeries(params.libraryId, currentPage);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="container py-8 space-y-8">
|
<div className="container py-8 space-y-8">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
<h1 className="text-3xl font-bold">Séries</h1>
|
<h1 className="text-3xl font-bold">Séries</h1>
|
||||||
<SeriesGrid series={series.content || []} serverUrl={serverUrl} />
|
{series.totalElements > 0 && (
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{series.totalElements} série{series.totalElements > 1 ? "s" : ""}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<PaginatedSeriesGrid
|
||||||
|
series={series.content || []}
|
||||||
|
serverUrl={serverUrl}
|
||||||
|
currentPage={currentPage}
|
||||||
|
totalPages={series.totalPages}
|
||||||
|
totalElements={series.totalElements}
|
||||||
|
pageSize={PAGE_SIZE}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -4,25 +4,44 @@ import { useRouter } from "next/navigation";
|
|||||||
import { KomgaSeries, KomgaBook } from "@/types/komga";
|
import { KomgaSeries, KomgaBook } from "@/types/komga";
|
||||||
import { useEffect, useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { BookGrid } from "@/components/series/BookGrid";
|
import { BookGrid } from "@/components/series/BookGrid";
|
||||||
import { ImageOff } from "lucide-react";
|
import { ImageOff, Loader2 } from "lucide-react";
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
|
import { Pagination } from "@/components/ui/Pagination";
|
||||||
|
import { useSearchParams, usePathname } from "next/navigation";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
interface SeriesData {
|
interface SeriesData {
|
||||||
series: KomgaSeries;
|
series: KomgaSeries;
|
||||||
books: KomgaBook[];
|
books: {
|
||||||
|
content: KomgaBook[];
|
||||||
|
totalElements: number;
|
||||||
|
totalPages: number;
|
||||||
|
number: number;
|
||||||
|
size: number;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const PAGE_SIZE = 24; // 6 colonnes x 4 lignes pour un affichage optimal
|
||||||
|
|
||||||
export default function SeriesPage({ params }: { params: { seriesId: string } }) {
|
export default function SeriesPage({ params }: { params: { seriesId: string } }) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
const pathname = usePathname();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const currentPage = searchParams.get("page") ? parseInt(searchParams.get("page")!) : 1;
|
||||||
|
|
||||||
const [data, setData] = useState<SeriesData | null>(null);
|
const [data, setData] = useState<SeriesData | null>(null);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
const [isChangingPage, setIsChangingPage] = useState(false);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [imageError, setImageError] = useState(false);
|
const [imageError, setImageError] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchSeriesData = async () => {
|
const fetchSeriesData = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`/api/komga/series/${params.seriesId}`);
|
setIsChangingPage(true);
|
||||||
|
const response = await fetch(
|
||||||
|
`/api/komga/series/${params.seriesId}?page=${currentPage - 1}&size=${PAGE_SIZE}`
|
||||||
|
);
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
throw new Error(data.error || "Erreur lors de la récupération de la série");
|
throw new Error(data.error || "Erreur lors de la récupération de la série");
|
||||||
@@ -34,16 +53,22 @@ export default function SeriesPage({ params }: { params: { seriesId: string } })
|
|||||||
setError(error instanceof Error ? error.message : "Une erreur est survenue");
|
setError(error instanceof Error ? error.message : "Une erreur est survenue");
|
||||||
} finally {
|
} finally {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
|
setIsChangingPage(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
fetchSeriesData();
|
fetchSeriesData();
|
||||||
}, [params.seriesId]);
|
}, [params.seriesId, currentPage]);
|
||||||
|
|
||||||
const handleBookClick = (book: KomgaBook) => {
|
const handleBookClick = (book: KomgaBook) => {
|
||||||
router.push(`/books/${book.id}`);
|
router.push(`/books/${book.id}`);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handlePageChange = (page: number) => {
|
||||||
|
setIsChangingPage(true);
|
||||||
|
router.push(`/series/${params.seriesId}?page=${page}`);
|
||||||
|
};
|
||||||
|
|
||||||
const getBookThumbnailUrl = (bookId: string) => {
|
const getBookThumbnailUrl = (bookId: string) => {
|
||||||
return `/api/komga/images/books/${bookId}/thumbnail`;
|
return `/api/komga/images/books/${bookId}/thumbnail`;
|
||||||
};
|
};
|
||||||
@@ -88,6 +113,8 @@ export default function SeriesPage({ params }: { params: { seriesId: string } })
|
|||||||
}
|
}
|
||||||
|
|
||||||
const { series, books } = data;
|
const { series, books } = data;
|
||||||
|
const startIndex = (currentPage - 1) * PAGE_SIZE + 1;
|
||||||
|
const endIndex = Math.min(currentPage * PAGE_SIZE, books.totalElements);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="container py-8 space-y-8">
|
<div className="container py-8 space-y-8">
|
||||||
@@ -178,15 +205,61 @@ export default function SeriesPage({ params }: { params: { seriesId: string } })
|
|||||||
|
|
||||||
{/* Grille des tomes */}
|
{/* Grille des tomes */}
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
<h2 className="text-2xl font-semibold">
|
<h2 className="text-2xl font-semibold">
|
||||||
Tomes <span className="text-muted-foreground">({books.length})</span>
|
Tomes <span className="text-muted-foreground">({books.totalElements})</span>
|
||||||
</h2>
|
</h2>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{books.totalElements > 0 ? (
|
||||||
|
<>
|
||||||
|
Affichage des tomes <span className="font-medium">{startIndex}</span> à{" "}
|
||||||
|
<span className="font-medium">{endIndex}</span> sur{" "}
|
||||||
|
<span className="font-medium">{books.totalElements}</span>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
"Aucun tome disponible"
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="relative">
|
||||||
|
{/* Indicateur de chargement */}
|
||||||
|
{isChangingPage && (
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center bg-background/50 backdrop-blur-sm z-10">
|
||||||
|
<div className="flex items-center gap-2 px-4 py-2 rounded-full bg-background border shadow-sm">
|
||||||
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
|
<span className="text-sm">Chargement...</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Grille avec animation de transition */}
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"transition-opacity duration-200",
|
||||||
|
isChangingPage ? "opacity-25" : "opacity-100"
|
||||||
|
)}
|
||||||
|
>
|
||||||
<BookGrid
|
<BookGrid
|
||||||
books={books}
|
books={books.content}
|
||||||
onBookClick={handleBookClick}
|
onBookClick={handleBookClick}
|
||||||
getBookThumbnailUrl={getBookThumbnailUrl}
|
getBookThumbnailUrl={getBookThumbnailUrl}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col items-center gap-4 sm:flex-row sm:justify-between">
|
||||||
|
<p className="text-sm text-muted-foreground order-2 sm:order-1">
|
||||||
|
Page {currentPage} sur {books.totalPages}
|
||||||
|
</p>
|
||||||
|
<Pagination
|
||||||
|
currentPage={currentPage}
|
||||||
|
totalPages={books.totalPages}
|
||||||
|
onPageChange={handlePageChange}
|
||||||
|
className="order-1 sm:order-2"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
102
src/components/library/PaginatedSeriesGrid.tsx
Normal file
102
src/components/library/PaginatedSeriesGrid.tsx
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { SeriesGrid } from "./SeriesGrid";
|
||||||
|
import { Pagination } from "@/components/ui/Pagination";
|
||||||
|
import { useRouter, usePathname, useSearchParams } from "next/navigation";
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { Loader2 } from "lucide-react";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
interface PaginatedSeriesGridProps {
|
||||||
|
series: any[];
|
||||||
|
serverUrl: string;
|
||||||
|
currentPage: number;
|
||||||
|
totalPages: number;
|
||||||
|
totalElements: number;
|
||||||
|
pageSize: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function PaginatedSeriesGrid({
|
||||||
|
series,
|
||||||
|
serverUrl,
|
||||||
|
currentPage,
|
||||||
|
totalPages,
|
||||||
|
totalElements,
|
||||||
|
pageSize,
|
||||||
|
}: PaginatedSeriesGridProps) {
|
||||||
|
const router = useRouter();
|
||||||
|
const pathname = usePathname();
|
||||||
|
const searchParams = useSearchParams();
|
||||||
|
const [isChangingPage, setIsChangingPage] = useState(false);
|
||||||
|
|
||||||
|
// Réinitialiser l'état de chargement quand les séries changent
|
||||||
|
useEffect(() => {
|
||||||
|
setIsChangingPage(false);
|
||||||
|
}, [series]);
|
||||||
|
|
||||||
|
const handlePageChange = (page: number) => {
|
||||||
|
setIsChangingPage(true);
|
||||||
|
// Créer un nouvel objet URLSearchParams pour manipuler les paramètres
|
||||||
|
const params = new URLSearchParams(searchParams);
|
||||||
|
params.set("page", page.toString());
|
||||||
|
|
||||||
|
// Rediriger vers la nouvelle URL avec les paramètres mis à jour
|
||||||
|
router.push(`${pathname}?${params.toString()}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Calcul des indices de début et de fin pour l'affichage
|
||||||
|
const startIndex = (currentPage - 1) * pageSize + 1;
|
||||||
|
const endIndex = Math.min(currentPage * pageSize, totalElements);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-8">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
{totalElements > 0 ? (
|
||||||
|
<>
|
||||||
|
Affichage des séries <span className="font-medium">{startIndex}</span> à{" "}
|
||||||
|
<span className="font-medium">{endIndex}</span> sur{" "}
|
||||||
|
<span className="font-medium">{totalElements}</span>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
"Aucune série trouvée"
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="relative">
|
||||||
|
{/* Indicateur de chargement */}
|
||||||
|
{isChangingPage && (
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center bg-background/50 backdrop-blur-sm z-10">
|
||||||
|
<div className="flex items-center gap-2 px-4 py-2 rounded-full bg-background border shadow-sm">
|
||||||
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
|
<span className="text-sm">Chargement...</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Grille avec animation de transition */}
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"transition-opacity duration-200",
|
||||||
|
isChangingPage ? "opacity-25" : "opacity-100"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<SeriesGrid series={series} serverUrl={serverUrl} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col items-center gap-4 sm:flex-row sm:justify-between">
|
||||||
|
<p className="text-sm text-muted-foreground order-2 sm:order-1">
|
||||||
|
Page {currentPage} sur {totalPages}
|
||||||
|
</p>
|
||||||
|
<Pagination
|
||||||
|
currentPage={currentPage}
|
||||||
|
totalPages={totalPages}
|
||||||
|
onPageChange={handlePageChange}
|
||||||
|
className="order-1 sm:order-2"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
114
src/components/ui/Pagination.tsx
Normal file
114
src/components/ui/Pagination.tsx
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { ChevronLeft, ChevronRight, MoreHorizontal } from "lucide-react";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
interface PaginationProps {
|
||||||
|
currentPage: number;
|
||||||
|
totalPages: number;
|
||||||
|
onPageChange: (page: number) => void;
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Pagination({ currentPage, totalPages, onPageChange, className }: PaginationProps) {
|
||||||
|
// Ne pas afficher la pagination s'il n'y a qu'une seule page
|
||||||
|
if (totalPages <= 1) return null;
|
||||||
|
|
||||||
|
// Fonction pour générer la liste des pages à afficher
|
||||||
|
const getPageNumbers = () => {
|
||||||
|
const pages: (number | "...")[] = [];
|
||||||
|
|
||||||
|
if (totalPages <= 7) {
|
||||||
|
// Si moins de 7 pages, afficher toutes les pages
|
||||||
|
for (let i = 1; i <= totalPages; i++) {
|
||||||
|
pages.push(i);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Toujours afficher la première page
|
||||||
|
pages.push(1);
|
||||||
|
|
||||||
|
if (currentPage > 3) {
|
||||||
|
pages.push("...");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pages autour de la page courante
|
||||||
|
for (
|
||||||
|
let i = Math.max(2, currentPage - 1);
|
||||||
|
i <= Math.min(totalPages - 1, currentPage + 1);
|
||||||
|
i++
|
||||||
|
) {
|
||||||
|
pages.push(i);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentPage < totalPages - 2) {
|
||||||
|
pages.push("...");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Toujours afficher la dernière page
|
||||||
|
pages.push(totalPages);
|
||||||
|
}
|
||||||
|
|
||||||
|
return pages;
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<nav
|
||||||
|
role="navigation"
|
||||||
|
aria-label="Pagination"
|
||||||
|
className={cn("flex justify-center items-center gap-1", className)}
|
||||||
|
>
|
||||||
|
{/* Bouton précédent */}
|
||||||
|
<button
|
||||||
|
onClick={() => onPageChange(currentPage - 1)}
|
||||||
|
disabled={currentPage === 1}
|
||||||
|
className="inline-flex items-center justify-center rounded-md text-sm font-medium h-10 px-4 py-2 gap-1 hover:bg-accent hover:text-accent-foreground disabled:pointer-events-none disabled:opacity-50"
|
||||||
|
aria-label="Page précédente"
|
||||||
|
>
|
||||||
|
<ChevronLeft className="h-4 w-4" />
|
||||||
|
<span className="sr-only md:not-sr-only">Précédent</span>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/* Liste des pages */}
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
{getPageNumbers().map((page, index) => {
|
||||||
|
if (page === "...") {
|
||||||
|
return (
|
||||||
|
<div key={`ellipsis-${index}`} className="flex items-center justify-center h-10 w-10">
|
||||||
|
<MoreHorizontal className="h-4 w-4" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={page}
|
||||||
|
onClick={() => onPageChange(page)}
|
||||||
|
disabled={page === currentPage}
|
||||||
|
className={cn(
|
||||||
|
"inline-flex items-center justify-center rounded-md text-sm font-medium h-10 w-10",
|
||||||
|
page === currentPage
|
||||||
|
? "bg-primary text-primary-foreground"
|
||||||
|
: "hover:bg-accent hover:text-accent-foreground"
|
||||||
|
)}
|
||||||
|
aria-label={`Page ${page}`}
|
||||||
|
aria-current={page === currentPage ? "page" : undefined}
|
||||||
|
>
|
||||||
|
{page}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Bouton suivant */}
|
||||||
|
<button
|
||||||
|
onClick={() => onPageChange(currentPage + 1)}
|
||||||
|
disabled={currentPage === totalPages}
|
||||||
|
className="inline-flex items-center justify-center rounded-md text-sm font-medium h-10 px-4 py-2 gap-1 hover:bg-accent hover:text-accent-foreground disabled:pointer-events-none disabled:opacity-50"
|
||||||
|
aria-label="Page suivante"
|
||||||
|
>
|
||||||
|
<span className="sr-only md:not-sr-only">Suivant</span>
|
||||||
|
<ChevronRight className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user