|Kit

Lightbox

A full-screen image viewer that grows out of the thumbnail you clicked, with swipe, pinch, zoom and drag-to-dismiss, and shrinks back into the tile of the image you end on.

Lightbox shows a set of images full-screen, one at a time. Give it data and something to open it with: a Gallery, or a Lightbox.Trigger per thumbnail. The image grows out of the thumbnail you clicked, using the pixels already on screen, and the full-resolution file crossfades in once it has decoded. When you close it, it shrinks back into the tile of whichever image is showing, and focus goes there too.

import { Lightbox } from '@42-central/ui-react/lightbox';

const photos = [
  { src: '/photos/lake.jpg', alt: 'A mountain lake at dawn', width: 2400, height: 1600 },
  { src: '/photos/falls.jpg', alt: 'A waterfall under a stone bridge', width: 1600, height: 2400 },
  // …
];

<Lightbox data={photos} loader={cdnLoader}>
  <Gallery data={photos} loader={cdnLoader} />
</Lightbox>

Click a photo, then use the arrows, swipe, double-click to zoom, or drag the image down to close.

Basic

Each Lightbox.Trigger opens the viewer at its index. It's a <button> with aria-haspopup="dialog" and a zoom-in cursor. Put the thumbnail inside, and the viewer opens from that thumbnail's pixels.

Code

<Lightbox data={photos} loader={unsplash}>
  {photos.map((photo, index) => (
    <Lightbox.Trigger key={photo.src} index={index}>
      <Image src={photo.src} alt={photo.alt} ratio={1} sizes="96px" loader={unsplash} />
    </Lightbox.Trigger>
  ))}
</Lightbox>

Give each image a width and height when you know them. The viewer then lays the image out before it loads, and it can grow from the thumbnail. Without them it uses the thumbnail's size, or fades in once the image has loaded.

Lightbox provides the open-index seam, so a Gallery inside it needs no wiring: each tile becomes a button that opens its own index. Pass the same data to both.

Code

<Lightbox data={photos} loader={unsplash}>
  <Gallery data={photos} min={140} loader={unsplash} />
</Lightbox>

The grid crops its tiles to squares. The image opens from the crop and uncrops as it grows, without stretching. Arrow to another photo, then close: the image shrinks into that photo's tile, and focus lands on it. A masonry tile that has moved to another column since the viewer opened is found at its new place, because the viewer looks the tile up when it closes.

Code

<Lightbox data={photos} loader={unsplash}>
  <Gallery data={photos} layout="masonry" min={140} loader={unsplash} />
</Lightbox>

Single image zoom

For click-to-zoom on one image, give Lightbox a single item and wrap the image in a trigger. Image has no zoom prop of its own: this is the same viewer with one item, so it has the same gestures, keys and accessibility. With one image there's no counter and no arrows.

Code

<Lightbox data={[photo]} loader={unsplash}>
  <Lightbox.Trigger>
    <Image src={photo.src} alt={photo.alt} width={320} ratio="3/2" loader={unsplash} />
  </Lightbox.Trigger>
</Lightbox>

Zoom and pan

The image has three zoom levels: fit, 2.5× and maxZoom (4× by default), each relative to the fitted size. Pinching and ⌘/Ctrl + wheel zoom smoothly anywhere between fit and maxZoom. Set zoom={false} to turn zoom off.

ToPointer or touchKeyboard
Zoom in at a pointDouble-click or double-tap; pinch; ⌘/Ctrl + wheel (a trackpad pinch)+, or Z for 2.5×
Zoom outDouble-click or double-tap again; pinch in−; 0 back to fit
Pan a zoomed imageDrag; wheel or trackpad scrollArrow keys
Zoom with one pointerThe Zoom in and Zoom out buttons

A plain wheel does nothing at fit, so a scroll doesn't zoom by accident. Once zoomed, it pans. When you drag past an edge, the image follows less and less (a rubber band), and when you let go it springs back inside. A flick carries on a little before it stops.

To move on from a zoomed image, pan it to its edge, let go, and drag past the edge again: the next image slides in, and the drag navigates as it would at fit. A pan that only just reached the edge stops there, so a long pan never flips to the next image by accident. The image you left goes back to fit once it's out of sight.

Drag to dismiss

At fit, drag the image up or down and the backdrop fades with it. Let go once it's travelled about an eighth of the screen height, counting where its speed would carry it (so a short, quick flick is enough), and the viewer closes from where the image is: it continues into the closing animation without jumping back first. Let go short of that and it springs back. The close button, Esc and a click or tap beside the image also close it.

Dragging sideways moves to the next or previous image. A quick flick is enough; a slow drag has to cross half the screen. On a right-to-left page the directions are reversed.

Thumbnails and captions

withThumbnails adds a strip of every image along the bottom. The current one stays centred, and clicking one jumps to it. An item's caption shows under the image.

