# Lightbox

> An image and video gallery that opens full screen with swipe and pinch to zoom, built on PhotoSwipe

A React component for projects built on shadcn/ui. The [interactive docs](https://alexandrejoly.me/components/lightbox) show each example live.

```tsx
import {
  Lightbox,
  LightboxActions,
  LightboxClose,
  LightboxContent,
  LightboxCounter,
  LightboxItem,
  LightboxNext,
  LightboxPrevious,
  LightboxZoom,
} from "@/components/ui/lightbox";

const LANDSCAPES = [
  { alt: "A turquoise mountain lake", name: "lake-forest" },
  { alt: "Clouds mirrored in a mountain lake", name: "mirror-lake" },
  { alt: "Snowy mountains in sunlight", name: "peaks" },
  { alt: "A wave breaking on a sandy shore", name: "shore" },
  { alt: "A wintry evergreen forest from above", name: "snow-forest" },
  { alt: "A wet mountain valley", name: "wet-valley" },
];

export const LightboxDemo = () => (
  <Lightbox className="w-full max-w-sm">
    {LANDSCAPES.map(({ alt, name }) => (
      <LightboxItem
        height={1200}
        href={`/demos/lightbox/${name}.png`}
        key={name}
        width={960}
      >
        <img
          alt={alt}
          className="aspect-4/5 w-full rounded-lg object-cover"
          height={300}
          src={`/demos/lightbox/${name}-thumb.png`}
          width={240}
        />
      </LightboxItem>
    ))}
    <LightboxContent>
      <LightboxCounter />
      <LightboxActions>
        <LightboxZoom />
        <LightboxClose />
      </LightboxActions>
      <LightboxPrevious />
      <LightboxNext />
    </LightboxContent>
  </Lightbox>
);
```

## Installation

With the shadcn CLI:

```bash
pnpm dlx shadcn@latest add @alexandrejoly/lightbox
```

Or by hand:

1. Install the dependencies:

   ```bash
   pnpm add @base-ui/react photoswipe
   ```
2. Add the shadcn components it builds on:

   ```bash
   pnpm dlx shadcn@latest add button
   ```
3. Copy the source into `components/ui/lightbox.tsx`, then update the import paths to match your aliases:

   ```tsx
   "use client";

   import { mergeProps } from "@base-ui/react/merge-props";
   import type { PhotoSwipeOptions } from "photoswipe";
   import PhotoSwipeLightbox from "photoswipe/lightbox";
   import {
     createContext,
     use,
     useCallback,
     useEffect,
     useId,
     useMemo,
     useRef,
     useState,
   } from "react";
   import { createPortal, flushSync } from "react-dom";

   import "photoswipe/style.css";
   import { Button } from "@/components/ui/button";
   import { cn } from "@/lib/utils";
   import { MagnifyingGlassMinusIcon, MagnifyingGlassPlusIcon, XIcon, CaretLeftIcon, CaretRightIcon } from "@phosphor-icons/react";

   type PhotoSwipe = NonNullable<PhotoSwipeLightbox["pswp"]>;

   type LightboxOptions = Omit<
     PhotoSwipeOptions,
     "children" | "dataSource" | "gallery" | "pswpModule"
   >;

   interface LightboxViewer {
     container: HTMLElement;
     pswp: PhotoSwipe;
   }

   interface LightboxSlide {
     canZoom: boolean;
     index: number;
     isZoomed: boolean;
     item: HTMLElement | null;
   }

   const CLOSED_SLIDE: LightboxSlide = {
     canZoom: false,
     index: 0,
     isZoomed: false,
     item: null,
   };

   const isSameSlide = (a: LightboxSlide, b: LightboxSlide) =>
     a.canZoom === b.canZoom &&
     a.index === b.index &&
     a.isZoomed === b.isZoomed &&
     a.item === b.item;

   interface LightboxContextValue {
     caption: HTMLElement | null;
     registerCaption: (node: HTMLElement | null) => void;
     slide: LightboxSlide;
     viewer: LightboxViewer | null;
   }

   const LightboxContext = createContext<LightboxContextValue | null>(null);

   function useLightboxContext() {
     const context = use(LightboxContext);
     if (!context) {
       throw new Error("useLightbox must be used within a Lightbox component");
     }
     return context;
   }

   function useLightbox() {
     const { slide, viewer } = useLightboxContext();
     const pswp = viewer?.pswp;
     const count = pswp?.getNumItems() ?? 0;
     const loop = (pswp?.options.loop ?? true) && count > 1;

     return {
       canGoNext: loop || slide.index < count - 1,
       canGoPrevious: loop || slide.index > 0,
       canZoom: slide.canZoom,
       close: () => pswp?.close(),
       count,
       index: slide.index,
       isZoomed: slide.isZoomed,
       next: () => pswp?.next(),
       previous: () => pswp?.prev(),
       toggleZoom: () => pswp?.toggleZoom(),
     };
   }

   function composeRefs<T>(...refs: (React.Ref<T> | undefined)[]) {
     return (node: T | null) => {
       for (const ref of refs) {
         if (typeof ref === "function") {
           ref(node);
         } else if (ref) {
           ref.current = node;
         }
       }
     };
   }

   const ITEM_SELECTOR = "[data-slot=lightbox-item]";
   const ITEM_CAPTION_SELECTOR = "[data-slot=lightbox-item-caption]";
   const CONTENT_SELECTOR = "[data-slot=lightbox-content]";
   const IMAGE_FRAME = 64;
   const NARROW_VIEWPORT = 640;

   const measureCaptionSpace = (
     caption: HTMLElement | null,
     item: HTMLElement | undefined
   ) => {
     const text = item?.querySelector(ITEM_CAPTION_SELECTOR);
     const probe = caption?.cloneNode(false);
     if (!(text && probe instanceof HTMLElement && caption?.parentElement)) {
       return 0;
     }
     probe.replaceChildren(
       ...Array.from(text.childNodes, (node) => node.cloneNode(true))
     );
     probe.style.visibility = "hidden";
     caption.parentElement.append(probe);
     const { marginBottom, marginTop } = getComputedStyle(probe);
     const space =
       Number.parseFloat(marginTop) +
       probe.getBoundingClientRect().height +
       Number.parseFloat(marginBottom);
     probe.remove();
     return space;
   };

   const getOptions = (
     gallery: string,
     options: LightboxOptions | undefined,
     measureCaption: (item: HTMLElement | undefined) => number
   ): PhotoSwipeOptions => ({
     arrowNext: false,
     arrowPrev: false,
     bgOpacity: 1,
     close: false,
     counter: false,
     wheelToZoom: true,
     zoom: false,
     ...(options?.padding
       ? {}
       : {
           paddingFn: (viewportSize, itemData) => {
             const side = viewportSize.x < NARROW_VIEWPORT ? 0 : IMAGE_FRAME;
             return {
               bottom: Math.max(IMAGE_FRAME, measureCaption(itemData.element)),
               left: side,
               right: side,
               top: IMAGE_FRAME,
             };
           },
         }),
     ...options,
     children: ITEM_SELECTOR,
     gallery: `#${CSS.escape(gallery)}`,
     mainClass: cn(
       "[--pswp-bg:var(--background)]! [--pswp-error-text-color:var(--muted-foreground)]! [--pswp-icon-color:var(--foreground)]! [--pswp-placeholder-bg:var(--muted)]!",
       options?.mainClass
     ),
     pswpModule: () => import("photoswipe"),
   });

   const videoIn = (element: HTMLElement | undefined) =>
     element?.querySelector("video");

   interface LightboxProps extends React.ComponentProps<"div"> {
     options?: LightboxOptions;
   }

   function Lightbox({ className, id, options, ...props }: LightboxProps) {
     const autoId = useId();
     const galleryId = id ?? autoId;
     const lightboxRef = useRef<PhotoSwipeLightbox | null>(null);
     const optionsRef = useRef(options);
     const captionRef = useRef<HTMLElement | null>(null);
     const captionSpaceRef = useRef(new WeakMap<HTMLElement, number>());
     const [caption, setCaption] = useState<HTMLElement | null>(null);
     const [viewer, setViewer] = useState<LightboxViewer | null>(null);
     const [slide, setSlide] = useState<LightboxSlide>(CLOSED_SLIDE);

     const registerCaption = useCallback((node: HTMLElement | null) => {
       captionRef.current = node;
       setCaption(node);
     }, []);

     const measureCaption = useCallback((item: HTMLElement | undefined) => {
       const space = measureCaptionSpace(captionRef.current, item);
       if (item) {
         captionSpaceRef.current.set(item, space);
       }
       return space;
     }, []);

     useEffect(() => {
       optionsRef.current = options;
       const lightbox = lightboxRef.current;
       if (lightbox) {
         lightbox.options = getOptions(galleryId, options, measureCaption);
       }
     }, [galleryId, measureCaption, options]);

     useEffect(() => {
       const lightbox = new PhotoSwipeLightbox(
         getOptions(galleryId, optionsRef.current, measureCaption)
       );
       lightboxRef.current = lightbox;

       lightbox.on("contentLoad", (event) => {
         const { content } = event;
         if (content.type !== "video") {
           return;
         }
         event.preventDefault();
         const video = document.createElement("video");
         video.className = "size-full";
         video.controls = true;
         video.playsInline = true;
         video.preload = "metadata";
         video.src = content.data.src ?? "";
         const element = document.createElement("div");
         element.append(video);
         content.element = element;
       });

       lightbox.on("contentActivate", ({ content }) => {
         void videoIn(content.element)
           ?.play()
           .catch(() => undefined);
       });

       lightbox.on("contentDeactivate", ({ content }) => {
         videoIn(content.element)?.pause();
       });

       lightbox.on("uiRegister", () => {
         lightbox.pswp?.ui?.registerElement({
           appendTo: "root",
           name: "lightbox-content",
           onInit: (container, pswp) => {
             const syncSlide = () => {
               const current = pswp.currSlide;
               if (!current) {
                 return;
               }
               const { currZoomLevel, zoomLevels } = current;
               const isZoomed = currZoomLevel > zoomLevels.initial;
               const next: LightboxSlide = {
                 canZoom:
                   current.isZoomable() &&
                   (isZoomed || zoomLevels.secondary > zoomLevels.initial),
                 index: pswp.currIndex,
                 isZoomed,
                 item: current.data.element ?? null,
               };
               const content = container.querySelector(CONTENT_SELECTOR);
               const contentTop = content
                 ? Number.parseFloat(getComputedStyle(content).paddingTop)
                 : 0;
               container.style.setProperty(
                 "--lightbox-image-bottom",
                 `${current.pan.y + current.height * currZoomLevel - contentTop}px`
               );
               container.toggleAttribute("data-zoomed", isZoomed);
               setSlide((previous) =>
                 isSameSlide(previous, next) ? previous : next
               );
             };

             const startIndex = pswp.options.index ?? 0;
             flushSync(() => {
               setViewer({ container, pswp });
               setSlide({
                 ...CLOSED_SLIDE,
                 index: startIndex,
                 item: pswp.getItemData(startIndex).element ?? null,
               });
             });

             pswp.on("change", syncSlide);
             pswp.on("zoomPanUpdate", syncSlide);
             pswp.on("loadComplete", syncSlide);
             pswp.on("loadError", syncSlide);

             const setAnimating = (isAnimating: boolean) =>
               container.toggleAttribute("data-animating", isAnimating);
             setAnimating(true);
             pswp.on("openingAnimationEnd", () => setAnimating(false));
             pswp.on("closingAnimationStart", () => setAnimating(true));
           },
         });
       });

       lightbox.on("destroy", () => {
         setViewer(null);
         setSlide(CLOSED_SLIDE);
       });

       lightbox.init();

       return () => {
         lightbox.destroy();
         lightboxRef.current = null;
       };
     }, [galleryId, measureCaption]);

     useEffect(() => {
       const { item } = slide;
       if (!(caption && viewer && item)) {
         return;
       }
       const observer = new ResizeObserver(() => {
         const reserved = captionSpaceRef.current.get(item);
         if (reserved !== undefined && measureCaption(item) !== reserved) {
           viewer.pswp.updateSize(true);
         }
       });
       observer.observe(caption);
       return () => observer.disconnect();
     }, [caption, measureCaption, slide, viewer]);

     const context = useMemo<LightboxContextValue>(
       () => ({ caption, registerCaption, slide, viewer }),
       [caption, registerCaption, slide, viewer]
     );

     return (
       <LightboxContext value={context}>
         <div
           className={cn(
             "grid grid-cols-[repeat(auto-fill,minmax(--spacing(24),1fr))] gap-2",
             className
           )}
           data-slot="lightbox"
           id={galleryId}
           {...props}
         />
       </LightboxContext>
     );
   }

   interface LightboxItemProps extends Omit<React.ComponentProps<"a">, "type"> {
     height: number;
     sizes?: string;
     srcSet?: string;
     type?: "image" | "video";
     width: number;
   }

   function LightboxItem({
     className,
     height,
     sizes,
     srcSet,
     type = "image",
     width,
     ...props
   }: LightboxItemProps) {
     return (
       <a
         className={cn(
           "focus-visible:ring-ring/50 cursor-zoom-in outline-none focus-visible:ring-3",
           className
         )}
         data-cropped="true"
         data-pswp-height={height}
         data-pswp-sizes={sizes}
         data-pswp-srcset={srcSet}
         data-pswp-type={type}
         data-pswp-width={width}
         data-slot="lightbox-item"
         {...props}
       />
     );
   }

   function LightboxItemCaption({
     children,
     ref,
     ...props
   }: React.ComponentProps<"div">) {
     const { caption, slide } = useLightboxContext();
     const [node, setNode] = useState<HTMLDivElement | null>(null);
     const setRefs = useMemo(() => composeRefs(ref, setNode), [ref]);
     const isOpen = node !== null && node.closest(ITEM_SELECTOR) === slide.item;

     return (
       <>
         <div data-slot="lightbox-item-caption" hidden ref={setRefs} {...props}>
           {children}
         </div>
         {isOpen && caption ? createPortal(children, caption) : null}
       </>
     );
   }

   function LightboxContent({ className, ...props }: React.ComponentProps<"div">) {
     const { viewer } = useLightboxContext();

     if (!viewer) {
       return null;
     }

     return createPortal(
       <div
         className={cn(
           "text-foreground pointer-events-none absolute inset-0 z-10 grid p-4 opacity-0 transition-opacity duration-(--pswp-transition-duration) *:col-start-1 *:row-start-1 in-[.pswp--ui-visible]:opacity-100 in-[.pswp--ui-visible]:*:pointer-events-auto",
           className
         )}
         data-slot="lightbox-content"
         {...props}
       />,
       viewer.container
     );
   }

   function LightboxCounter({ className, ...props }: React.ComponentProps<"div">) {
     const { count, index } = useLightbox();

     return (
       <div
         className={cn(
           "text-muted-foreground flex h-8 items-center self-start justify-self-center text-sm",
           className
         )}
         data-slot="lightbox-counter"
         {...props}
       >
         {index + 1} / {count}
       </div>
     );
   }

   function LightboxCaption({
     className,
     ref,
     ...props
   }: React.ComponentProps<"div">) {
     const { registerCaption } = useLightboxContext();
     const setRefs = useMemo(
       () => composeRefs(ref, registerCaption),
       [ref, registerCaption]
     );

     return (
       <div
         className={cn(
           "text-muted-foreground absolute inset-x-0 top-(--lightbox-image-bottom) mt-3 mb-4 text-center text-sm transition-opacity in-data-animating:opacity-0 in-data-animating:transition-none in-data-zoomed:opacity-0",
           className
         )}
         data-slot="lightbox-caption"
         ref={setRefs}
         {...props}
       />
     );
   }

   function LightboxActions({ className, ...props }: React.ComponentProps<"div">) {
     return (
       <div
         className={cn("flex gap-2 self-start justify-self-end", className)}
         data-slot="lightbox-actions"
         {...props}
       />
     );
   }

   function LightboxZoom({
     className,
     ...props
   }: React.ComponentProps<typeof Button>) {
     const { canZoom, isZoomed, toggleZoom } = useLightbox();

     return (
       <Button
         className={cn("self-start justify-self-end", className)}
         data-slot="lightbox-zoom"
         {...mergeProps<typeof Button>(
           {
             disabled: !canZoom,
             onClick: toggleZoom,
             size: "icon",
             variant: "outline",
           },
           props
         )}
       >
         {isZoomed ? (
           <MagnifyingGlassMinusIcon aria-hidden />
         ) : (
           <MagnifyingGlassPlusIcon aria-hidden />
         )}
         <span className="sr-only">{isZoomed ? "Zoom out" : "Zoom in"}</span>
       </Button>
     );
   }

   function LightboxClose({
     className,
     ...props
   }: React.ComponentProps<typeof Button>) {
     const { close } = useLightbox();

     return (
       <Button
         className={cn("self-start justify-self-end", className)}
         data-slot="lightbox-close"
         {...mergeProps<typeof Button>(
           {
             onClick: close,
             size: "icon",
             variant: "outline",
           },
           props
         )}
       >
         <XIcon aria-hidden />
         <span className="sr-only">Close</span>
       </Button>
     );
   }

   function LightboxPrevious({
     className,
     ...props
   }: React.ComponentProps<typeof Button>) {
     const { canGoPrevious, count, previous } = useLightbox();

     if (count < 2) {
       return null;
     }

     return (
       <Button
         className={cn("self-center justify-self-start max-sm:hidden", className)}
         data-slot="lightbox-previous"
         {...mergeProps<typeof Button>(
           {
             disabled: !canGoPrevious,
             onClick: previous,
             size: "icon",
             variant: "outline",
           },
           props
         )}
       >
         <CaretLeftIcon aria-hidden />
         <span className="sr-only">Previous slide</span>
       </Button>
     );
   }

   function LightboxNext({
     className,
     ...props
   }: React.ComponentProps<typeof Button>) {
     const { canGoNext, count, next } = useLightbox();

     if (count < 2) {
       return null;
     }

     return (
       <Button
         className={cn("self-center justify-self-end max-sm:hidden", className)}
         data-slot="lightbox-next"
         {...mergeProps<typeof Button>(
           {
             disabled: !canGoNext,
             onClick: next,
             size: "icon",
             variant: "outline",
           },
           props
         )}
       >
         <CaretRightIcon aria-hidden />
         <span className="sr-only">Next slide</span>
       </Button>
     );
   }

   export {
     Lightbox,
     LightboxActions,
     LightboxCaption,
     LightboxClose,
     LightboxContent,
     LightboxCounter,
     LightboxItem,
     LightboxItemCaption,
     LightboxNext,
     LightboxPrevious,
     LightboxZoom,
     useLightbox,
   };
   ```

## Usage

```tsx
import {
  Lightbox,
  LightboxActions,
  LightboxClose,
  LightboxContent,
  LightboxCounter,
  LightboxItem,
  LightboxNext,
  LightboxPrevious,
  LightboxZoom,
} from "@/components/ui/lightbox";
```

```tsx
<Lightbox>
  {photos.map((photo) => (
    <LightboxItem
      height={photo.height}
      href={photo.src}
      key={photo.src}
      width={photo.width}
    >
      <img alt={photo.alt} src={photo.thumbnail} />
    </LightboxItem>
  ))}
  <LightboxContent>
    <LightboxCounter />
    <LightboxActions>
      <LightboxZoom />
      <LightboxClose />
    </LightboxActions>
    <LightboxPrevious />
    <LightboxNext />
  </LightboxContent>
