feat: observer viewport for cover
This commit is contained in:
@@ -2,7 +2,7 @@
|
||||
|
||||
import { ImageOff } from "lucide-react";
|
||||
import Image from "next/image";
|
||||
import { useState } from "react";
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ImageLoader } from "@/components/ui/image-loader";
|
||||
|
||||
@@ -29,6 +29,9 @@ export function Cover({
|
||||
}: CoverProps) {
|
||||
const [imageError, setImageError] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [isInViewport, setIsInViewport] = useState(false);
|
||||
const [imageUrl, setImageUrl] = useState<string | null>(null);
|
||||
const coverRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const getImageUrl = () => {
|
||||
if (type === "series") {
|
||||
@@ -37,6 +40,34 @@ export function Cover({
|
||||
return `/api/komga/images/books/${id}/thumbnail`;
|
||||
};
|
||||
|
||||
// Observer pour détecter quand la cover est dans le viewport
|
||||
useEffect(() => {
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
entries.forEach((entry) => {
|
||||
setIsInViewport(entry.isIntersecting);
|
||||
if (entry.isIntersecting && !imageUrl) {
|
||||
setImageUrl(getImageUrl());
|
||||
}
|
||||
});
|
||||
},
|
||||
{
|
||||
rootMargin: "50px", // Préchargement avant que l'élément soit visible
|
||||
}
|
||||
);
|
||||
|
||||
const element = coverRef.current;
|
||||
if (element) {
|
||||
observer.observe(element);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (element) {
|
||||
observer.unobserve(element);
|
||||
}
|
||||
};
|
||||
}, [id, imageUrl]);
|
||||
|
||||
if (imageError) {
|
||||
return (
|
||||
<div className="w-full h-full flex items-center justify-center bg-muted rounded-lg">
|
||||
@@ -46,10 +77,11 @@ export function Cover({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative w-full h-full">
|
||||
<div ref={coverRef} className="relative w-full h-full">
|
||||
<ImageLoader isLoading={isLoading} />
|
||||
{imageUrl && (
|
||||
<Image
|
||||
src={getImageUrl()}
|
||||
src={imageUrl}
|
||||
alt={alt}
|
||||
fill
|
||||
className={cn(
|
||||
@@ -65,6 +97,7 @@ export function Cover({
|
||||
quality={quality}
|
||||
priority={priority}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user