Lake Louise, Alberta
Multnomah Falls, Oregon
Black Forest, Germany
Hoh rainforest, Washington
Valley of Fire, Nevada
Fairy Glen, Isle of Skye
Dolomites, Italy
Provence, France

Code

<Lightbox data={photosWithCaptions} loader={unsplash} withThumbnails>
  <Gallery data={photosWithCaptions} layout="justified" rowHeight={120} loader={unsplash} />
</Lightbox>

On a touch screen, a tap on the image hides the controls, and another shows them again. They're never hidden while keyboard focus is in them.

Download

withDownload adds a button that saves the current image. It fetches the file and saves it through DownloadButton, so a cross-origin image downloads as long as its server allows CORS. While the image is fetched the button is busy (a spinner, aria-busy, re-clicks ignored), and a failed fetch is announced instead of saving an error page. By default it saves src, named after its last path segment. Use an item's download to save something else, such as the original instead of the CDN rendition, with a file name of your choice.

Code

const data = photos.map((photo) => ({
  ...photo,
  download: { src: photo.original, name: `${photo.id}.jpg` },
}));

<Lightbox data={data} withDownload />

Right-to-left

The viewer takes its direction from the locale. Under IntlProvider locale="ar", ← goes to the next image, a swipe to the right goes forward, the arrow buttons and their icons swap sides, and the thumbnail strip starts on the right. Every string in this demo is translated, and numbers use the locale's digits.

Code

<IntlProvider locale="ar-EG">
  <div dir="rtl" lang="ar">
    <Lightbox data={photos} withThumbnails translations={arabic}>
      <Gallery data={photos} layout="justified" />
    </Lightbox>
  </div>
</IntlProvider>

Composable parts

<Lightbox> is a ready-made arrangement of parts. Build your own with Lightbox.Root (state and the open-index seam), Lightbox.Content (the full-screen dialog and its backdrop), Lightbox.Viewport (the gestures and the slides), and the controls you want inside Lightbox.Controls groups, which fade with the backdrop and hide on a tap. Lightbox.Context gives a render function the state and the commands.

An item with content shows that instead of the image: a video, a map, an embed. Custom media fades in and out instead of growing from the thumbnail, doesn't zoom, and keeps its own pointer events, so a video's controls work. The fourth photo below opens a video.

Code

<Lightbox.Root data={[...photos, { src: poster, alt: 'A flower opening', content: <video src={clip} controls /> }]}>
  <Gallery data={thumbnails} />
  <Lightbox.Content>
    <Lightbox.Viewport />
    <Lightbox.Controls className="absolute inset-x-0 bottom-0 flex justify-center gap-2 p-4">
      <Lightbox.Prev />
      <Lightbox.Context>
        {({ index, count, zoom }) => `${index + 1} of ${count} · ${Math.round(zoom * 100)}%`}
      </Lightbox.Context>
      <Lightbox.Next />
      <Lightbox.ZoomOut />
      <Lightbox.ZoomIn />
      <Lightbox.CloseTrigger />
    </Lightbox.Controls>
  </Lightbox.Content>
</Lightbox.Root>

Lightbox.Viewport renders each slide through its child function, (index) => <Lightbox.Slide index={index} /> by default. Return a Lightbox.Slide with children to show custom media at an index without putting it in data.

Custom icons and parts

Every piece can be replaced:

  • Icons through icons, a map of prev, next, zoomIn, zoomOut, download, close and fallback, on Lightbox.Root or the ready-made Lightbox. A button's children replace its icon outright. fallback shows in place of an image that failed to load; null leaves the stage empty. The kit's own chevrons mirror on a right-to-left page; yours are drawn as given, so add rtl:-scale-x-100 to an arrow. Add className={iconStroke} (from @42/ui-react) for the kit's 1.5px line.
  • Thumbnails through Lightbox.Thumbnails' child function, (index) => ReactNode. Return a Lightbox.Thumbnail with your own children: it keeps the label, aria-current, the click and the centring. Style the current one with data-current: or aria-current:.
  • The counter through Lightbox.Counter's function child, which gets the position and the count already formatted for the locale. translations.counter changes it everywhere instead.
  • Buttons, one by one, in the ready-made form through classNames: control styles every button, and prev, next, zoomIn, zoomOut, download and close style one each.

Code

<Lightbox.Root
  data={photos}
  icons={{
    prev: <ArrowLeft className={cn(iconStroke, "rtl:-scale-x-100")} />,
    next: <ArrowRight className={cn(iconStroke, "rtl:-scale-x-100")} />,
    zoomIn: <Plus className={iconStroke} />,
    zoomOut: <Minus className={iconStroke} />,
    download: <ArrowDownToLine className={iconStroke} />,
    close: <Minimize2 className={iconStroke} />,
  }}
