# Contact Sheet

A grid of photo thumbnails that opens into a full-screen lightbox. It zooms out of the thumbnail you press, swipes, drags and pages with the arrow keys, has a thumbnail strip, and closes back into the photo you ended on. Built on ui-sdk's Dialog and Carousel, so the focus trap, scroll lock and ARIA are done.

React component from Creative UI. Docs: https://ui.krutikraut.com/docs/contact-sheet

## Installation

```bash
npx shadcn@latest add @creative-ui/contact-sheet
```

On an older shadcn CLI, use the URL: `npx shadcn@latest add https://ui.krutikraut.com/r/contact-sheet.json`

Add `@layer ui-sdk;` at the top of your global stylesheet, above `@import "tailwindcss"`.

## Dependencies

- `@ui-sdk/react@0.1.0-beta.20` (npm)
- `@ui-sdk/core@0.1.0-beta.20` (npm)
- `lucide-react` (npm)
- `utils` (shadcn)

## Usage

```tsx
import { ContactSheet } from "@/components/contact-sheet"

const photos = [
  { src: "/work/harbour.jpg", thumb: "/work/harbour-400.jpg", alt: "Fishing boats in a harbour at dawn", caption: "Harbour, 6 am" },
  { src: "/work/market.jpg", alt: "A spice stall at a night market" },
  // ...
]

export function Portfolio() {
  return <ContactSheet photos={photos} label="Harbour series" />
}

// Four fixed columns, wrapping round at the ends, reporting which photo is open.
<ContactSheet photos={photos} columns={4} loop onIndexChange={(i) => i !== null && track("photo_viewed", i)} />
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `photos` (required) | `ContactSheetPhoto[]` | - | Each photo is `{ src, alt, thumb?, caption? }`. `thumb` is a smaller file for the grid and the strip; `src` is what the lightbox shows. `src` must be unique: it is the key. |
| `label` | `string` | `"Photos"` | Names the grid for screen readers, and titles the lightbox and its carousel. |
| `columns` | `number` | - | A fixed column count. Without it the grid fits as many 9rem columns as there's room for. |
| `loop` | `boolean` | `false` | Next on the last photo goes to the first, and back from the first reaches the last. |
| `frameNumbers` | `boolean` | `true` | Small numbers under each thumbnail, like the frame numbers on a darkroom contact sheet. |
| `onIndexChange` | `(index: number \| null) => void` | - | Called with the photo's index, from 0, as the lightbox opens and pages, and with `null` when it closes. |

Also accepts all native `<div>` props.

## Also exported

- `type ContactSheetPhoto`: The shape of one photo.

## Notes

- Built on `@ui-sdk/react` Dialog and Carousel, which handle the focus trap, Escape, scroll lock, swipe and drag, arrow keys and the ARIA. Add `@layer ui-sdk;` at the top of your global stylesheet, above `@import "tailwindcss"`, so your styles win over the few rules ui-sdk adds.
- The lightbox opens from the thumbnail you pressed and closes into the photo you ended on, and focus goes back to that thumbnail, not the one you started from.
- Left and Right page from anywhere in the lightbox. The thumbnail strip is a tablist: one Tab stop, arrows to move, Home and End for the ends.
- Photos next to the current one load eagerly and the rest lazily, so a long sheet costs the grid's thumbnails up front. Give `thumb` a small file for a fast grid.
- The lightbox is always dark, whatever the page theme, so photos are judged against black. Reduced motion keeps the fade and drops the zoom.
- `@ui-sdk/react` needs React 19 and, with TypeScript, `@types/react` 19.2.10 or newer. It's in beta: this item pins 0.1.0-beta.20.

## Source

### registry/new-york/blocks/contact-sheet/contact-sheet.tsx

```tsx
"use client"

import * as React from "react"
import {
  Carousel,
  CarouselContent,
  CarouselIndicator,
  CarouselIndicatorGroup,
  CarouselItem,
  CarouselNext,
  CarouselPrevious,
  CarouselViewport,
  createCarouselController,
} from "@ui-sdk/react/carousel"
import {
  createDialogController,
  Dialog,
  DialogBackdrop,
  DialogClose,
  DialogContent,
  DialogTitle,
  DialogTrigger,
} from "@ui-sdk/react/dialog"
import { ChevronLeftIcon, ChevronRightIcon, XIcon } from "lucide-react"

import { cn } from "@/lib/utils"

export type ContactSheetPhoto = {
  src: string
  alt: string
  /** A smaller file for the grid and the strip. Falls back to `src`. */
  thumb?: string
  caption?: React.ReactNode
}

type ContactSheetProps = Omit<React.ComponentProps<"div">, "children"> & {
  photos: ContactSheetPhoto[]
  /** Names the grid, the lightbox and its carousel. */
  label?: string
  /** A fixed column count. Without it the grid fits as many 9rem columns as there's room for. */
  columns?: number
  /** Next on the last photo goes round to the first. */
  loop?: boolean
  /** Small frame numbers under each thumbnail, like a darkroom contact sheet. */
  frameNumbers?: boolean
  /** Called with the photo's index when the lightbox opens or pages, and `null` when it closes. */
  onIndexChange?: (index: number | null) => void
}

