Colección

Luz de otoño

3 obras

Toca una obra · arrástrala para cerrarla

React + MotionOverlays

Lightbox que se cierra arrastrando

La obra que tocas vuela de la cuadrícula a pantalla completa; arrástrala arriba o abajo y vuelve a su hueco.

Ajustes

110px
18px

Código

import { useEffect, useRef, useState, type RefObject } from "react";
import { AnimatePresence, motion, useMotionValue, useReducedMotion, useTransform } from "framer-motion";
import { X } from "lucide-react";

const WORKS = [
  {
    id: "bruma",
    title: "Bruma",
    meta: "Óleo digital · 120 × 150 cm",
    art: "radial-gradient(80% 60% at 30% 18%, #f0f9ff 0%, transparent 60%), radial-gradient(90% 70% at 85% 95%, #0e5a73 0%, transparent 62%), linear-gradient(180deg, #bfe3f5 0%, #56b3d9 45%, #144a5c 100%)",
  },
  {
    id: "brasa",
    title: "Brasa",
    meta: "Óleo digital · 90 × 90 cm",
    art: "radial-gradient(70% 55% at 70% 25%, #ffe6a8 0%, transparent 60%), radial-gradient(100% 80% at 5% 100%, #6e1423 0%, transparent 60%), linear-gradient(160deg, #fb9a4b 0%, #e2344f 55%, #470b1f 100%)",
  },
  {
    id: "marea",
    title: "Marea",
    meta: "Óleo digital · 90 × 90 cm",
    art: "radial-gradient(80% 60% at 20% 85%, #c9bcff 0%, transparent 60%), radial-gradient(70% 60% at 90% 10%, #f5b4f5 0%, transparent 55%), linear-gradient(200deg, #2b2a7a 0%, #6a35d8 50%, #1b1745 100%)",
  },
];

const GRAIN = "url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='180' height='180'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.8' numOctaves='3' stitchTiles='stitch'/></filter><rect width='100%' height='100%' filter='url(%23n)'/></svg>\")";

const morph = { type: "spring" as const, stiffness: 320, damping: 32, mass: 0.9 };

const FOCUSABLE =
  'a[href],button:not([disabled]),input:not([disabled]),select,textarea,[tabindex]:not([tabindex="-1"])';

// Modal accesible: enfoca el primer control (o el marcado con data-autofocus), atrapa Tab, cierra con Esc y devuelve el foco
function useDialog(ref: RefObject<HTMLElement | null>, open: boolean, onClose: () => void) {
  const close = useRef(onClose);
  useEffect(() => {
    close.current = onClose;
  });
  useEffect(() => {
    if (!open) return;
    const previous = document.activeElement as HTMLElement | null;
    const node = ref.current;
    const first =
      node?.querySelector<HTMLElement>("[data-autofocus]") ?? node?.querySelector<HTMLElement>(FOCUSABLE);
    first?.focus({ preventScroll: true });
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        e.preventDefault();
        close.current();
        return;
      }
      if (e.key !== "Tab" || !node) return;
      const items = Array.from(node.querySelectorAll<HTMLElement>(FOCUSABLE));
      if (!items.length) return;
      const firstItem = items[0];
      const lastItem = items[items.length - 1];
      if (!firstItem || !lastItem) return;
      if (!node.contains(document.activeElement)) {
        e.preventDefault();
        firstItem.focus();
      } else if (e.shiftKey && document.activeElement === firstItem) {
        e.preventDefault();
        lastItem.focus();
      } else if (!e.shiftKey && document.activeElement === lastItem) {
        e.preventDefault();
        firstItem.focus();
      }
    };
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("keydown", onKey);
      previous?.focus({ preventScroll: true });
    };
  }, [open, ref]);
}

interface LightboxProps {
  /** Píxeles de arrastre vertical para cerrar */
  threshold?: number;
  caption?: boolean;
  radius?: number;
}