>
  <Gallery data={photos} />
  <Lightbox.Content data-thumbnails>
    <Lightbox.Viewport />
    <Lightbox.Controls className="absolute inset-x-0 top-0 flex items-center gap-1 p-3">
      <Lightbox.Counter>{({ position, count }) => `Photo ${position} of ${count}`}</Lightbox.Counter>
      <div className="ms-auto flex gap-1">
        <Lightbox.ZoomOut />
        <Lightbox.ZoomIn />
        <Lightbox.Download />
        <Lightbox.CloseTrigger />
      </div>
    </Lightbox.Controls>
    <Lightbox.Controls className="absolute inset-x-0 top-1/2 flex -translate-y-1/2 justify-between p-3">
      <Lightbox.Prev />
      <Lightbox.Next />
    </Lightbox.Controls>
    <Lightbox.Controls className="absolute inset-x-0 bottom-0 flex justify-center p-3">
      <Lightbox.Thumbnails className="gap-2">
        {(index) => (
          <Lightbox.Thumbnail index={index} className="rounded-full aria-current:ring-brand-400">
            <Image src={photos[index].src} alt="" ratio={1} radius="full" className="block size-full" />
          </Lightbox.Thumbnail>
        )}
      </Lightbox.Thumbnails>
    </Lightbox.Controls>
  </Lightbox.Content>
</Lightbox.Root>

data-thumbnails on Lightbox.Content leaves room for the strip under the image, as the ready-made form does with withThumbnails.

Motion

Every animation uses the kit's motion tokens, and plays as a Web Animation or a CSS animation, so it runs off the main thread where the browser can.

  • Opening and closing take --duration-slow (300ms) on --ease-emphasized. The image grows from the thumbnail's own rectangle to its fitted size, using transforms only. It sits in a clipping frame that changes shape, from the thumbnail's crop to the image's own proportions, while the image inside is scaled the other way, so the picture is never stretched in any frame. The thumbnail's rounded corners straighten on the way. When the two shapes already match, it's a plain move and scale. With no thumbnail on screen (it was scrolled away, or there wasn't one) the image fades in from 96% scale instead. The backdrop and the controls fade over the same 300ms, on --ease-standard.
  • Gestures follow the pointer exactly, with no lag. Dragging down to dismiss moves the image at 60% of the pointer's speed.
  • Releases spring. Navigation and a dismiss that doesn't close settle with the kit's settle spring, a pan that ran past an edge comes back with the overshoot spring, and each spring starts at the speed your finger was moving.
  • Navigation slides the next image in. Slides are placed with inset-inline-start, so a right-to-left page mirrors them with no extra code, and they're never reordered in the DOM.
  • Reduced motion. With prefers-reduced-motion: reduce, opening, closing, navigation and every release happen at once. Gestures still follow your finger: they're direct manipulation, not animation.

Shared-element transitions between pages

The lightbox animates within one page. To grow a thumbnail into a detail page when the route changes, use React's <ViewTransition> instead: give the thumbnail and the detail image the same name, and the browser morphs one into the other. Your router has to run navigations as view transitions (in Next.js, experimental.viewTransition).

import { ViewTransition } from 'react';

// The list page
<Link href={`/photos/${photo.id}`}>
  <ViewTransition name={`photo-${photo.id}`} share="photo">
    <Image src={photo.src} alt={photo.alt} ratio={1} />
  </ViewTransition>
</Link>

// The detail page
<ViewTransition name={`photo-${photo.id}`} share="photo">
  <Image src={photo.src} alt={photo.alt} width={photo.width} height={photo.height} priority />
</ViewTransition>
::view-transition-group(.photo) {
  animation-duration: var(--duration-slow);
  animation-timing-function: var(--ease-emphasized);
}
@media (prefers-reduced-motion: reduce) {
  ::view-transition-group(.photo) {
    animation: none;
  }
}

The lightbox doesn't use view transitions itself: a view transition animates a snapshot, and a snapshot can't be dragged, pinched or interrupted halfway.

API

Prop

Type

Lightbox.Root takes everything from data to onExitComplete, icons, and children.

LightboxItem

Prop

Type

Parts