</Lightbox>
```

## Examples

### Captions

Put a `LightboxItemCaption` in each item and a `LightboxCaption` in the content. The image shrinks to keep the caption in view, right under it.

```tsx
import {
  Lightbox,
  LightboxCaption,
  LightboxClose,
  LightboxContent,
  LightboxItem,
  LightboxItemCaption,
  LightboxNext,
  LightboxPrevious,
} from "@/components/ui/lightbox";

const LANDSCAPES = [
  {
    caption: "Fog rolling over the hills before sunrise.",
    name: "misty-hills",
    title: "Misty hills",
  },
  {
    caption: "Waves breaking on the rocks of a rough coast at dusk.",
    name: "rough-coast",
    title: "A rough ocean coast",
  },
  {
    caption: "A turquoise lake hidden in a pine forest.",
    name: "lake-forest",
    title: "A turquoise mountain lake",
  },
];

export const LightboxCaptions = () => (
  <Lightbox className="w-full max-w-sm">
    {LANDSCAPES.map(({ caption, name, title }) => (
      <LightboxItem
        height={1200}
        href={`/demos/lightbox/${name}.png`}
        key={name}
        width={960}
      >
        <img
          alt={title}
          className="aspect-4/5 w-full rounded-lg object-cover"
          height={300}
          src={`/demos/lightbox/${name}-thumb.png`}
          width={240}
        />
        <LightboxItemCaption>{caption}</LightboxItemCaption>
      </LightboxItem>
    ))}
    <LightboxContent>
      <LightboxClose />
      <LightboxPrevious />
      <LightboxNext />
      <LightboxCaption />
    </LightboxContent>
  </Lightbox>
);
```

### Video

An item with `type="video"` opens its file in a video player. Its thumbnail is any image, such as the first frame of the video.

```tsx
import {
  Lightbox,
  LightboxClose,
  LightboxContent,
  LightboxCounter,
  LightboxItem,
  LightboxNext,
  LightboxPrevious,
} from "@/components/ui/lightbox";

