# Swipe-to-close lightbox

> Tap an artwork and it flies from the grid to full screen. Drag it up or down to send it back.

- Category: [Overlays](https://library.aimran.es/components/overlays)
- Built with: React + Motion
- Live editor: https://library.aimran.es/blocks/drag-dismiss-lightbox
- Library: AIMRAN Library (https://library.aimran.es), free, no sign-up, by Aimran Oukham

## Where to use it

A lightbox you can swipe away feels right in any gallery people browse with their thumb: a painter's portfolio, product photos in an online shop or the pictures of a holiday rental. The image grows out of its thumbnail and the dark background fades as you drag, so closing it feels physical.

The pieces are gradients standing in for real images, so the first job is dropping in your photos. There are no arrows to jump between pictures; each one opens on its own. If people keep closing it by accident, raise the drag distance.

## Code

### React (Motion)

```tsx
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: "Digital oil · 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: "Digital oil · 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: "Tide",
    meta: "Digital oil · 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]">Collection</p>
            <h2 className="mt-1 text-[22px] font-semibold tracking-[-0.03em]">Autumn light</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={"Open " + 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]">Tap a piece · drag to close</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="Close" 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">Drag to close</p>
                )}
              </motion.div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
```

## Prompt for AI assistants

Paste this into ChatGPT, Claude, Cursor, v0 or Lovable to adapt the block to your stack (Tailwind, Vue, Svelte…):

````text
I want to add the “Swipe-to-close lightbox” block (Overlays) from AIMRAN Library to my project.

## What it is
Tap an artwork and it flies from the grid to full screen. Drag it up or down to send it back.

## Chosen settings
- Drag to close: 110px (from 60 to 200px)
- Photo radius: 18px (from 0 to 28px)
- Pie con título: yes

## What I need
1. Add it to my project with the same look and animation as the reference code: same sizes, colours, radii, shadows, timings and easing.
2. It is built with React + TypeScript, with framer-motion for the animation and lucide-react for the icons. If my project uses something else (Vue, Svelte, Astro, plain HTML…), translate it without losing any behaviour. If I use Tailwind, turn the styles into classes; if not, keep the CSS in its own file.
3. Expose the settings above as props (or CSS variables) with those values as defaults.
4. Make it work well on phones: nothing that depends only on hover, touch targets of at least 44 px and no overflow on 320 px screens.
5. Make it look right in light and dark mode.
6. Keep it accessible: semantic HTML, roles and aria-* where needed, visible focus and keyboard support.
7. Respect prefers-reduced-motion: with reduced motion, no big animations but the same end result.

## Reference code
```tsx
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: "Digital oil · 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: "Digital oil · 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: "Tide",
    meta: "Digital oil · 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]">Collection</p>
            <h2 className="mt-1 text-[22px] font-semibold tracking-[-0.03em]">Autumn light</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={"Open " + 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]">Tap a piece · drag to close</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="Close" 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">Drag to close</p>
                )}
              </motion.div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}
```

Give me the complete final code, ready to paste, and tell me in one line where to put it in my project.
````