export default function Lightbox({
  threshold = 110,
  caption = true,
  radius = 18,
}: LightboxProps) {
  const [openId, setOpenId] = useState<string | null>(null);
  const panel = useRef<HTMLDivElement>(null);
  const y = useMotionValue(0);
  const fade = useTransform(y, [-260, 0, 260], [0, 1, 0]);
  const shrink = useTransform(y, [-260, 0, 260], [0.8, 1, 0.8]);
  const reduce = useReducedMotion();
  const work = WORKS.find((w) => w.id === openId);
  const transition = reduce ? { duration: 0 } : morph;
  const close = () => setOpenId(null);
  useDialog(panel, !!work, close);
  useEffect(() => {
    if (work) y.set(0);
  }, [work, y]);

  return (
    <div className="flex w-full flex-col items-center bg-[#f7f7f7] p-5 text-[#1d1d1f] dark:bg-[#0a0a0a] dark:text-[#f5f5f7]">
      <div className="w-full max-w-[420px]">
        <div className="mb-4 flex items-end justify-between">
          <div>
            <p className="text-[11px] font-medium uppercase tracking-[0.22em] text-[#86868b]">Colección</p>
            <h2 className="mt-1 text-[22px] font-semibold tracking-[-0.03em]">Luz de otoño</h2>
          </div>
          <span className="text-[12px] text-[#86868b]">{WORKS.length} obras</span>
        </div>
        <div className="grid aspect-[4/3] w-full grid-cols-5 grid-rows-2 gap-2">
          {WORKS.map((w, i) => (
            <motion.button
              key={w.id}
              type="button"
              layoutId={"work-" + w.id}
              transition={transition}
              aria-label={"Abrir " + w.title}
              aria-haspopup="dialog"
              onClick={() => setOpenId(w.id)}
              whileHover={{ scale: 1.015 }}
              whileTap={{ scale: 0.98 }}
              className={"relative overflow-hidden outline-none shadow-[0_1px_2px_rgba(0,0,0,0.1),0_10px_30px_-12px_rgba(0,0,0,0.35)] focus-visible:ring-2 focus-visible:ring-[#0071e3] focus-visible:ring-offset-2 " + (i === 0 ? "col-span-3 row-span-2" : "col-span-2")}
              style={{ borderRadius: 16, background: w.art }}
            >
              <span aria-hidden className="pointer-events-none absolute inset-0 opacity-[0.22] mix-blend-overlay" style={{ backgroundImage: GRAIN }} />
            </motion.button>
          ))}
        </div>
        <p className="mt-4 text-[12px] text-[#86868b]">Toca una obra · arrástrala para cerrarla</p>
      </div>

      <AnimatePresence>
        {work && (
          // fixed: el visor ocupa toda la ventana
          <motion.div
            key="viewer"
            ref={panel}
            role="dialog"
            aria-modal="true"
            aria-label={work.title}
            className="fixed inset-0 z-50 flex flex-col text-white"
          >
            <motion.div
              aria-hidden
              className="absolute inset-0"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              transition={{ duration: reduce ? 0 : 0.25 }}
            >
              <motion.div className="absolute inset-0 bg-[#050505]" style={{ opacity: fade }} onClick={close} />
            </motion.div>
            <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="relative flex justify-end p-3">
              <motion.div style={{ opacity: fade }}>
                <button type="button" aria-label="Cerrar" onClick={close} className="grid h-9 w-9 place-items-center rounded-full bg-white/10 text-white ring-1 ring-inset ring-white/15 backdrop-blur-md transition hover:bg-white/20">
                  <X className="h-4 w-4" strokeWidth={1.5} />
                </button>
              </motion.div>
            </motion.div>
            <div className="pointer-events-none relative flex min-h-0 flex-1 items-center justify-center px-6">
              <motion.div
                layoutId={"work-" + work.id}
                transition={transition}
                drag="y"
                dragConstraints={{ top: 0, bottom: 0 }}
                dragElastic={0.9}
                onDragEnd={(_, info) => {
                  if (Math.abs(info.offset.y) > threshold || Math.abs(info.velocity.y) > 700) close();
                }}
                className="pointer-events-auto relative aspect-[4/5] h-full max-h-[440px] max-w-full cursor-grab touch-none overflow-hidden shadow-[0_40px_100px_-20px_rgba(0,0,0,0.7)] active:cursor-grabbing"
                style={{ y, scale: shrink, borderRadius: radius, background: work.art }}
              >
                <span aria-hidden className="pointer-events-none absolute inset-0 opacity-[0.22] mix-blend-overlay" style={{ backgroundImage: GRAIN }} />
              </motion.div>
            </div>
            <motion.div
              initial={{ opacity: 0, y: 8 }}
              animate={{ opacity: 1, y: 0, transition: { delay: reduce ? 0 : 0.12 } }}
              exit={{ opacity: 0, transition: { duration: 0.1 } }}
              className="relative px-6 pb-5 pt-4 text-center"
            >
              <motion.div style={{ opacity: fade }}>
                {caption ? (
                  <>
                    <p className="text-[15px] font-medium">{work.title}</p>
                    <p className="mt-0.5 text-[12px] text-white/55">{work.meta}</p>
                  </>
                ) : (
                  <p className="text-[12px] text-white/55">Arrastra para cerrar</p>
                )}
              </motion.div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

Prompt para IA

Pégalo en ChatGPT, Claude o Cursor y adaptará el bloque a tu proyecto con estos ajustes, aunque no uses React.

Más en Overlays

Dónde usarlo

Un lightbox que se cierra arrastrando queda bien en cualquier galería que se recorre con el pulgar: el portfolio de una ilustradora, las fotos de producto de una tienda online o las imágenes de un apartamento turístico. La foto sale de su miniatura y el fondo se aclara mientras la arrastras, así que cerrar tiene algo físico.

Las obras son degradados que hacen de imagen, así que lo primero es poner tus fotos. No hay flechas para pasar de una a otra: cada foto se abre por separado. Si la gente lo cierra sin querer, sube la distancia de arrastre.