Files
reui-blocks/blocks/product-gallery7.tsx
T

346 lines
13 KiB
TypeScript

"use client";
import "photoswipe/style.css";
import PhotoSwipeLightbox from "photoswipe/lightbox";
import { useCallback, useEffect, useRef, useState } from "react";
import { AspectRatio } from "@/components/ui/aspect-ratio";
import { Badge, badgeVariants } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
import {
Carousel,
type CarouselApi,
CarouselContent,
CarouselItem,
CarouselNext,
CarouselPrevious,
} from "@/components/ui/carousel";
import { useMediaQuery } from "@/hooks/useMediaQuery";
import { cn } from "@/lib/utils";
type ProductImages = {
srcset: string;
src: string;
alt: string;
width: number;
height: number;
sizes: string;
thumbnail: string;
}[];
interface ProductGallery7Props {
images: ProductImages;
galleryID: string;
className?: string;
}
const PRODUCT_IMAGES: ProductImages = [
{
srcset:
"/block-media/shadcnblocks/block/ecommerce/skin-care-product/point-normal-Xp0bTCLD07k-unsplash-3.jpg 2160w, /block-media/shadcnblocks/block/ecommerce/skin-care-product/point-normal-Xp0bTCLD07k-unsplash-2.jpg 1920w, /block-media/shadcnblocks/block/ecommerce/skin-care-product/point-normal-Xp0bTCLD07k-unsplash-1.jpg 640w",
src: "/block-media/shadcnblocks/block/ecommerce/skin-care-product/point-normal-Xp0bTCLD07k-unsplash-3.jpg",
thumbnail:
"/block-media/shadcnblocks/block/ecommerce/skin-care-product/point-normal-Xp0bTCLD07k-unsplash-1.jpg",
sizes: "(min-width: 2160px) 2160px, (min-width: 1920px) 1920px, 100vw",
alt: "",
width: 2160,
height: 2700,
},
{
srcset:
"/block-media/shadcnblocks/block/ecommerce/skin-care-product/brittney-weng-CSquI0aw_Rg-unsplash-3.jpg 2400w, /block-media/shadcnblocks/block/ecommerce/skin-care-product/brittney-weng-CSquI0aw_Rg-unsplash-2.jpg 1920w, /block-media/shadcnblocks/block/ecommerce/skin-care-product/brittney-weng-CSquI0aw_Rg-unsplash-1.jpg 640w",
src: "/block-media/shadcnblocks/block/ecommerce/skin-care-product/brittney-weng-CSquI0aw_Rg-unsplash-3.jpg",
thumbnail:
"/block-media/shadcnblocks/block/ecommerce/skin-care-product/brittney-weng-CSquI0aw_Rg-unsplash-1.jpg",
sizes: "(min-width: 2400px) 2400px, (min-width: 1920px) 1920px, 100vw",
alt: "",
width: 2400,
height: 3000,
},
{
srcset:
"/block-media/shadcnblocks/block/ecommerce/skin-care-product/kadarius-seegars-Mxy5gokl8mE-unsplash-3.jpg 2400w, /block-media/shadcnblocks/block/ecommerce/skin-care-product/kadarius-seegars-Mxy5gokl8mE-unsplash-2.jpg 1920w, /block-media/shadcnblocks/block/ecommerce/skin-care-product/kadarius-seegars-Mxy5gokl8mE-unsplash-1.jpg 640w",
src: "/block-media/shadcnblocks/block/ecommerce/skin-care-product/kadarius-seegars-Mxy5gokl8mE-unsplash-3.jpg",
thumbnail:
"/block-media/shadcnblocks/block/ecommerce/skin-care-product/kadarius-seegars-Mxy5gokl8mE-unsplash-1.jpg",
sizes: "(min-width: 2400px) 2400px, (min-width: 1920px) 1920px, 100vw",
alt: "",
width: 2400,
height: 3600,
},
];
const ProductGallery7 = ({
images = PRODUCT_IMAGES,
galleryID = "ProductGallery7",
className,
}: ProductGallery7Props) => {
const [api, setApi] = useState<CarouselApi>();
const [current, setCurrent] = useState(0);
const lightboxRef = useRef<PhotoSwipeLightbox | null>(null);
const previewRef = useRef<HTMLDivElement>(null);
const thumbnailRef = useRef<HTMLUListElement>(null);
const isDesktop = useMediaQuery("(width >= 900px)");
useEffect(() => {
const lightbox = new PhotoSwipeLightbox({
gallery: "#" + galleryID,
children: "a",
bgOpacity: 1,
wheelToZoom: true,
arrowPrev: false,
arrowNext: false,
close: false,
zoom: false,
counter: false,
mainClass: "[&>div:first-child]:!bg-background",
pswpModule: () => import("photoswipe"),
});
const buttonClassName = cn(
buttonVariants({
variant: "outline",
size: "icon",
className: "rounded-full",
}),
);
const indicatorClassName = cn(badgeVariants({ variant: "secondary" }));
lightbox.on("uiRegister", () => {
if (lightbox?.pswp?.ui) {
lightbox.pswp.ui.registerElement({
name: "custom-close-btn",
order: 10,
isButton: false,
appendTo: "root",
className: "absolute top-5 end-5",
html: `
<button type="button" id="pswp-close" class="${buttonClassName}">
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"></path><path d="m6 6 12 12"></path></svg>
</button>
`,
onInit: (el, pswp) => {
el.querySelector("#pswp-close")?.addEventListener("click", () =>
pswp.close(),
);
},
});
}
if (lightbox?.pswp?.ui) {
lightbox.pswp.ui.registerElement({
name: "custom-indicator-btn",
order: 10,
isButton: false,
appendTo: "root",
className: "absolute top-5 start-5",
html: `
<div id="pswp-indicator" class="${indicatorClassName} h-8.5 px-4 !rounded-full">
</div>
`,
onInit: (el, pswp) => {
const indicatorElem = el.querySelector("#pswp-indicator");
pswp.on("change", () => {
if (indicatorElem) {
indicatorElem.innerHTML = `${pswp.currIndex + 1} / ${pswp.getNumItems()}`;
}
});
},
});
}
if (lightbox?.pswp?.ui) {
lightbox.pswp.ui.registerElement({
name: "custom-next-prev-btns",
order: 10,
isButton: false,
appendTo: "root",
className: "absolute top-1/2 inset-x-0 -translate-y-1/2",
html: `
<div class="flex items-center justify-between px-4">
<button type="button" id="pswp-prev" class="${buttonClassName}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 18 6-6-6-6"/></svg>
</button>
<button type="button" id="pswp-next" class="${buttonClassName}">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m15 18-6-6 6-6"/></svg>
</button>
</div>
`,
onInit: (el, pswp) => {
el.querySelector("#pswp-prev")?.addEventListener("click", () =>
pswp.next(),
);
el.querySelector("#pswp-next")?.addEventListener("click", () =>
pswp.prev(),
);
},
});
}
});
lightbox.init();
lightboxRef.current = lightbox;
return () => {
lightbox.destroy();
lightboxRef.current = null;
};
}, [galleryID]);
const onSelect = useCallback((carouselApi: CarouselApi) => {
if (!carouselApi) return;
setCurrent(carouselApi.selectedScrollSnap() + 1);
}, []);
useEffect(() => {
if (!api) return;
onSelect(api);
api.on("reInit", onSelect);
api.on("select", onSelect);
return () => {
api.off("select", onSelect);
};
}, [api, onSelect]);
useEffect(() => {
const lightbox = lightboxRef.current;
if (!lightbox || !api) return;
const syncCarousel = () => {
api.scrollTo(lightbox.pswp?.currIndex || 0);
};
lightbox.on("change", syncCarousel);
return () => {
lightbox.off("change", syncCarousel);
};
}, [api]);
useEffect(() => {
if (!previewRef.current || !thumbnailRef.current) return;
const observer = new ResizeObserver(([entry]) => {
if (!isDesktop && thumbnailRef.current) {
thumbnailRef.current.style.height = `${entry.contentRect.height}px`;
}
});
if (!isDesktop) {
observer.observe(previewRef.current);
}
return () => observer.disconnect();
}, [isDesktop]);
if (!images) return;
return (
<section dir="rtl" className={cn("mx-auto w-full max-w-193", className)}>
<div className="flex w-full items-start justify-center gap-4">
<ul
ref={thumbnailRef}
className="hidden w-20 shrink-0 grow-0 flex-col gap-2 overflow-y-auto [-ms-overflow-style:none] [scrollbar-width:none] md:flex [::-webkit-scrollbar]:hidden"
>
{images.map((img, index) => (
<li
className="w-full shrink-0"
key={`product-gallery-7-thumbnail-${index}`}
>
<button
onClick={() => api?.scrollTo(index)}
data-state={index + 1 === current ? "active" : "inactive"}
type="button"
className="relative block size-20 overflow-hidden rounded-[0.875rem] after:pointer-events-none after:absolute after:inset-0 after:z-10 after:block after:size-full after:rounded-[0.875rem] after:inset-ring-2 after:inset-ring-transparent after:transition-shadow after:duration-200 after:content-[''] data-[state=active]:after:inset-ring-current"
>
<img
src={img.thumbnail}
alt={img.alt}
className="block size-full object-cover object-center"
loading="lazy"
/>
</button>
</li>
))}
</ul>
<div className="w-full md:max-w-2xl">
<div className="group/product-photos relative h-fit w-full">
<Badge className="absolute top-4 start-4 z-10 rounded-full bg-lime-200 px-4 py-1 text-base leading-snug text-black">
New
</Badge>
<div className="pswp-gallery" id={galleryID}>
<Carousel
dir="rtl"
setApi={setApi}
opts={{ direction: "rtl", align: "start" }}
className="w-full"
>
<CarouselContent className="-ms-2">
{images.map((img, index) => (
<CarouselItem
key={`product-gallery-7-image-${index}`}
className="w-full ps-2"
>
<AspectRatio
ref={index === 0 ? previewRef : undefined}
ratio={0.8}
className="w-full overflow-hidden rounded-[0.875rem] bg-muted"
>
<a
href={img.src}
data-pswp-width={img.width}
data-pswp-height={img.height}
data-pswp-srcset={img.srcset}
data-cropped="true"
className="block size-full hover:cursor-zoom-in"
>
<img
src={img.src}
srcSet={img.srcset}
alt={img.alt}
width={img.width}
height={img.height}
sizes={img.sizes}
className="block size-full rounded-[0.875rem] object-cover object-center"
/>
</a>
</AspectRatio>
</CarouselItem>
))}
</CarouselContent>
<div className="hidden opacity-0 group-hover/product-photos:opacity-100 md:block">
{current > 1 && (
<CarouselPrevious className="start-0 ms-6 size-11 dark:bg-white dark:hover:bg-white dark:[&>svg]:stroke-black" />
)}
{current < images.length && (
<CarouselNext className="end-0 me-6 size-11 dark:bg-white dark:hover:bg-white dark:[&>svg]:stroke-black" />
)}
</div>
</Carousel>
</div>
<Badge
className="absolute bottom-4 start-4 rounded-full bg-background py-1.5 text-xs xl:hidden"
variant="secondary"
>
{current || 1} / {images.length}
</Badge>
</div>
<div className="relative my-2 h-[0.1875rem] w-full overflow-hidden rounded-[0.625rem] bg-muted xl:hidden">
<div
style={{
width: `calc(100% / ${images.length})`,
insetInlineStart: `calc((100% / ${images.length}) * ${current - 1})`,
}}
className="absolute h-full bg-foreground transition-[inset-inline-start] duration-300"
></div>
</div>
</div>
</div>
</section>
);
};
export { ProductGallery7 };