export const LightboxVideo = () => (
  <Lightbox className="w-full max-w-sm">
    <LightboxItem height={1200} href="/demos/lightbox/forest.png" width={960}>
      <img
        alt="A misty forest on a slope"
        className="aspect-4/5 w-full rounded-lg object-cover"
        height={300}
        src="/demos/lightbox/forest-thumb.png"
        width={240}
      />
    </LightboxItem>
    <LightboxItem
      height={864}
      href="/demos/lightbox/landscapes.mp4"
      type="video"
      width={864}
    >
      <img
        alt="Landscapes fading into one another"
        className="aspect-4/5 w-full rounded-lg object-cover"
        height={216}
        src="/demos/lightbox/landscapes-thumb.png"
        width={216}
      />
    </LightboxItem>
    <LightboxItem
      height={1200}
      href="/demos/lightbox/foggy-woodlands.png"
      width={960}
    >
      <img
        alt="Foggy woodlands"
        className="aspect-4/5 w-full rounded-lg object-cover"
        height={300}
        src="/demos/lightbox/foggy-woodlands-thumb.png"
        width={240}
      />
    </LightboxItem>
    <LightboxContent>
      <LightboxCounter />
      <LightboxClose />
      <LightboxPrevious />
      <LightboxNext />
    </LightboxContent>
  </Lightbox>
);
```

### useLightbox

`useLightbox` gives the current slide to controls of your own, here a link that downloads it.

```tsx
import { DownloadSimpleIcon } from "@phosphor-icons/react";
import { Button } from "@/components/ui/button";
import {
  Lightbox,
  LightboxClose,
  LightboxContent,
  LightboxItem,
  LightboxNext,
  LightboxPrevious,
  useLightbox,
} from "@/components/ui/lightbox";

