feat: no more loading on pages

This commit is contained in:
Julien Froidefond
2025-02-16 21:16:38 +01:00
parent 921e7128a5
commit 9cca472953
7 changed files with 17 additions and 197 deletions

View File

@@ -3,7 +3,6 @@ import { Inter } from "next/font/google";
import "@/styles/globals.css"; import "@/styles/globals.css";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import ClientLayout from "@/components/layout/ClientLayout"; import ClientLayout from "@/components/layout/ClientLayout";
import { NetworkProgressProvider } from "@/components/ui/network-progress";
const inter = Inter({ subsets: ["latin"] }); const inter = Inter({ subsets: ["latin"] });
@@ -114,9 +113,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })
/> />
</head> </head>
<body className={cn("min-h-screen bg-background font-sans antialiased", inter.className)}> <body className={cn("min-h-screen bg-background font-sans antialiased", inter.className)}>
<NetworkProgressProvider> <ClientLayout>{children}</ClientLayout>
<ClientLayout>{children}</ClientLayout>
</NetworkProgressProvider>
</body> </body>
</html> </html>
); );

View File

@@ -4,7 +4,6 @@ import { HeroSection } from "./HeroSection";
import { MediaRow } from "./MediaRow"; import { MediaRow } from "./MediaRow";
import { KomgaBook, KomgaSeries } from "@/types/komga"; import { KomgaBook, KomgaSeries } from "@/types/komga";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useNetworkRequest } from "@/lib/hooks/use-network-request";
interface HomeData { interface HomeData {
ongoing: KomgaSeries[]; ongoing: KomgaSeries[];
@@ -18,14 +17,14 @@ interface HomeContentProps {
export function HomeContent({ data }: HomeContentProps) { export function HomeContent({ data }: HomeContentProps) {
const router = useRouter(); const router = useRouter();
const { executeRequest } = useNetworkRequest();
const handleItemClick = async (item: KomgaSeries | KomgaBook) => { const handleItemClick = async (item: KomgaSeries | KomgaBook) => {
const path = "booksCount" in item ? `/series/${item.id}` : `/books/${item.id}`; const path = "booksCount" in item ? `/series/${item.id}` : `/books/${item.id}`;
await router.push(path);
};
await executeRequest(async () => { const handleSeriesClick = (seriesId: string) => {
router.push(path); router.push(`/series/${seriesId}`);
});
}; };
// Vérification des données pour le debug // Vérification des données pour le debug

View File

@@ -7,7 +7,6 @@ import { cn } from "@/lib/utils";
import { authService } from "@/lib/services/auth.service"; import { authService } from "@/lib/services/auth.service";
import { useEffect, useState, useCallback } from "react"; import { useEffect, useState, useCallback } from "react";
import { KomgaLibrary, KomgaSeries } from "@/types/komga"; import { KomgaLibrary, KomgaSeries } from "@/types/komga";
import { useNetworkRequest } from "@/lib/hooks/use-network-request";
interface SidebarProps { interface SidebarProps {
isOpen: boolean; isOpen: boolean;
@@ -17,7 +16,6 @@ interface SidebarProps {
export function Sidebar({ isOpen, onClose }: SidebarProps) { export function Sidebar({ isOpen, onClose }: SidebarProps) {
const pathname = usePathname(); const pathname = usePathname();
const router = useRouter(); const router = useRouter();
const { executeRequest } = useNetworkRequest();
const [libraries, setLibraries] = useState<KomgaLibrary[]>([]); const [libraries, setLibraries] = useState<KomgaLibrary[]>([]);
const [favorites, setFavorites] = useState<KomgaSeries[]>([]); const [favorites, setFavorites] = useState<KomgaSeries[]>([]);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
@@ -112,11 +110,9 @@ export function Sidebar({ isOpen, onClose }: SidebarProps) {
router.push("/login"); router.push("/login");
}; };
const handleLinkClick = async (path: string) => { const handleLinkClick = (path: string) => {
onClose(); onClose();
await executeRequest(async () => { router.push(path);
router.push(path);
});
}; };
const navigation = [ const navigation = [

View File

@@ -6,7 +6,6 @@ import { useRouter, usePathname, useSearchParams } from "next/navigation";
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { Loader2, Filter } from "lucide-react"; import { Loader2, Filter } from "lucide-react";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { useNetworkRequest } from "@/lib/hooks/use-network-request";
interface PaginatedSeriesGridProps { interface PaginatedSeriesGridProps {
series: any[]; series: any[];
@@ -26,7 +25,6 @@ export function PaginatedSeriesGrid({
const router = useRouter(); const router = useRouter();
const pathname = usePathname(); const pathname = usePathname();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const { executeRequest } = useNetworkRequest();
const [isChangingPage, setIsChangingPage] = useState(false); const [isChangingPage, setIsChangingPage] = useState(false);
const [showOnlyUnread, setShowOnlyUnread] = useState(searchParams.get("unread") === "true"); const [showOnlyUnread, setShowOnlyUnread] = useState(searchParams.get("unread") === "true");
@@ -45,9 +43,7 @@ export function PaginatedSeriesGrid({
} }
// Rediriger vers la nouvelle URL avec les paramètres mis à jour // Rediriger vers la nouvelle URL avec les paramètres mis à jour
await executeRequest(async () => { await router.push(`${pathname}?${params.toString()}`);
router.push(`${pathname}?${params.toString()}`);
});
}; };
const handleUnreadFilter = async () => { const handleUnreadFilter = async () => {
@@ -62,9 +58,11 @@ export function PaginatedSeriesGrid({
} }
setShowOnlyUnread(!showOnlyUnread); setShowOnlyUnread(!showOnlyUnread);
await executeRequest(async () => { await router.push(`${pathname}?${params.toString()}`);
router.push(`${pathname}?${params.toString()}`); };
});
const handleSeriesClick = (seriesId: string) => {
router.push(`/series/${seriesId}`);
}; };
// Calcul des indices de début et de fin pour l'affichage // Calcul des indices de début et de fin pour l'affichage

View File

@@ -7,7 +7,6 @@ import { useState, useEffect } from "react";
import { Loader2, Filter } from "lucide-react"; import { Loader2, Filter } from "lucide-react";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
import { KomgaBook } from "@/types/komga"; import { KomgaBook } from "@/types/komga";
import { useNetworkRequest } from "@/lib/hooks/use-network-request";
interface PaginatedBookGridProps { interface PaginatedBookGridProps {
books: KomgaBook[]; books: KomgaBook[];
@@ -27,7 +26,6 @@ export function PaginatedBookGrid({
const router = useRouter(); const router = useRouter();
const pathname = usePathname(); const pathname = usePathname();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const { executeRequest } = useNetworkRequest();
const [isChangingPage, setIsChangingPage] = useState(false); const [isChangingPage, setIsChangingPage] = useState(false);
const [showOnlyUnread, setShowOnlyUnread] = useState(searchParams.get("unread") === "true"); const [showOnlyUnread, setShowOnlyUnread] = useState(searchParams.get("unread") === "true");
@@ -46,9 +44,7 @@ export function PaginatedBookGrid({
} }
// Rediriger vers la nouvelle URL avec les paramètres mis à jour // Rediriger vers la nouvelle URL avec les paramètres mis à jour
await executeRequest(async () => { await router.push(`${pathname}?${params.toString()}`);
router.push(`${pathname}?${params.toString()}`);
});
}; };
const handleUnreadFilter = async () => { const handleUnreadFilter = async () => {
@@ -63,15 +59,11 @@ export function PaginatedBookGrid({
} }
setShowOnlyUnread(!showOnlyUnread); setShowOnlyUnread(!showOnlyUnread);
await executeRequest(async () => { await router.push(`${pathname}?${params.toString()}`);
router.push(`${pathname}?${params.toString()}`);
});
}; };
const handleBookClick = async (book: KomgaBook) => { const handleBookClick = (book: KomgaBook) => {
await executeRequest(async () => { router.push(`/books/${book.id}`);
router.push(`/books/${book.id}`);
});
}; };
// Calcul des indices de début et de fin pour l'affichage // Calcul des indices de début et de fin pour l'affichage

View File

@@ -1,83 +0,0 @@
"use client";
import { createContext, useContext, useState, useCallback } from "react";
import { Loader2 } from "lucide-react";
import { cn } from "@/lib/utils";
interface NetworkProgressContextType {
startProgress: (requestId: string) => void;
updateProgress: (requestId: string, progress: number) => void;
completeProgress: (requestId: string) => void;
}
const NetworkProgressContext = createContext<NetworkProgressContextType | null>(null);
export function NetworkProgressProvider({ children }: { children: React.ReactNode }) {
const [activeRequests, setActiveRequests] = useState<Record<string, number>>({});
const startProgress = useCallback((requestId: string) => {
setActiveRequests((prev) => ({ ...prev, [requestId]: 0 }));
}, []);
const updateProgress = useCallback((requestId: string, progress: number) => {
setActiveRequests((prev) => ({ ...prev, [requestId]: progress }));
}, []);
const completeProgress = useCallback((requestId: string) => {
setActiveRequests((prev) => {
const newRequests = { ...prev };
delete newRequests[requestId];
return newRequests;
});
}, []);
const requestCount = Object.keys(activeRequests).length;
return (
<NetworkProgressContext.Provider value={{ startProgress, updateProgress, completeProgress }}>
{children}
{requestCount > 0 && (
<>
{/* Barre de progression en haut */}
<div className="fixed top-0 left-0 right-0 z-50">
<div className="h-0.5 w-full bg-muted overflow-hidden">
<div className="h-full bg-primary animate-pulse" />
</div>
</div>
{/* Indicateur de chargement au centre */}
<div className="fixed top-14 left-1/2 transform -translate-x-1/2 z-50">
<div className="bg-background/80 backdrop-blur-sm rounded-lg px-3 py-1.5 flex items-center gap-2 shadow-sm">
<Loader2 className="h-3 w-3 animate-spin" />
<span className="text-xs font-medium">Chargement</span>
</div>
</div>
</>
)}
</NetworkProgressContext.Provider>
);
}
export function useNetworkProgress() {
const context = useContext(NetworkProgressContext);
if (!context) {
throw new Error("useNetworkProgress must be used within a NetworkProgressProvider");
}
return context;
}
// Fonction utilitaire pour simuler une progression
export async function simulateProgress(
requestId: string,
updateFn: (requestId: string, progress: number) => void,
duration: number = 1000
) {
const steps = 20;
const increment = 100 / steps;
const stepDuration = duration / steps;
for (let i = 1; i <= steps; i++) {
await new Promise((resolve) => setTimeout(resolve, stepDuration));
updateFn(requestId, Math.min(increment * i, 99));
}
}

View File

@@ -1,79 +0,0 @@
"use client";
import { useNetworkProgress } from "@/components/ui/network-progress";
import { useCallback, useRef, useEffect } from "react";
import { usePathname, useSearchParams } from "next/navigation";
export function useNetworkRequest() {
const { startProgress, updateProgress, completeProgress } = useNetworkProgress();
const pathname = usePathname();
const searchParams = useSearchParams();
const currentRequestId = useRef<string | null>(null);
const abortControllerRef = useRef<AbortController | null>(null);
useEffect(() => {
// Si on a un requestId en cours, c'est que la navigation est terminée
if (currentRequestId.current) {
updateProgress(currentRequestId.current, 100);
setTimeout(() => {
if (currentRequestId.current) {
completeProgress(currentRequestId.current);
currentRequestId.current = null;
}
}, 100);
}
return () => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
}
};
}, [pathname, searchParams, updateProgress, completeProgress]);
const executeRequest = useCallback(
async <T>(requestFn: () => Promise<T>): Promise<T> => {
if (!currentRequestId.current) {
currentRequestId.current = Math.random().toString(36).substring(7);
startProgress(currentRequestId.current);
abortControllerRef.current = new AbortController();
}
try {
const wrappedFn = async () => {
const originalFetch = window.fetch;
window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
if (!currentRequestId.current) return originalFetch(input, init);
const response = await originalFetch(input, {
...init,
signal: abortControllerRef.current?.signal,
});
return response;
};
try {
return await requestFn();
} finally {
window.fetch = originalFetch;
}
};
return await wrappedFn();
} catch (error) {
if (currentRequestId.current) {
completeProgress(currentRequestId.current);
currentRequestId.current = null;
}
if (abortControllerRef.current) {
abortControllerRef.current = null;
}
throw error;
}
},
[startProgress, updateProgress, completeProgress]
);
return { executeRequest };
}