zasuiv0.1
GitHub
Menú

Escaneo y rutas

Lightbox

Visor de fotos a pantalla completa: fondo oscuro, la foto entera, X para cerrar, flechas y teclado cuando hay varias. Política: toda foto que se abre con un clic usa este visor.

Dependencias: lucide-react

Uso

Instalación

Con la CLI de zasui (ver Introducción): instala el componente con sus dependencias y queda listo para usar.

pnpm dlx @medialityc/zasui add lightbox
Ver el código
'use client';

import { cn } from '@/lib/utils';
import { ChevronLeft, ChevronRight, X } from 'lucide-react';
import * as React from 'react';

export interface LightboxImage {
	url: string;
	/** Nombre del archivo, arriba a la izquierda. */
	name?: string;
	/** Texto bajo la foto (fecha, quién la subió…). */
	caption?: React.ReactNode;
}

interface LightboxProps {
	images: LightboxImage[];
	/** Foto abierta; `null` = cerrado. */
	index: number | null;
	/** Se llama con la nueva foto al navegar; con `null` al cerrar (X, Escape o clic fuera). */
	onIndexChange: (index: number | null) => void;
	/** La foto no cargó (URL firmada caducada…). */
	onError?: () => void;
	className?: string;
}

/**
 * Visor de fotos a pantalla completa: fondo oscuro, la foto entera, **X para cerrar**, flechas
 * y teclado (←, →, Escape) cuando hay varias. Política: toda foto que se abre con un clic usa
 * este visor, no una pestaña nueva ni un modal con la foto dentro. Va en línea (`fixed`, sin portal): así,
 * dentro de un modal, sus clics cuentan como clics dentro de él y no lo cierran.
 */
export function Lightbox({ images, index, onIndexChange, onError, className }: LightboxProps) {
	const open = index !== null && index >= 0 && index < images.length;
	const total = images.length;

	React.useEffect(() => {
		if (!open) return;
		const onKey = (e: KeyboardEvent) => {
			// Captura y corta: Escape cierra solo el visor, no el modal que pueda haber debajo.
			if (e.key === 'Escape') {
				e.stopPropagation();
				onIndexChange(null);
			} else if (e.key === 'ArrowRight' && total > 1) onIndexChange(((index as number) + 1) % total);
			else if (e.key === 'ArrowLeft' && total > 1) onIndexChange(((index as number) - 1 + total) % total);
		};
		const overflow = document.body.style.overflow;
		document.body.style.overflow = 'hidden';
		window.addEventListener('keydown', onKey, true);
		return () => {
			window.removeEventListener('keydown', onKey, true);
			document.body.style.overflow = overflow;
		};
	}, [open, index, total, onIndexChange]);

	if (!open) return null;
	const image = images[index as number];
	const nav = (delta: number) => (e: React.MouseEvent) => {
		e.stopPropagation();
		onIndexChange(((index as number) + delta + total) % total);
	};

	return (
		<div
			data-slot='lightbox'
			role='dialog'
			aria-modal='true'
			aria-label={image.name ?? 'Foto'}
			onClick={() => onIndexChange(null)}
			className={cn('fixed inset-0 z-[10000] flex items-center justify-center bg-black/85 p-4 backdrop-blur-sm', className)}
		>
			<div className='pointer-events-none absolute inset-x-0 top-0 flex items-center justify-between gap-3 bg-gradient-to-b from-black/60 to-transparent p-4 text-white'>
				<div className='min-w-0'>
					<p className='truncate text-sm font-semibold'>{image.name ?? 'Foto'}</p>
					{total > 1 && (
						<p className='text-xs opacity-80'>
							{(index as number) + 1} de {total}
						</p>
					)}
				</div>
			</div>
			<button
				type='button'
				aria-label='Cerrar'
				onClick={(e) => {
					e.stopPropagation();
					onIndexChange(null);
				}}
				className='absolute top-3 right-3 z-10 inline-flex h-10 w-10 items-center justify-center rounded-full bg-white/10 text-white transition hover:bg-white/25'
			>
				<X className='h-5 w-5' />
			</button>
			{total > 1 && (
				<>
					<button
						type='button'
						aria-label='Anterior'
						onClick={nav(-1)}
						className='absolute left-3 z-10 inline-flex h-11 w-11 items-center justify-center rounded-full bg-white/10 text-white transition hover:bg-white/25'
					>
						<ChevronLeft className='h-6 w-6' />
					</button>
					<button
						type='button'
						aria-label='Siguiente'
						onClick={nav(1)}
						className='absolute right-3 z-10 inline-flex h-11 w-11 items-center justify-center rounded-full bg-white/10 text-white transition hover:bg-white/25'
					>
						<ChevronRight className='h-6 w-6' />
					</button>
				</>
			)}
			<figure className='flex max-h-full max-w-full flex-col items-center gap-2' onClick={(e) => e.stopPropagation()}>
				{/* URL firmada de MinIO (host variable): no pasa por next/image. */}
				{/* eslint-disable-next-line @next/next/no-img-element */}
				<img
					key={image.url}
					src={image.url}
					alt={image.name ?? 'Foto'}
					onError={onError}
					className='max-h-[82vh] max-w-[92vw] rounded-lg object-contain shadow-2xl'
				/>
				{image.caption && <figcaption className='text-sm text-white/80'>{image.caption}</figcaption>}
			</figure>
		</div>
	);
}