const LANDSCAPES = [
  { alt: "Snowy mountains in sunlight", name: "peaks" },
  { alt: "A wave breaking on a sandy shore", name: "shore" },
  { alt: "A wet mountain valley", name: "wet-valley" },
];

const LightboxDownload = () => {
  const { index } = useLightbox();
  const landscape = LANDSCAPES[index];

  return (
    <Button
      className="self-end justify-self-center"
      nativeButton={false}
      render={({ children, ...props }) => (
        <a {...props} download href={`/demos/lightbox/${landscape?.name}.png`}>
          {children}
        </a>
      )}
      variant="outline"
    >
      <DownloadSimpleIcon data-icon="inline-start" />
      Download
    </Button>
  );
};

export const LightboxUseLightbox = () => (
  <Lightbox className="w-full max-w-sm">
    {LANDSCAPES.map(({ alt, name }) => (
      <LightboxItem
        height={1200}
        href={`/demos/lightbox/${name}.png`}
        key={name}
        width={960}
      >
        <img
          alt={alt}
          className="aspect-4/5 w-full rounded-lg object-cover"
          height={300}
          src={`/demos/lightbox/${name}-thumb.png`}
          width={240}
        />
      </LightboxItem>
    ))}
    <LightboxContent>
      <LightboxClose />
      <LightboxPrevious />
      <LightboxNext />
      <LightboxDownload />
    </LightboxContent>
  </Lightbox>
);
```

## Accessibility

Each item is a link to the full-size file, so the gallery still works before the script loads or without it. The thumbnail’s `alt` names the link, and the viewer reuses it for the full-size image: give every thumbnail one. `LightboxItemCaption` is `hidden` in the thumbnail, so it does not change the link’s name.

The viewer is a modal: focus moves into it and stays there, the arrow keys move between slides, Z toggles the zoom, and Escape closes it and returns focus to the item that opened it. The buttons carry their names as visually hidden text, and the zoom button’s name switches between Zoom in and Zoom out.

Meets WCAG 2.2: [4.1.2 Name, Role, Value](https://www.w3.org/WAI/WCAG22/Understanding/name-role-value.html)

## API reference

### Lightbox

The gallery: it finds every `LightboxItem` inside it and opens the viewer on the one pressed. A grid of thumbnails at least 96px wide, with as many columns as its width holds.

Takes every prop of `div`.

| Prop | Type | Description |
| --- | --- | --- |
| `options` | `PhotoSwipeOptions` | PhotoSwipe options, read each time the viewer opens, such as `loop`. PhotoSwipe’s own buttons and counter are off in favour of the parts below, the background takes `--background` at full opacity, and the mouse wheel zooms (`wheelToZoom`). The image keeps a 64px frame for the parts, none on the sides below 640px, and a caption below it takes the room it needs; `padding` or `paddingFn` replace that frame. |

### LightboxItem

A link to one full-size file, holding its thumbnail. The viewer zooms out of the thumbnail and back into it, cropped and rounded as it is.

Takes every prop of `a`.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `width, height` | `number` | — | The full-size file’s width and height in pixels. |
| `type` | `"image" \| "video"` | `"image"` | A video plays in the viewer with its controls, from the slide it is on, and pauses when you leave it. |
| `srcSet, sizes` | `string` | — | Responsive sources for the full-size image. |

### LightboxItemCaption

The item’s caption, placed inside its `LightboxItem`. It stays hidden in the thumbnail and shows in `LightboxCaption` while its item is open.

Takes every prop of `div`.

### LightboxContent

The layer over the open viewer, portaled into it; it renders nothing while the viewer is closed. It stacks its children in one grid cell over the viewer, 16px in from its edges: place each with `self-*` and `justify-self-*`, as the parts below do. Pointer events pass through it to the slides and stop on its children. It fades with the viewer’s controls, which a tap on touch screens hides and shows. Its children can read `--lightbox-image-bottom`, the image’s bottom edge from the top of the cell they share, match `data-zoomed` while the image is zoomed in and `data-animating` while the viewer opens and closes, when `--lightbox-image-bottom` does not follow the image.

Takes every prop of `div`.

### LightboxCounter

The current slide and the count, centred at the top.

Takes every prop of `div`.

### LightboxCaption

The open item’s `LightboxItemCaption`, centred under the image. Its top margin sets the gap to the image and its bottom margin the room kept below it. It follows the image as it is dragged, hides while the image is zoomed in, stays hidden until the viewer has opened and hides at once when it closes, and the image makes room again when its text changes. Items without a caption leave it empty.

Takes every prop of `div`.

### LightboxActions

Lines up `LightboxZoom` and `LightboxClose` in the top end corner.

Takes every prop of `div`.

### LightboxZoom

Outline button that zooms the image in and out; put it in `LightboxActions` beside `LightboxClose`. Disabled on a video and on an image already shown at full size. An `onClick` runs before the zoom.

Takes every prop of [shadcn Button](https://ui.shadcn.com/docs/components/base/button).

### LightboxClose

Outline button in the top end corner that closes the viewer. An `onClick` runs before it closes.

Takes every prop of [shadcn Button](https://ui.shadcn.com/docs/components/base/button).

### LightboxPrevious

Outline button on the start side, centred, that moves to the previous slide. It loops from the first slide to the last; with `loop` off, it is disabled there instead. Hidden below 640px, where you swipe, and with a single item. An `onClick` runs before the slide changes.

Takes every prop of [shadcn Button](https://ui.shadcn.com/docs/components/base/button).

### LightboxNext

Outline button on the end side, centred, that moves to the next slide. It loops from the last slide to the first; with `loop` off, it is disabled there instead. Hidden below 640px, where you swipe, and with a single item. An `onClick` runs before the slide changes.

Takes every prop of [shadcn Button](https://ui.shadcn.com/docs/components/base/button).

### useLightbox()

Reads and drives the open viewer from inside `LightboxContent`, for controls of your own.

| Return value | Type | Description |
| --- | --- | --- |
| `index, count` | `number` | The current slide, from 0, and the slide count, 0 while the viewer is closed. |
| `canGoPrevious, canGoNext` | `boolean` | Whether a slide exists before or after the current one. |
| `canZoom, isZoomed` | `boolean` | Whether the current slide can zoom, and whether it is zoomed in. |
| `previous, next, toggleZoom, close` | `() => void` | Move one slide, zoom in or out, or close the viewer. |

[All components](https://alexandrejoly.me/components.md)
