feat(i18n): translate library page

This commit is contained in:
Julien Froidefond
2025-02-27 12:29:15 +01:00
parent ed8817d76c
commit 52a212ef07
9 changed files with 147 additions and 56 deletions

View File

@@ -1,35 +1,38 @@
import { Book } from "lucide-react";
import { Cover } from "@/components/ui/cover";
import { KomgaLibrary } from "@/types/komga";
import { useTranslate } from "@/hooks/useTranslate";
interface LibraryGridProps {
libraries: KomgaLibrary[];
onLibraryClick?: (library: KomgaLibrary) => void;
}
// Fonction utilitaire pour formater la date de manière sécurisée
const formatDate = (dateString: string): string => {
// Utility function to format date safely
const formatDate = (dateString: string, locale: string): string => {
try {
const date = new Date(dateString);
if (isNaN(date.getTime())) {
return "Date non disponible";
return "Date unavailable";
}
return new Intl.DateTimeFormat("fr-FR", {
return new Intl.DateTimeFormat(locale, {
year: "numeric",
month: "long",
day: "numeric",
}).format(date);
} catch (error) {
console.error("Erreur lors du formatage de la date:", error);
return "Date non disponible";
console.error("Error formatting date:", error);
return "Date unavailable";
}
};
export function LibraryGrid({ libraries, onLibraryClick }: LibraryGridProps) {
const { t } = useTranslate();
if (!libraries.length) {
return (
<div className="text-center p-8">
<p className="text-muted-foreground">Aucune bibliothèque disponible</p>
<p className="text-muted-foreground">{t("library.empty")}</p>
</div>
);
}
@@ -49,18 +52,20 @@ interface LibraryCardProps {
}
function LibraryCard({ library, onClick }: LibraryCardProps) {
const { t, i18n } = useTranslate();
return (
<button
onClick={onClick}
className="group relative flex flex-col h-48 rounded-lg border bg-card text-card-foreground shadow-sm hover:bg-accent hover:text-accent-foreground transition-colors overflow-hidden"
>
{/* Image de couverture */}
{/* Cover image */}
<div className="absolute inset-0 bg-muted">
<div className="w-full h-full opacity-20 group-hover:opacity-30 transition-opacity">
<Cover
type="series"
id={library.id}
alt={`Couverture de ${library.name}`}
alt={t("library.coverAlt", { name: library.name })}
sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
quality={25}
readBooks={library.booksReadCount}
@@ -69,7 +74,7 @@ function LibraryCard({ library, onClick }: LibraryCardProps) {
</div>
</div>
{/* Contenu */}
{/* Content */}
<div className="relative h-full flex flex-col p-6">
<div className="flex items-center gap-3 mb-4">
<Book className="h-6 w-6 shrink-0" />
@@ -85,11 +90,13 @@ function LibraryCard({ library, onClick }: LibraryCardProps) {
: "bg-green-500/10 text-green-500"
}`}
>
{library.unavailable ? "Non disponible" : "Disponible"}
{t(library.unavailable ? "library.status.unavailable" : "library.status.available")}
</span>
</div>
<div className="text-xs text-muted-foreground">
Dernière mise à jour : {formatDate(library.lastModified)}
{t("library.lastUpdated", {
date: formatDate(library.lastModified, i18n.language === "fr" ? "fr-FR" : "en-US"),
})}
</div>
</div>
</div>

View File

@@ -8,6 +8,7 @@ import { Loader2, Filter } from "lucide-react";
import { cn } from "@/lib/utils";
import { KomgaSeries } from "@/types/komga";
import { SearchInput } from "./SearchInput";
import { useTranslate } from "@/hooks/useTranslate";
interface PaginatedSeriesGridProps {
series: KomgaSeries[];
@@ -33,18 +34,19 @@ export function PaginatedSeriesGrid({
const searchParams = useSearchParams();
const [isChangingPage, setIsChangingPage] = useState(false);
const [showOnlyUnread, setShowOnlyUnread] = useState(initialShowOnlyUnread);
const { t } = useTranslate();
// Réinitialiser l'état de chargement quand les séries changent
// Reset loading state when series change
useEffect(() => {
setIsChangingPage(false);
}, [series]);
// Mettre à jour l'état local quand la prop change
// Update local state when prop changes
useEffect(() => {
setShowOnlyUnread(initialShowOnlyUnread);
}, [initialShowOnlyUnread]);
// Appliquer le filtre par défaut au chargement initial
// Apply default filter on initial load
useEffect(() => {
if (defaultShowOnlyUnread && !searchParams.has("unread")) {
const params = new URLSearchParams(searchParams.toString());
@@ -56,75 +58,68 @@ export function PaginatedSeriesGrid({
const handlePageChange = async (page: number) => {
setIsChangingPage(true);
// Créer un nouvel objet URLSearchParams pour manipuler les paramètres
const params = new URLSearchParams(searchParams.toString());
params.set("page", page.toString());
// Conserver l'état du filtre unread
params.set("unread", showOnlyUnread.toString());
// Rediriger vers la nouvelle URL avec les paramètres mis à jour
await router.push(`${pathname}?${params.toString()}`);
};
const handleUnreadFilter = async () => {
setIsChangingPage(true);
const params = new URLSearchParams(searchParams.toString());
params.set("page", "1"); // Retourner à la première page lors du changement de filtre
params.set("page", "1");
const newUnreadState = !showOnlyUnread;
setShowOnlyUnread(newUnreadState);
// Toujours définir explicitement le paramètre unread
params.set("unread", newUnreadState.toString());
await router.push(`${pathname}?${params.toString()}`);
};
// Calcul des indices de début et de fin pour l'affichage
// Calculate start and end indices for display
const startIndex = (currentPage - 1) * pageSize + 1;
const endIndex = Math.min(currentPage * pageSize, totalElements);
const getShowingText = () => {
if (!totalElements) return t("series.empty");
return t("series.display.showing", {
start: startIndex,
end: endIndex,
total: totalElements,
});
};
return (
<div className="space-y-8">
<div className="flex items-center justify-between flex-wrap gap-4">
<div className="flex-1">
<SearchInput />
<SearchInput placeholder={t("series.filters.search")} />
</div>
<div className="flex items-center gap-4">
<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>
<p className="text-sm text-muted-foreground">{getShowingText()}</p>
<button
onClick={handleUnreadFilter}
className="inline-flex items-center gap-2 px-3 py-2 text-sm font-medium rounded-lg hover:bg-accent hover:text-accent-foreground whitespace-nowrap"
>
<Filter className="h-4 w-4" />
{showOnlyUnread ? "Afficher tout" : "À lire"}
{showOnlyUnread ? t("series.filters.showAll") : t("series.filters.unread")}
</button>
</div>
</div>
<div className="relative">
{/* Indicateur de chargement */}
{/* Loading indicator */}
{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>
<span className="text-sm">{t("sidebar.libraries.loading")}</span>
</div>
</div>
)}
{/* Grille avec animation de transition */}
{/* Grid with transition animation */}
<div
className={cn(
"transition-opacity duration-200",
@@ -137,7 +132,7 @@ export function PaginatedSeriesGrid({
<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}
{t("series.display.page", { current: currentPage, total: totalPages })}
</p>
<Pagination
currentPage={currentPage}

View File

@@ -8,7 +8,7 @@ interface SearchInputProps {
placeholder?: string;
}
export const SearchInput = ({ placeholder = "Rechercher une série..." }: SearchInputProps) => {
export const SearchInput = ({ placeholder }: SearchInputProps) => {
const router = useRouter();
const searchParams = useSearchParams();
const [isPending, startTransition] = useTransition();
@@ -42,7 +42,7 @@ export const SearchInput = ({ placeholder = "Rechercher une série..." }: Search
className="pl-9"
defaultValue={searchParams.get("search") ?? ""}
onChange={(e) => handleSearch(e.target.value)}
aria-label="Rechercher une série"
aria-label={placeholder}
/>
{isPending && (
<div className="absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2">

View File

@@ -4,47 +4,52 @@ import { KomgaSeries } from "@/types/komga";
import { useRouter } from "next/navigation";
import { cn } from "@/lib/utils";
import { Cover } from "@/components/ui/cover";
import { useTranslate } from "@/hooks/useTranslate";
interface SeriesGridProps {
series: KomgaSeries[];
}
// Fonction utilitaire pour obtenir les informations de statut de lecture
const getReadingStatusInfo = (series: KomgaSeries) => {
// Utility function to get reading status info
const getReadingStatusInfo = (series: KomgaSeries, t: (key: string, options?: any) => string) => {
if (series.booksCount === 0) {
return {
label: "Pas de tomes",
label: t("series.status.noBooks"),
className: "bg-yellow-500/10 text-yellow-500",
};
}
if (series.booksCount === series.booksReadCount) {
return {
label: "Lu",
label: t("series.status.read"),
className: "bg-green-500/10 text-green-500",
};
}
if (series.booksReadCount > 0) {
return {
label: `${series.booksReadCount}/${series.booksCount}`,
label: t("series.status.progress", {
read: series.booksReadCount,
total: series.booksCount,
}),
className: "bg-blue-500/10 text-blue-500",
};
}
return {
label: "Non lu",
label: t("series.status.unread"),
className: "bg-yellow-500/10 text-yellow-500",
};
};
export function SeriesGrid({ series }: SeriesGridProps) {
const router = useRouter();
const { t } = useTranslate();
if (!series.length) {
return (
<div className="text-center p-8">
<p className="text-muted-foreground">Aucune série disponible</p>
<p className="text-muted-foreground">{t("series.empty")}</p>
</div>
);
}
@@ -63,7 +68,7 @@ export function SeriesGrid({ series }: SeriesGridProps) {
<Cover
type="series"
id={series.id}
alt={`Couverture de ${series.metadata.title}`}
alt={t("series.coverAlt", { title: series.metadata.title })}
isCompleted={series.booksCount === series.booksReadCount}
readBooks={series.booksReadCount}
totalBooks={series.booksCount}
@@ -73,13 +78,13 @@ export function SeriesGrid({ series }: SeriesGridProps) {
<div className="flex items-center gap-2">
<span
className={`px-2 py-0.5 rounded-full text-xs ${
getReadingStatusInfo(series).className
getReadingStatusInfo(series, t).className
}`}
>
{getReadingStatusInfo(series).label}
{getReadingStatusInfo(series, t).label}
</span>
<span className="text-xs text-white/80">
{series.booksCount} tome{series.booksCount > 1 ? "s" : ""}
{t("series.books", { count: series.booksCount })}
</span>
</div>
</div>

View File

@@ -9,7 +9,7 @@ export function I18nProvider({ children, locale }: PropsWithChildren<{ locale: s
// Synchroniser la langue avec celle du cookie côté client
if (typeof window !== "undefined") {
const localeCookie = document.cookie.split("; ").find((row) => row.startsWith("NEXT_LOCALE="));
console.log(localeCookie);
if (localeCookie) {
const locale = localeCookie.split("=")[1];
if (i18n.language !== locale) {

View File

@@ -1,12 +1,32 @@
import { useTranslation } from "react-i18next";
export function useTranslate() {
const { t, i18n } = useTranslation("common");
const { t: tBase, i18n } = useTranslation("common");
const changeLanguage = (lang: string) => {
i18n.changeLanguage(lang);
};
const t = (translationKey: string, values?: { [key: string]: number | string }) => {
if (values && Object.keys(values).length > 0) {
const translatedText = tBase(translationKey, values);
const placeholderRegex = new RegExp(`(\{${Object.keys(values).join("}|{")}\})`, "g");
const parts = translatedText.split(placeholderRegex);
return parts
.map((part) => {
const key = part.replace(/[{}]/g, "");
if (values[key] !== undefined) {
return values[key];
}
return part;
})
.join("");
}
return tBase(translationKey, values);
};
return {
t,
i18n,

View File

@@ -36,6 +36,10 @@ if (!i18n.isInitialized) {
maxAge: 365 * 24 * 60 * 60, // 1 an
},
},
react: {
transSupportBasicHtmlNodes: true, // Permet l'utilisation de balises HTML de base
transKeepBasicHtmlNodesFor: ["br", "strong", "i", "p", "span"], // Liste des balises autorisées
},
});
}

View File

@@ -111,5 +111,35 @@
"cleared": "Server cache cleared successfully"
}
}
},
"library": {
"empty": "No libraries available",
"coverAlt": "Cover of {name}",
"status": {
"available": "Available",
"unavailable": "Unavailable"
},
"lastUpdated": "Last updated: {date}"
},
"series": {
"empty": "No series available",
"coverAlt": "Cover of {title}",
"status": {
"noBooks": "No books",
"read": "Read",
"unread": "Unread",
"progress": "{read}/{total}"
},
"books": "{count} book | {count} books",
"filters": {
"title": "Filters",
"showAll": "Show all",
"unread": "Unread",
"search": "Search series..."
},
"display": {
"showing": "Showing series {start} to {end} of {total}",
"page": "Page {current} of {total}"
}
}
}

View File

@@ -111,5 +111,35 @@
"cleared": "Cache serveur supprimé avec succès"
}
}
},
"library": {
"empty": "Aucune bibliothèque disponible",
"coverAlt": "Couverture de {name}",
"status": {
"available": "Disponible",
"unavailable": "Non disponible"
},
"lastUpdated": "Dernière mise à jour : {date}"
},
"series": {
"empty": "Aucune série disponible",
"coverAlt": "Couverture de {title}",
"status": {
"noBooks": "Pas de tomes",
"read": "Lu",
"unread": "Non lu",
"progress": "{read}/{total}"
},
"books": "{count} tome | {count} tomes",
"filters": {
"title": "Filtres",
"showAll": "Afficher tout",
"unread": "À lire",
"search": "Rechercher une série..."
},
"display": {
"showing": "Affichage des séries {start} à {end} sur {total}",
"page": "Page {current} sur {total}"
}
}
}