feat: ajoute la pagination et le filtrage des tomes dans la page série

This commit is contained in:
Julien Froidefond
2025-02-11 21:43:09 +01:00
parent f8725857ad
commit e4a663b6d4
6 changed files with 300 additions and 261 deletions

View File

@@ -21,26 +21,32 @@ export async function GET(request: Request, { params }: { params: { libraryId: s
return NextResponse.json({ error: "Credentials Komga manquants" }, { status: 401 });
}
// Récupérer les paramètres de pagination depuis l'URL
// Récupérer les paramètres de pagination et de filtre depuis l'URL
const { searchParams } = new URL(request.url);
const page = searchParams.get("page") || "0";
const size = searchParams.get("size") || "20";
const unreadOnly = searchParams.get("unread") === "true";
// Clé de cache unique pour cette page de séries
const cacheKey = `library-${params.libraryId}-series-${page}-${size}`;
const cacheKey = `library-${params.libraryId}-series-${page}-${size}-${unreadOnly}`;
// Fonction pour récupérer les séries
const fetchSeries = async () => {
const response = await fetch(
`${config.serverUrl}/api/v1/series?library_id=${params.libraryId}&page=${page}&size=${size}`,
{
headers: {
Authorization: `Basic ${Buffer.from(
`${config.credentials.username}:${config.credentials.password}`
).toString("base64")}`,
},
}
);
// Construire l'URL avec les paramètres
let url = `${config.serverUrl}/api/v1/series?library_id=${params.libraryId}&page=${page}&size=${size}`;
// Ajouter le filtre pour les séries non lues et en cours si nécessaire
if (unreadOnly) {
url += "&read_status=UNREAD&read_status=IN_PROGRESS";
}
const response = await fetch(url, {
headers: {
Authorization: `Basic ${Buffer.from(
`${config.credentials.username}:${config.credentials.password}`
).toString("base64")}`,
},
});
if (!response.ok) {
const errorData = await response.json().catch(() => null);

View File

@@ -0,0 +1,78 @@
import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { serverCacheService } from "@/lib/services/server-cache.service";
export async function GET(request: Request, { params }: { params: { seriesId: string } }) {
try {
// Récupérer les credentials Komga depuis le cookie
const configCookie = cookies().get("komgaCredentials");
if (!configCookie) {
return NextResponse.json({ error: "Configuration Komga manquante" }, { status: 401 });
}
let config;
try {
config = JSON.parse(atob(configCookie.value));
} catch (error) {
return NextResponse.json({ error: "Configuration Komga invalide" }, { status: 401 });
}
if (!config.credentials?.username || !config.credentials?.password) {
return NextResponse.json({ error: "Credentials Komga manquants" }, { status: 401 });
}
// Récupérer les paramètres de pagination et de filtre depuis l'URL
const { searchParams } = new URL(request.url);
const page = searchParams.get("page") || "0";
const size = searchParams.get("size") || "24";
const unreadOnly = searchParams.get("unread") === "true";
// Clé de cache unique pour cette page de tomes
const cacheKey = `series-${params.seriesId}-books-${page}-${size}-${unreadOnly}`;
// Fonction pour récupérer les tomes
const fetchBooks = async () => {
// Construire l'URL avec les paramètres
let url = `${config.serverUrl}/api/v1/series/${params.seriesId}/books?page=${page}&size=${size}&sort=metadata.numberSort,asc`;
// Ajouter le filtre pour les tomes non lus et en cours si nécessaire
if (unreadOnly) {
url += "&read_status=UNREAD&read_status=IN_PROGRESS";
}
const response = await fetch(url, {
headers: {
Authorization: `Basic ${Buffer.from(
`${config.credentials.username}:${config.credentials.password}`
).toString("base64")}`,
},
});
if (!response.ok) {
const errorData = await response.json().catch(() => null);
throw new Error(
JSON.stringify({
error: "Erreur lors de la récupération des tomes",
details: errorData,
})
);
}
return response.json();
};
// Récupérer les données du cache ou faire l'appel API
const data = await serverCacheService.getOrSet(cacheKey, fetchBooks, 5 * 60); // Cache de 5 minutes
return NextResponse.json(data);
} catch (error) {
console.error("Erreur lors de la récupération des tomes:", error);
return NextResponse.json(
{
error: "Erreur serveur",
details: error instanceof Error ? error.message : "Erreur inconnue",
},
{ status: 500 }
);
}
}

View File

@@ -3,12 +3,12 @@ import { PaginatedSeriesGrid } from "@/components/library/PaginatedSeriesGrid";
interface PageProps {
params: { libraryId: string };
searchParams: { page?: string };
searchParams: { page?: string; unread?: string };
}
const PAGE_SIZE = 20;
async function getLibrarySeries(libraryId: string, page: number = 1) {
async function getLibrarySeries(libraryId: string, page: number = 1, unreadOnly: boolean = false) {
const configCookie = cookies().get("komgaCredentials");
if (!configCookie) {
@@ -25,7 +25,13 @@ async function getLibrarySeries(libraryId: string, page: number = 1) {
// Paramètres de pagination
const pageIndex = page - 1; // L'API Komga utilise un index base 0
const url = `${config.serverUrl}/api/v1/series?library_id=${libraryId}&page=${pageIndex}&size=${PAGE_SIZE}`;
// Construire l'URL avec les paramètres
let url = `${config.serverUrl}/api/v1/series?library_id=${libraryId}&page=${pageIndex}&size=${PAGE_SIZE}`;
// Ajouter le filtre pour les séries non lues et en cours si nécessaire
if (unreadOnly) {
url += "&read_status=UNREAD&read_status=IN_PROGRESS";
}
const credentials = `${config.credentials.username}:${config.credentials.password}`;
const auth = Buffer.from(credentials).toString("base64");
@@ -51,9 +57,14 @@ async function getLibrarySeries(libraryId: string, page: number = 1) {
export default async function LibraryPage({ params, searchParams }: PageProps) {
const currentPage = searchParams.page ? parseInt(searchParams.page) : 1;
const unreadOnly = searchParams.unread === "true";
try {
const { data: series, serverUrl } = await getLibrarySeries(params.libraryId, currentPage);
const { data: series, serverUrl } = await getLibrarySeries(
params.libraryId,
currentPage,
unreadOnly
);
return (
<div className="container py-8 space-y-8">

View File

@@ -1,265 +1,92 @@
"use client";
import { useRouter } from "next/navigation";
import { cookies } from "next/headers";
import { PaginatedBookGrid } from "@/components/series/PaginatedBookGrid";
import { SeriesHeader } from "@/components/series/SeriesHeader";
import { KomgaSeries, KomgaBook } from "@/types/komga";
import { useEffect, useState } from "react";
import { BookGrid } from "@/components/series/BookGrid";
import { ImageOff, Loader2 } from "lucide-react";
import Image from "next/image";
import { Pagination } from "@/components/ui/Pagination";
import { useSearchParams, usePathname } from "next/navigation";
import { cn } from "@/lib/utils";
interface SeriesData {
series: KomgaSeries;
books: {
content: KomgaBook[];
totalElements: number;
totalPages: number;
number: number;
size: number;
};
interface PageProps {
params: { seriesId: string };
searchParams: { page?: string; unread?: string };
}
const PAGE_SIZE = 24; // 6 colonnes x 4 lignes pour un affichage optimal
const PAGE_SIZE = 24;
export default function SeriesPage({ params }: { params: { seriesId: string } }) {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
const currentPage = searchParams.get("page") ? parseInt(searchParams.get("page")!) : 1;
export default async function SeriesPage({ params, searchParams }: PageProps) {
const currentPage = searchParams.page ? parseInt(searchParams.page) : 1;
const unreadOnly = searchParams.unread === "true";
const [data, setData] = useState<SeriesData | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [isChangingPage, setIsChangingPage] = useState(false);
const [error, setError] = useState<string | null>(null);
const [imageError, setImageError] = useState(false);
const configCookie = cookies().get("komgaCredentials");
if (!configCookie) {
throw new Error("Configuration Komga manquante");
}
useEffect(() => {
const fetchSeriesData = async () => {
try {
setIsChangingPage(true);
const response = await fetch(
`/api/komga/series/${params.seriesId}?page=${currentPage - 1}&size=${PAGE_SIZE}`
);
if (!response.ok) {
const data = await response.json();
throw new Error(data.error || "Erreur lors de la récupération de la série");
try {
const config = JSON.parse(atob(configCookie.value));
if (!config.serverUrl || !config.credentials?.username || !config.credentials?.password) {
throw new Error("Configuration Komga invalide ou incomplète");
}
const credentials = `${config.credentials.username}:${config.credentials.password}`;
const auth = Buffer.from(credentials).toString("base64");
// Paramètres de pagination
const pageIndex = currentPage - 1; // L'API Komga utilise un index base 0
// Appels API parallèles pour les détails de la série et les tomes
const [seriesResponse, booksResponse] = await Promise.all([
// Détails de la série
fetch(`${config.serverUrl}/api/v1/series/${params.seriesId}`, {
headers: {
Authorization: `Basic ${auth}`,
Accept: "application/json",
},
next: { revalidate: 300 },
}),
// Liste des tomes avec pagination et filtre
fetch(
`${config.serverUrl}/api/v1/series/${
params.seriesId
}/books?page=${pageIndex}&size=${PAGE_SIZE}&sort=metadata.numberSort,asc${
unreadOnly ? "&read_status=UNREAD&read_status=IN_PROGRESS" : ""
}`,
{
headers: {
Authorization: `Basic ${auth}`,
Accept: "application/json",
},
next: { revalidate: 300 },
}
const data = await response.json();
setData(data);
} catch (error) {
console.error("Erreur:", error);
setError(error instanceof Error ? error.message : "Une erreur est survenue");
} finally {
setIsLoading(false);
setIsChangingPage(false);
}
};
),
]);
fetchSeriesData();
}, [params.seriesId, currentPage]);
if (!seriesResponse.ok || !booksResponse.ok) {
throw new Error("Erreur lors de la récupération des données");
}
const handleBookClick = (book: KomgaBook) => {
router.push(`/books/${book.id}`);
};
const [series, books] = await Promise.all([seriesResponse.json(), booksResponse.json()]);
const handlePageChange = (page: number) => {
setIsChangingPage(true);
router.push(`/series/${params.seriesId}?page=${page}`);
};
const getBookThumbnailUrl = (bookId: string) => {
return `/api/komga/images/books/${bookId}/thumbnail`;
};
if (isLoading) {
return (
<div className="container py-8 space-y-8 animate-pulse">
<div className="flex flex-col md:flex-row gap-8">
<div className="w-48 h-72 bg-muted rounded-lg" />
<div className="flex-1 space-y-4">
<div className="h-8 bg-muted rounded w-1/3" />
<div className="h-4 bg-muted rounded w-1/4" />
<div className="h-24 bg-muted rounded" />
</div>
</div>
<div className="space-y-4">
<div className="h-6 bg-muted rounded w-32" />
<div className="grid gap-4 sm:grid-cols-3 lg:grid-cols-6">
{[...Array(6)].map((_, i) => (
<div key={i} className="rounded-lg border bg-card overflow-hidden">
<div className="aspect-[2/3] bg-muted" />
<div className="p-2 space-y-2">
<div className="h-4 bg-muted rounded" />
<div className="h-3 bg-muted rounded w-1/2" />
</div>
</div>
))}
</div>
</div>
<div className="container py-8 space-y-8">
<SeriesHeader series={series} serverUrl={config.serverUrl} />
<PaginatedBookGrid
books={books.content || []}
serverUrl={config.serverUrl}
currentPage={currentPage}
totalPages={books.totalPages}
totalElements={books.totalElements}
pageSize={PAGE_SIZE}
/>
</div>
);
}
if (error || !data) {
} catch (error) {
return (
<div className="container py-8">
<div className="container py-8 space-y-8">
<h1 className="text-3xl font-bold">Série</h1>
<div className="rounded-md bg-destructive/15 p-4">
<p className="text-sm text-destructive">{error || "Données non disponibles"}</p>
<p className="text-sm text-destructive">
{error instanceof Error ? error.message : "Erreur lors de la récupération de la série"}
</p>
</div>
</div>
);
}
const { series, books } = data;
const startIndex = (currentPage - 1) * PAGE_SIZE + 1;
const endIndex = Math.min(currentPage * PAGE_SIZE, books.totalElements);
return (
<div className="container py-8 space-y-8">
{/* En-tête de la série */}
<div className="flex flex-col md:flex-row gap-8">
{/* Couverture */}
<div className="w-48 shrink-0">
<div className="relative aspect-[2/3] rounded-lg overflow-hidden bg-muted">
{!imageError ? (
<Image
src={`/api/komga/images/series/${series.id}/thumbnail`}
alt={`Couverture de ${series.metadata.title}`}
fill
className="object-cover"
onError={() => setImageError(true)}
/>
) : (
<div className="w-full h-full flex items-center justify-center">
<ImageOff className="w-12 h-12" />
</div>
)}
</div>
</div>
{/* Informations */}
<div className="flex-1 space-y-4">
<div>
<h1 className="text-3xl font-bold">{series.metadata.title}</h1>
{series.metadata.status && (
<span
className={`mt-2 inline-block px-2 py-1 rounded-full text-xs ${
series.metadata.status === "ENDED"
? "bg-green-500/10 text-green-500"
: series.metadata.status === "ONGOING"
? "bg-blue-500/10 text-blue-500"
: series.metadata.status === "ABANDONED"
? "bg-destructive/10 text-destructive"
: "bg-yellow-500/10 text-yellow-500"
}`}
>
{series.metadata.status === "ENDED"
? "Terminé"
: series.metadata.status === "ONGOING"
? "En cours"
: series.metadata.status === "ABANDONED"
? "Abandonné"
: "En pause"}
</span>
)}
</div>
{series.metadata.summary && (
<p className="text-muted-foreground">{series.metadata.summary}</p>
)}
<div className="space-y-1 text-sm text-muted-foreground">
{series.metadata.publisher && (
<div>
<span className="font-medium">Éditeur :</span> {series.metadata.publisher}
</div>
)}
{series.metadata.genres?.length > 0 && (
<div>
<span className="font-medium">Genres :</span> {series.metadata.genres.join(", ")}
</div>
)}
{series.metadata.tags?.length > 0 && (
<div>
<span className="font-medium">Tags :</span> {series.metadata.tags.join(", ")}
</div>
)}
{series.metadata.language && (
<div>
<span className="font-medium">Langue :</span>{" "}
{new Intl.DisplayNames([navigator.language], { type: "language" }).of(
series.metadata.language
)}
</div>
)}
{series.metadata.ageRating && (
<div>
<span className="font-medium">Âge recommandé :</span> {series.metadata.ageRating}+
</div>
)}
</div>
</div>
</div>
{/* Grille des tomes */}
<div className="space-y-4">
<div className="flex items-center justify-between">
<h2 className="text-2xl font-semibold">
Tomes <span className="text-muted-foreground">({books.totalElements})</span>
</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
books={books.content}
onBookClick={handleBookClick}
getBookThumbnailUrl={getBookThumbnailUrl}
/>
</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>
);
}

View File

@@ -4,7 +4,7 @@ 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 { Loader2, Filter } from "lucide-react";
import { cn } from "@/lib/utils";
interface PaginatedSeriesGridProps {
@@ -28,6 +28,7 @@ export function PaginatedSeriesGrid({
const pathname = usePathname();
const searchParams = useSearchParams();
const [isChangingPage, setIsChangingPage] = useState(false);
const [showOnlyUnread, setShowOnlyUnread] = useState(searchParams.get("unread") === "true");
// Réinitialiser l'état de chargement quand les séries changent
useEffect(() => {
@@ -39,11 +40,29 @@ export function PaginatedSeriesGrid({
// Créer un nouvel objet URLSearchParams pour manipuler les paramètres
const params = new URLSearchParams(searchParams);
params.set("page", page.toString());
if (showOnlyUnread) {
params.set("unread", "true");
}
// Rediriger vers la nouvelle URL avec les paramètres mis à jour
router.push(`${pathname}?${params.toString()}`);
};
const handleUnreadFilter = () => {
setIsChangingPage(true);
const params = new URLSearchParams(searchParams);
params.set("page", "1"); // Retourner à la première page lors du changement de filtre
if (!showOnlyUnread) {
params.set("unread", "true");
} else {
params.delete("unread");
}
setShowOnlyUnread(!showOnlyUnread);
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);
@@ -62,6 +81,13 @@ export function PaginatedSeriesGrid({
"Aucune série trouvée"
)}
</p>
<button
onClick={handleUnreadFilter}
className="flex items-center gap-2 px-3 py-2 text-sm font-medium rounded-lg hover:bg-accent hover:text-accent-foreground"
>
<Filter className="h-4 w-4" />
{showOnlyUnread ? "Afficher tout" : "À lire"}
</button>
</div>
<div className="relative">

View File

@@ -0,0 +1,91 @@
"use client";
import Image from "next/image";
import { ImageOff } from "lucide-react";
import { KomgaSeries } from "@/types/komga";
interface SeriesHeaderProps {
series: KomgaSeries;
serverUrl: string;
}
export function SeriesHeader({ series, serverUrl }: SeriesHeaderProps) {
return (
<div className="flex flex-col md:flex-row gap-8">
{/* Couverture */}
<div className="w-48 shrink-0">
<div className="relative aspect-[2/3] rounded-lg overflow-hidden bg-muted">
<Image
src={`/api/komga/images/series/${series.id}/thumbnail`}
alt={`Couverture de ${series.metadata.title}`}
fill
className="object-cover"
/>
</div>
</div>
{/* Informations */}
<div className="flex-1 space-y-4">
<div>
<h1 className="text-3xl font-bold">{series.metadata.title}</h1>
{series.metadata.status && (
<span
className={`mt-2 inline-block px-2 py-1 rounded-full text-xs ${
series.metadata.status === "ENDED"
? "bg-green-500/10 text-green-500"
: series.metadata.status === "ONGOING"
? "bg-blue-500/10 text-blue-500"
: series.metadata.status === "ABANDONED"
? "bg-destructive/10 text-destructive"
: "bg-yellow-500/10 text-yellow-500"
}`}
>
{series.metadata.status === "ENDED"
? "Terminé"
: series.metadata.status === "ONGOING"
? "En cours"
: series.metadata.status === "ABANDONED"
? "Abandonné"
: "En pause"}
</span>
)}
</div>
{series.metadata.summary && (
<p className="text-muted-foreground">{series.metadata.summary}</p>
)}
<div className="space-y-1 text-sm text-muted-foreground">
{series.metadata.publisher && (
<div>
<span className="font-medium">Éditeur :</span> {series.metadata.publisher}
</div>
)}
{series.metadata.genres?.length > 0 && (
<div>
<span className="font-medium">Genres :</span> {series.metadata.genres.join(", ")}
</div>
)}
{series.metadata.tags?.length > 0 && (
<div>
<span className="font-medium">Tags :</span> {series.metadata.tags.join(", ")}
</div>
)}
{series.metadata.language && (
<div>
<span className="font-medium">Langue :</span>{" "}
{new Intl.DisplayNames([navigator.language], { type: "language" }).of(
series.metadata.language
)}
</div>
)}
{series.metadata.ageRating && (
<div>
<span className="font-medium">Âge recommandé :</span> {series.metadata.ageRating}+
</div>
)}
</div>
</div>
</div>
);
}