/** Centre of an element as a CSS transform origin, in viewport px. */
function originOf(el: Element | null | undefined) {
  if (!el) return "50% 50%"
  const r = el.getBoundingClientRect()
  return `${Math.round(r.left + r.width / 2)}px ${Math.round(r.top + r.height / 2)}px`
}

/** Scrolls only the strip, unlike scrollIntoView, which can also move the page behind the dialog. */
function centerInStrip(strip: HTMLElement | null, index: number) {
  const item = strip?.querySelectorAll<HTMLElement>("[data-slot=carousel-indicator]")[index]
  if (!strip || !item) return
  strip.scrollLeft = item.offsetLeft - (strip.clientWidth - item.offsetWidth) / 2
}

function ContactSheet({
  photos,
  label = "Photos",
  columns,
  loop = false,
  frameNumbers = true,
  onIndexChange,
  className,
  style,
  ...props
}: ContactSheetProps) {
  const [dialog] = React.useState(() => createDialogController())
  const [carousel] = React.useState(() => createCarouselController())
  const [page, setPage] = React.useState(1)
  const [origin, setOrigin] = React.useState("50% 50%")
  const thumbs = React.useRef<(HTMLButtonElement | null)[]>([])
  const strip = React.useRef<HTMLDivElement>(null)
  const viewport = React.useRef<HTMLDivElement>(null)

  const show = (next: number) => {
    setPage(next)
    onIndexChange?.(next - 1)
    centerInStrip(strip.current, next - 1)
  }

  if (photos.length === 0) return null

  return (
    <div
      data-slot="contact-sheet"
      className={cn("w-full", className)}
      style={{ ...style, ...(columns ? { "--contact-sheet-columns": columns } : null) } as React.CSSProperties}
      {...props}
    >
      <ul
        aria-label={label}
        className={cn(
          "grid gap-3",
          columns
            ? "grid-cols-[repeat(var(--contact-sheet-columns),minmax(0,1fr))]"
            : "grid-cols-[repeat(auto-fill,minmax(min(9rem,100%),1fr))]"
        )}
      >
        {photos.map((photo, index) => (
          <li key={photo.src} className="flex min-w-0 flex-col gap-1.5">
            <DialogTrigger
              controller={dialog}
              ref={(el: HTMLButtonElement | null) => {
                thumbs.current[index] = el
              }}
              onClick={(event: React.MouseEvent<HTMLButtonElement>) => {
                setOrigin(originOf(event.currentTarget))
                setPage(index + 1)
                onIndexChange?.(index)
              }}
              className={cn(
                "group/thumb relative block aspect-[4/3] w-full cursor-zoom-in overflow-hidden rounded-xl bg-muted",
                "ring-1 ring-foreground/10 outline-none ring-inset",
                "transition-transform duration-150 ease-out active:scale-[0.97]",
                "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
              )}
            >
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={photo.thumb ?? photo.src}
                alt={photo.alt}
                loading="lazy"
                decoding="async"
                draggable={false}
                className={cn(
                  "size-full object-cover transition-[filter] duration-200 ease-out",
                  "[@media(hover:hover)_and_(pointer:fine)]:group-hover/thumb:brightness-110"
                )}
              />
            </DialogTrigger>
            {frameNumbers && (
              <span aria-hidden className="font-mono text-[10px] leading-none tracking-wider text-muted-foreground tabular-nums">
                {String(index + 1).padStart(2, "0")}
              </span>
            )}
          </li>
        ))}
      </ul>

      <Dialog
        controller={dialog}
        onOpenChange={(open: boolean) => {
          if (open) return
          // Shrink back into the photo the viewer ended on, which is also where focus returns.
          setOrigin(originOf(thumbs.current[page - 1]))
          onIndexChange?.(null)
        }}
      >
        <DialogBackdrop
          className={cn(
            "fixed inset-0 bg-black/90 backdrop-blur-sm",
            "transition-opacity duration-200 ease-out",
            "data-starting-style:opacity-0 data-ending-style:opacity-0 data-ending-style:duration-150"
          )}
        />
        <DialogContent
          initialFocus={() => viewport.current}
          finalFocus={() => thumbs.current[page - 1]}
          style={{ transformOrigin: origin }}
          className={cn(
            "fixed inset-0 m-0 size-full max-h-none max-w-none bg-transparent p-0 text-white outline-none",
            "transition-[opacity,scale] duration-[240ms] ease-[cubic-bezier(0.23,1,0.32,1)]",
            "data-starting-style:scale-[0.92] data-starting-style:opacity-0",
            "data-ending-style:scale-[0.92] data-ending-style:opacity-0 data-ending-style:duration-150",
            "motion-reduce:data-starting-style:scale-100 motion-reduce:data-ending-style:scale-100"
          )}
          onKeyDown={(event: React.KeyboardEvent) => {
            // The viewport and the strip page with arrows themselves; this covers the buttons around them.
            const target = event.target as HTMLElement
            if (target.closest("[data-slot=carousel-viewport], [data-slot=carousel-indicator-group]")) return
            if (event.key === "ArrowRight") carousel.next()
            else if (event.key === "ArrowLeft") carousel.previous()
          }}
        >
          <Carousel
            aria-label={label}
            controller={carousel}
            loop={loop}
            page={page}
            onPageChange={show}
            className="grid size-full grid-cols-[minmax(0,1fr)] grid-rows-[auto_minmax(0,1fr)_auto]"
          >
            <header className="flex items-center justify-between gap-4 px-4 pt-4 sm:px-6">
              <DialogTitle className="min-w-0 truncate text-sm font-medium text-white/90">{label}</DialogTitle>
              <div className="flex items-center gap-3">
                <span aria-hidden className="font-mono text-xs text-white/60 tabular-nums">
                  {page} / {photos.length}
                </span>
                <DialogClose
                  aria-label="Close"
                  className={cn(
                    "grid size-9 place-items-center rounded-full bg-white/10 text-white",
                    "transition-[background-color,scale] duration-150 ease-out active:scale-[0.94]",
                    "[@media(hover:hover)_and_(pointer:fine)]:hover:bg-white/20",
                    "outline-none focus-visible:ring-2 focus-visible:ring-white/80"
                  )}
                >
                  <XIcon aria-hidden className="size-4" />
                </DialogClose>
              </div>
            </header>

            <div className="relative min-h-0">
              <CarouselViewport
                ref={viewport}
                className="size-full [scrollbar-width:none] outline-none focus-visible:ring-1 focus-visible:ring-white/40 focus-visible:ring-inset"
              >
                <CarouselContent className="h-full">
                  {photos.map((photo, index) => (
                    <CarouselItem key={photo.src} aria-label={photo.alt} className="h-full basis-full overflow-clip">
                      <figure className="flex size-full flex-col items-center justify-center gap-3 px-4 py-4 sm:px-20">
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img
                          src={photo.src}
                          alt={photo.alt}
                          loading={Math.abs(index + 1 - page) <= 1 ? "eager" : "lazy"}
                          decoding="async"
                          draggable={false}
                          className="min-h-0 max-w-full flex-1 rounded-lg object-contain select-none"
                        />
                        {photo.caption && (
                          <figcaption className="max-w-prose text-center text-sm text-pretty text-white/75">
                            {photo.caption}
                          </figcaption>
                        )}
                      </figure>
                    </CarouselItem>
                  ))}
                </CarouselContent>
              </CarouselViewport>
              <CarouselPrevious aria-label="Previous photo" className={stepClass("left-3 sm:left-5")}>
                <ChevronLeftIcon aria-hidden className="size-5" />
              </CarouselPrevious>
              <CarouselNext aria-label="Next photo" className={stepClass("right-3 sm:right-5")}>
                <ChevronRightIcon aria-hidden className="size-5" />
              </CarouselNext>
            </div>

            <CarouselIndicatorGroup
              ref={(el: HTMLDivElement | null) => {
                strip.current = el
                // Mounts as the lightbox opens: start with the current frame in view.
                centerInStrip(el, page - 1)
              }}
              aria-label="Choose a photo"
              className="relative flex gap-2 overflow-x-auto px-4 pt-3 pb-4 [scrollbar-width:none] sm:justify-center-safe sm:px-6"
            >
              {photos.map((photo, index) => (
                <CarouselIndicator
                  key={photo.src}
                  page={index + 1}
                  aria-label={photo.alt}
                  className={cn(
                    "relative h-12 w-16 shrink-0 overflow-hidden rounded-md opacity-45",
                    "transition-[opacity,scale] duration-150 ease-out active:scale-[0.95]",
                    "data-selected:opacity-100 data-selected:ring-2 data-selected:ring-white",
                    "[@media(hover:hover)_and_(pointer:fine)]:hover:opacity-80",
                    "outline-none focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-white/80"
                  )}
                >
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={photo.thumb ?? photo.src}
                    alt=""
                    loading="lazy"
                    decoding="async"
                    draggable={false}
                    className="size-full object-cover"
                  />
                </CarouselIndicator>
              ))}
            </CarouselIndicatorGroup>
          </Carousel>
        </DialogContent>
      </Dialog>
    </div>
  )
}

function stepClass(side: string) {
  return cn(
    "absolute top-1/2 hidden size-11 -translate-y-1/2 place-items-center rounded-full bg-white/10 text-white backdrop-blur-md sm:grid",
    "transition-[background-color,opacity,scale] duration-150 ease-out active:scale-[0.94]",
    "[@media(hover:hover)_and_(pointer:fine)]:hover:bg-white/20",
    // At the ends they stay focusable (aria-disabled), so dim rather than hide them.
    "data-disabled:cursor-default data-disabled:opacity-30",
    "outline-none focus-visible:ring-2 focus-visible:ring-white/80",
    side
  )
}

export { ContactSheet }
```