PartRendersNotes
Lightbox.RootNothing of its ownState, the Ark dialog and the open-index seam.
Lightbox.Trigger<button>index (0 by default). Takes asChild. It's also where the morph and focus return for that index.
Lightbox.ContentThe portaled, full-screen dialogWith its backdrop and live region. container, classNames.positioner and classNames.backdrop.
Lightbox.ViewportThe stageTakes the gestures and the wheel. Its child function (index) => ReactNode renders each slide.
Lightbox.SlideOne slideindex; children replace the image with custom media.
Lightbox.Controls<div>A group of controls: fades with the backdrop, hides on a tap, lets clicks through its empty space.
Lightbox.Counter<div aria-hidden>"3 / 12". Children replace it; a function child gets { position, count }, locale-formatted.
Lightbox.Caption<div>The current item's caption, or your children. Nothing when there's neither.
Lightbox.ThumbnailsA group of buttonsOne per image. Its child function (index) => ReactNode renders each; classNames.thumbnail styles the default ones.
Lightbox.Thumbnail<button>index. aria-current and data-current on the image showing. Children replace the thumbnail image.
Lightbox.Prev, Next, ZoomIn, ZoomOut, Download, CloseTrigger<button>44px round buttons. Children replace icons.prev, icons.next, icons.zoomIn, icons.zoomOut, icons.download, icons.close.
Lightbox.ContextYour render function{ phase, open, index, count, zoom, next, prev, goto, zoomIn, zoomOut, reset, close }.

Only Lightbox.Trigger takes asChild.

Accessibility

  • A modal dialog, following the APG pattern: role="dialog" with aria-modal="true", named by translations.label. Focus moves into it when it opens and stays inside until it closes. The page behind is hidden from assistive technology and doesn't scroll. Esc and a visible close button close it.
  • Focus goes back to the image you end on. Opened from photo 2 and closed on photo 5, focus lands on photo 5's tile, which is also where the image shrinks back to. If that image has no tile, focus goes back to whatever opened the viewer.
  • Announcements. A polite live region says "Image 3 of 12" when the image changes and "Zoom 250%" when the zoom does. The visible counter is hidden from screen readers, so nothing is read twice. Each slide is a group named "Image N of M", and the image keeps its alt. The slides on either side are inert.
  • Every gesture has a single-pointer and a keyboard equivalent (WCAG 2.5.1 and 2.5.7): the Previous, Next, Zoom in and Zoom out buttons, and these keys:
KeyDoes
→ / ←Next / previous image, in reading order (swapped on a right-to-left page). Pans when zoomed.
↑ / ↓Pans when zoomed.
+ / −Zooms in / out a level.
0Back to fit.
ZToggles fit and 2.5×.
EscCloses.
TabMoves through the controls.
  • Large controls. Every button is 44px, above the WCAG 2.5.8 minimum. One that has run out (Zoom in at the deepest zoom, Previous on the first image without loop) is aria-disabled, not disabled, so it keeps focus.
  • Controls stay for keyboard users. A tap hides them for touch users, but never while keyboard focus is in them, and focusing one shows them all again.
  • Reduced motion. Everything that animates on its own happens at once; see Motion.
  • Page zoom. The viewer never disables the browser's pinch-zoom of the page.

Internationalization

Every string the viewer shows or announces is in translations. Alt text and captions are your content: translate them with the rest of the page. Numbers arrive already formatted with Intl.NumberFormat for the locale from IntlProvider, digits and percent sign included.

KeyDefault
label"Image viewer"
closeLabel"Close"
prevLabel"Previous image"
nextLabel"Next image"
zoomInLabel"Zoom in"
zoomOutLabel"Zoom out"
downloadLabel"Download"
downloadError(name) => `${name} couldn't be downloaded`
thumbnailsLabel"Thumbnails"
slideLabel(position, count) => `Image ${position} of ${count}`
counter(position, count) => `${position} / ${count}`
zoomLevel(percent) => `Zoom ${percent}`
<Lightbox
  data={photos}
  translations={{
    label: t('viewer.label'),
    slideLabel: (position, count) => t('viewer.slide', { position, count }),
    zoomLevel: (percent) => t('viewer.zoom', { percent }),
  }}
/>

Testing

testId lands on the dialog content, and each item's testId on its slide. Most of the viewer is easier to reach by role:

await user.click(screen.getByRole('button', { name: 'A mountain lake at dawn' })); // a Gallery tile
const viewer = screen.getByRole('dialog', { name: 'Image viewer' });
await user.click(within(viewer).getByRole('button', { name: 'Next image' }));
expect(within(viewer).getByRole('group', { name: 'Image 2 of 12' })).toBeVisible();

The viewer's motion runs on the Web Animations API, which jsdom doesn't have. Stub Element.prototype.animate with an animation that finishes when you tell it to, as the kit's own test setup does. Let a frame pass before expecting the dialog to be gone: Ark unmounts it after the exit animation, in a requestAnimationFrame.

Changelog

v0.29.0
  • No computed-style read on mount in production: the RTL direction check runs in development only

    #464
v0.20.0
  • New Lightbox viewer that grows out of the clicked thumbnail and shrinks back into the tile you end on: swipe, drag down to dismiss, pinch, double-tap or ⌘-scroll to zoom, ← → mirrored in RTL; use <Lightbox data> or compose Trigger, Thumbnails, Caption, Download and more, with an icons map

    #354

On this page