Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(core): add XDSLightbox component (#2298)

Andrey Goder8c6a2b2b1bb1
diff --git a/apps/storybook/stories/Lightbox.stories.tsx b/apps/storybook/stories/Lightbox.stories.tsx
new file mode 100644
index 0000000000..fee3bb7dad
--- /dev/null
+++ b/apps/storybook/stories/Lightbox.stories.tsx
@@ -0,0 +1,175 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {XDSLightbox, useXDSLightbox} from '@xds/core/Lightbox';
+
+const meta: Meta<typeof XDSLightbox> = {
+ title: 'Core/Lightbox',
+ component: XDSLightbox,
+ tags: ['autodocs'],
+};
+
+export default meta;
+type Story = StoryObj<typeof XDSLightbox>;
+
+const SAMPLE_IMAGE = 'https://picsum.photos/id/10/1200/800';
+const GALLERY_MEDIA = [
+ {
+ src: 'https://picsum.photos/id/10/1200/800',
+ alt: 'Forest path',
+ caption: 'A winding path through the forest',
+ },
+ {src: 'https://picsum.photos/id/15/1200/800', alt: 'Mountain lake'},
+ {
+ src: 'https://picsum.photos/id/20/1200/800',
+ alt: 'Beach sunset',
+ caption: 'Golden hour at the beach',
+ },
+ {src: 'https://picsum.photos/id/25/1200/800', alt: 'City skyline'},
+];
+
+export const Default: Story = {
+ render: () => {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button onClick={() => setIsOpen(true)}>Open lightbox</button>
+ <XDSLightbox
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ media={{
+ src: SAMPLE_IMAGE,
+ alt: 'Forest path',
+ caption: 'A winding path through the forest',
+ }}
+ />
+ </>
+ );
+ },
+};
+
+export const Gallery: Story = {
+ render: () => {
+ const [isOpen, setIsOpen] = useState(false);
+ const [index, setIndex] = useState(0);
+ return (
+ <>
+ <div style={{display: 'flex', gap: '8px'}}>
+ {GALLERY_MEDIA.map((item, i) => (
+ <img
+ key={item.src}
+ src={item.src}
+ alt={item.alt}
+ style={{
+ width: 120,
+ height: 80,
+ objectFit: 'cover',
+ cursor: 'pointer',
+ borderRadius: 4,
+ }}
+ onClick={() => {
+ setIndex(i);
+ setIsOpen(true);
+ }}
+ />
+ ))}
+ </div>
+ <XDSLightbox
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ media={GALLERY_MEDIA}
+ index={index}
+ onIndexChange={setIndex}
+ />
+ </>
+ );
+ },
+};
+
+export const WithZoom: Story = {
+ render: () => {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button onClick={() => setIsOpen(true)}>Open with zoom</button>
+ <XDSLightbox
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ media={{src: SAMPLE_IMAGE, alt: 'Forest path'}}
+ hasZoom
+ />
+ </>
+ );
+ },
+};
+
+export const WithCaption: Story = {
+ render: () => {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button onClick={() => setIsOpen(true)}>Open with caption</button>
+ <XDSLightbox
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ media={{
+ src: SAMPLE_IMAGE,
+ alt: 'Forest path',
+ caption:
+ 'A beautiful forest path winding through tall trees on a misty morning',
+ }}
+ />
+ </>
+ );
+ },
+};
+
+export const Video: Story = {
+ render: () => {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button onClick={() => setIsOpen(true)}>Open video</button>
+ <XDSLightbox
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ media={{
+ src: 'https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm',
+ alt: 'Flower blooming',
+ type: 'video',
+ caption: 'A flower blooming in time-lapse',
+ }}
+ />
+ </>
+ );
+ },
+};
+
+export const WithHook: Story = {
+ render: () => {
+ const lightbox = useXDSLightbox({media: GALLERY_MEDIA});
+ return (
+ <>
+ <div style={{display: 'flex', gap: '8px'}}>
+ {GALLERY_MEDIA.map((item, i) => (
+ <img
+ key={item.src}
+ src={item.src}
+ alt={item.alt}
+ style={{
+ width: 120,
+ height: 80,
+ objectFit: 'cover',
+ cursor: 'pointer',
+ borderRadius: 4,
+ }}
+ {...lightbox.getTriggerProps(i)}
+ />
+ ))}
+ </div>
+ {lightbox.element}
+ </>
+ );
+ },
+};
diff --git a/internal/vibe-tests/test-sets/default.json b/internal/vibe-tests/test-sets/default.json
index fbe7638f78..47e0c89b02 100644
--- a/internal/vibe-tests/test-sets/default.json
+++ b/internal/vibe-tests/test-sets/default.json
@@ -927,6 +927,45 @@
"Add a tooltip on the status dot showing the uptime percentage",
"Add a \"Refresh\" button that rechecks all service statuses"
]
+ },
+ {
+ "id": "fwc-12",
+ "category": "feature-with-constraint",
+ "prompt": "Build an image thumbnail grid. When a user clicks a thumbnail, open a fullscreen lightbox showing the image with a caption and a close button.",
+ "expectedComponents": [
+ "XDSLightbox"
+ ],
+ "complexity": "simple",
+ "followUps": [
+ "Add zoom support so users can double-click to zoom in on details",
+ "Add a download button that saves the full-resolution image"
+ ]
+ },
+ {
+ "id": "fwc-13",
+ "category": "feature-with-constraint",
+ "prompt": "Create a photo gallery for a product page. Show 4 product images as thumbnails. Clicking any thumbnail opens a lightbox gallery where users can navigate between all images with prev/next arrows and keyboard. Show a counter like '2 of 4'.",
+ "expectedComponents": [
+ "XDSLightbox"
+ ],
+ "complexity": "moderate",
+ "followUps": [
+ "Highlight the currently-viewed thumbnail while the lightbox is open",
+ "Add captions to each image that display below the photo in the lightbox"
+ ]
+ },
+ {
+ "id": "fwc-14",
+ "category": "feature-with-constraint",
+ "prompt": "Build a media gallery that mixes images and videos. Clicking any item opens a lightbox viewer. Videos should show native playback controls. Images should support zoom on double-click.",
+ "expectedComponents": [
+ "XDSLightbox"
+ ],
+ "complexity": "moderate",
+ "followUps": [
+ "Add autoplay for videos when they become the active item in the gallery",
+ "Add a filmstrip thumbnail bar at the bottom of the lightbox for quick navigation"
+ ]
}
],
"holdout": [
diff --git a/packages/cli/templates/blocks/components/Lightbox/LightboxShowcase.doc.mjs b/packages/cli/templates/blocks/components/Lightbox/LightboxShowcase.doc.mjs
new file mode 100644
index 0000000000..ca9271c0e4
--- /dev/null
+++ b/packages/cli/templates/blocks/components/Lightbox/LightboxShowcase.doc.mjs
@@ -0,0 +1,14 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../../../../../core/src/docs-types').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ exampleFor: 'Lightbox',
+ name: 'Lightbox',
+ isReady: true,
+ aspectRatio: 1,
+ isShowcase: true,
+ description:
+ 'A fullscreen image viewer with caption.',
+ componentsUsed: ['Lightbox'],
+};
diff --git a/packages/cli/templates/blocks/components/Lightbox/LightboxShowcase.tsx b/packages/cli/templates/blocks/components/Lightbox/LightboxShowcase.tsx
new file mode 100644
index 0000000000..536df64a59
--- /dev/null
+++ b/packages/cli/templates/blocks/components/Lightbox/LightboxShowcase.tsx
@@ -0,0 +1,22 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useState} from 'react';
+import {XDSLightbox} from '@xds/core/Lightbox';
+
+export default function LightboxShowcase() {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button onClick={() => setIsOpen(true)}>View image</button>
+ <XDSLightbox
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ media={{
+ src: 'https://picsum.photos/id/10/1200/800',
+ alt: 'Forest path',
+ caption: 'A winding path through the forest',
+ }}
+ />
+ </>
+ );
+}
diff --git a/packages/core/package.json b/packages/core/package.json
index 9cc7ec18e4..a14387139b 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -325,6 +325,12 @@
"import": "./dist/Layout/index.mjs",
"require": "./dist/Layout/index.js"
},
+ "./Lightbox": {
+ "source": "./src/Lightbox/index.ts",
+ "types": "./dist/Lightbox/index.d.ts",
+ "import": "./dist/Lightbox/index.mjs",
+ "require": "./dist/Lightbox/index.js"
+ },
"./Link": {
"source": "./src/Link/index.ts",
"types": "./dist/Link/index.d.ts",
diff --git a/packages/core/src/Lightbox/Lightbox.doc.mjs b/packages/core/src/Lightbox/Lightbox.doc.mjs
new file mode 100644
index 0000000000..a5df634022
--- /dev/null
+++ b/packages/core/src/Lightbox/Lightbox.doc.mjs
@@ -0,0 +1,152 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** @type {import('../docs-types').ComponentDoc} */
+
+export const docs = {
+ name: 'Lightbox',
+ keywords: ["lightbox","image","video","viewer","gallery","zoom","fullscreen","media","photo","preview"],
+ props: [
+ {
+ name: 'isOpen',
+ type: 'boolean',
+ description: 'Whether the lightbox is open.',
+ required: true,
+ },
+ {
+ name: 'onOpenChange',
+ type: '(isOpen: boolean) => void',
+ description: 'Callback when the lightbox open state changes.',
+ required: true,
+ },
+ {
+ name: 'media',
+ type: 'XDSLightboxMedia | XDSLightboxMedia[]',
+ description: 'Media to display. Pass a single object for one item, or an array for gallery mode with prev/next navigation. Each item has src, alt, optional caption and type.',
+ required: true,
+ },
+ {
+ name: 'index',
+ type: 'number',
+ description: 'Current index in gallery mode (when media is an array).',
+ default: '0',
+ },
+ {
+ name: 'onIndexChange',
+ type: '(index: number) => void',
+ description: 'Callback when the gallery index changes via prev/next navigation.',
+ },
+ {
+ name: 'hasZoom',
+ type: 'boolean',
+ description: 'Enable zoom on double-click (images only). When zoomed, drag to pan.',
+ default: 'false',
+ },
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description: 'StyleX styles for layout customization. Must be stylex.create() value.',
+ },
+ ],
+ theming: {
+ targets: [
+ {className: 'xds-lightbox', visualProps: []},
+ ],
+ },
+ usage: {
+ description:
+ 'A fullscreen overlay for viewing images and videos at full resolution. Supports single-item and gallery modes with prev/next navigation, optional zoom and pan for images, and native video controls.',
+ bestPractices: [
+ { guidance: true, description: 'Always provide alt text for every image for screen reader accessibility.' },
+ { guidance: true, description: 'Use gallery mode with onIndexChange for multi-image sets.' },
+ { guidance: true, description: 'Enable hasZoom only when viewing high-resolution images that benefit from close inspection.' },
+ { guidance: false, description: 'Use the lightbox for non-image content — it is specialized for images.' },
+ { guidance: false, description: 'Nest interactive content inside captions — keep them plain text.' },
+ ],
+ },
+};
+
+/** @type {import('../docs-types').ComponentDoc} */
+export const docsZh = {
+ name: 'Lightbox',
+ props: [
+ {
+ name: 'isOpen',
+ type: 'boolean',
+ description: '灯箱是否打开。',
+ required: true,
+ },
+ {
+ name: 'onOpenChange',
+ type: '(isOpen: boolean) => void',
+ description: '灯箱打开状态变化时的回调。',
+ required: true,
+ },
+ {
+ name: 'media',
+ type: 'XDSLightboxMedia | XDSLightboxMedia[]',
+ description: '要显示的媒体。传入单个对象或数组(用于画廊模式的上一张/下一张导航)。',
+ required: true,
+ },
+ {
+ name: 'index',
+ type: 'number',
+ description: '画廊模式中当前索引。',
+ default: '0',
+ },
+ {
+ name: 'onIndexChange',
+ type: '(index: number) => void',
+ description: '通过上一张/下一张导航更改画廊索引时的回调。',
+ },
+ {
+ name: 'hasZoom',
+ type: 'boolean',
+ description: '启用双击缩放(仅图片)。缩放后可拖动平移。',
+ default: 'false',
+ },
+ {
+ name: 'xstyle',
+ type: 'StyleXStyles',
+ description: '用于布局自定义的 StyleX 样式。必须是 stylex.create() 的值。',
+ },
+ ],
+ theming: {
+ targets: [
+ {className: 'xds-lightbox', visualProps: []},
+ ],
+ },
+ usage: {
+ description:
+ 'A fullscreen overlay for viewing images and videos at full resolution. Supports single-item and gallery modes with prev/next navigation, optional zoom and pan for images, and native video controls.',
+ bestPractices: [
+ { guidance: true, description: 'Always provide alt text for every image for screen reader accessibility.' },
+ { guidance: true, description: 'Use gallery mode with onIndexChange for multi-image sets.' },
+ { guidance: true, description: 'Enable hasZoom only when viewing high-resolution images that benefit from close inspection.' },
+ { guidance: false, description: 'Use the lightbox for non-image content — it is specialized for images.' },
+ { guidance: false, description: 'Nest interactive content inside captions — keep them plain text.' },
+ ],
+ },
+};
+
+/** @type {import('../docs-types').TranslationDoc} */
+export const docsDense = {
+ description: 'Fullscreen overlay for viewing images and videos at full resolution with gallery navigation and zoom.',
+ usage: {
+ description:
+ 'A fullscreen overlay for viewing images and videos at full resolution. Supports single-item and gallery modes with prev/next navigation, optional zoom and pan for images, and native video controls.',
+ bestPractices: [
+ { guidance: true, description: 'Always provide alt text for every image.' },
+ { guidance: true, description: 'Use gallery mode with onIndexChange for multi-image sets.' },
+ { guidance: false, description: 'Use for non-image content — specialized for images.' },
+ ],
+ },
+ propDescriptions: {
+ isOpen: 'Whether the lightbox is open.',
+ onOpenChange: 'Callback when open state changes.',
+ media: 'Single media object or array for gallery mode.',
+ index: 'Current index in gallery mode.',
+ onIndexChange: 'Callback when gallery index changes.',
+ hasZoom: 'Enable double-click zoom and drag pan (images only).',
+ xstyle: 'StyleX styles for layout customization.',
+ },
+};
diff --git a/packages/core/src/Lightbox/XDSLightbox.test.tsx b/packages/core/src/Lightbox/XDSLightbox.test.tsx
new file mode 100644
index 0000000000..fe96ba91a0
--- /dev/null
+++ b/packages/core/src/Lightbox/XDSLightbox.test.tsx
@@ -0,0 +1,270 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, it, expect, vi, beforeEach} from 'vitest';
+import {render, screen, fireEvent} from '@testing-library/react';
+import {XDSLightbox} from './XDSLightbox';
+
+// Mock showModal/close for jsdom
+beforeEach(() => {
+ HTMLDialogElement.prototype.showModal = vi.fn(function (
+ this: HTMLDialogElement,
+ ) {
+ this.setAttribute('open', '');
+ });
+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {
+ this.removeAttribute('open');
+ });
+});
+
+describe('XDSLightbox', () => {
+ it('renders as a dialog element', () => {
+ render(
+ <XDSLightbox
+ isOpen={false}
+ onOpenChange={() => {}}
+ media={{src: '/photo.jpg', alt: 'Photo'}}
+ />,
+ );
+ const dialog = document.querySelector('dialog');
+ expect(dialog).toBeInTheDocument();
+ });
+
+ it('calls showModal when isOpen becomes true', () => {
+ render(
+ <XDSLightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={{src: '/photo.jpg', alt: 'Photo'}}
+ />,
+ );
+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenCalled();
+ });
+
+ it('renders the image with correct src and alt', () => {
+ render(
+ <XDSLightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={{src: '/photo.jpg', alt: 'A beautiful photo'}}
+ />,
+ );
+ const img = screen.getByAltText('A beautiful photo');
+ expect(img).toBeInTheDocument();
+ expect(img).toHaveAttribute('src', '/photo.jpg');
+ });
+
+ it('renders caption when provided', () => {
+ render(
+ <XDSLightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={{
+ src: '/photo.jpg',
+ alt: 'Photo',
+ caption: 'Sunset over the ocean',
+ }}
+ />,
+ );
+ expect(screen.getByText('Sunset over the ocean')).toBeInTheDocument();
+ });
+
+ it('does not render caption when not provided', () => {
+ const {container} = render(
+ <XDSLightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={{src: '/photo.jpg', alt: 'Photo'}}
+ />,
+ );
+ expect(container.querySelectorAll('[class*="caption"]').length).toBe(0);
+ });
+
+ it('calls onOpenChange(false) when close button is clicked', () => {
+ const onOpenChange = vi.fn();
+ render(
+ <XDSLightbox
+ isOpen={true}
+ onOpenChange={onOpenChange}
+ media={{src: '/photo.jpg', alt: 'Photo'}}
+ />,
+ );
+ const closeButton = screen.getByLabelText('Close');
+ fireEvent.click(closeButton);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it('calls onOpenChange(false) on Escape via cancel event', () => {
+ const onOpenChange = vi.fn();
+ render(
+ <XDSLightbox
+ isOpen={true}
+ onOpenChange={onOpenChange}
+ media={{src: '/photo.jpg', alt: 'Photo'}}
+ />,
+ );
+ const dialog = document.querySelector('dialog')!;
+ const cancelEvent = new Event('cancel', {cancelable: true});
+ dialog.dispatchEvent(cancelEvent);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it('sets aria-label on the dialog', () => {
+ render(
+ <XDSLightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={{src: '/photo.jpg', alt: 'Beach sunset'}}
+ />,
+ );
+ const dialog = document.querySelector('dialog');
+ expect(dialog).toHaveAttribute('aria-label', 'Beach sunset');
+ });
+
+ it('forwards ref to dialog element', () => {
+ const ref = {current: null as HTMLDialogElement | null};
+ render(
+ <XDSLightbox
+ ref={ref}
+ isOpen={false}
+ onOpenChange={() => {}}
+ media={{src: '/photo.jpg', alt: 'Photo'}}
+ />,
+ );
+ expect(ref.current).toBeInstanceOf(HTMLDialogElement);
+ });
+
+ describe('gallery mode', () => {
+ const media = [
+ {src: '/a.jpg', alt: 'Image A', caption: 'First'},
+ {src: '/b.jpg', alt: 'Image B', caption: 'Second'},
+ {src: '/c.jpg', alt: 'Image C'},
+ ];
+
+ it('renders the image at the given index', () => {
+ render(
+ <XDSLightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={media}
+ index={1}
+ />,
+ );
+ expect(screen.getByAltText('Image B')).toBeInTheDocument();
+ });
+
+ it('shows gallery counter', () => {
+ render(
+ <XDSLightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={media}
+ index={0}
+ />,
+ );
+ expect(screen.getByText('1 / 3')).toBeInTheDocument();
+ });
+
+ it('shows prev/next buttons for middle item', () => {
+ render(
+ <XDSLightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={media}
+ index={1}
+ />,
+ );
+ expect(screen.getByLabelText('Previous image')).toBeInTheDocument();
+ expect(screen.getByLabelText('Next image')).toBeInTheDocument();
+ });
+
+ it('hides prev button on first item', () => {
+ render(
+ <XDSLightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={media}
+ index={0}
+ />,
+ );
+ expect(screen.queryByLabelText('Previous image')).not.toBeInTheDocument();
+ expect(screen.getByLabelText('Next image')).toBeInTheDocument();
+ });
+
+ it('hides next button on last item', () => {
+ render(
+ <XDSLightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={media}
+ index={2}
+ />,
+ );
+ expect(screen.getByLabelText('Previous image')).toBeInTheDocument();
+ expect(screen.queryByLabelText('Next image')).not.toBeInTheDocument();
+ });
+
+ it('calls onIndexChange when next is clicked', () => {
+ const onIndexChange = vi.fn();
+ render(
+ <XDSLightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={media}
+ index={0}
+ onIndexChange={onIndexChange}
+ />,
+ );
+ fireEvent.click(screen.getByLabelText('Next image'));
+ expect(onIndexChange).toHaveBeenCalledWith(1);
+ });
+
+ it('calls onIndexChange when prev is clicked', () => {
+ const onIndexChange = vi.fn();
+ render(
+ <XDSLightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={media}
+ index={2}
+ onIndexChange={onIndexChange}
+ />,
+ );
+ fireEvent.click(screen.getByLabelText('Previous image'));
+ expect(onIndexChange).toHaveBeenCalledWith(1);
+ });
+
+ it('navigates via arrow keys', () => {
+ const onIndexChange = vi.fn();
+ render(
+ <XDSLightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={media}
+ index={1}
+ onIndexChange={onIndexChange}
+ />,
+ );
+ const dialog = document.querySelector('dialog')!;
+ fireEvent.keyDown(dialog, {key: 'ArrowRight'});
+ expect(onIndexChange).toHaveBeenCalledWith(2);
+ fireEvent.keyDown(dialog, {key: 'ArrowLeft'});
+ expect(onIndexChange).toHaveBeenCalledWith(0);
+ });
+ });
+
+ describe('video support', () => {
+ it('renders a video element when type is video', () => {
+ const {container} = render(
+ <XDSLightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={{src: '/clip.mp4', alt: 'A clip', type: 'video'}}
+ />,
+ );
+ const video = container.querySelector('video');
+ expect(video).toBeInTheDocument();
+ expect(video).toHaveAttribute('src', '/clip.mp4');
+ expect(video).toHaveAttribute('controls');
+ });
+ });
+});
diff --git a/packages/core/src/Lightbox/XDSLightbox.tsx b/packages/core/src/Lightbox/XDSLightbox.tsx
new file mode 100644
index 0000000000..9785e8510a
--- /dev/null
+++ b/packages/core/src/Lightbox/XDSLightbox.tsx
@@ -0,0 +1,570 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file XDSLightbox.tsx
+ * @input Uses React, native dialog, StyleX, XDSIconButton, theme tokens
+ * @output Exports XDSLightbox component, XDSLightboxProps, XDSLightboxMedia
+ * @position Core implementation; consumed by index.ts
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Lightbox/Lightbox.doc.mjs (props table, features, implementation notes)
+ * - /packages/core/src/Lightbox/XDSLightbox.test.tsx (tests for new/changed behavior)
+ * - /packages/core/src/Lightbox/index.ts (exports if types change)
+ * - /apps/storybook/stories/Lightbox.stories.tsx (storybook stories)
+ * - /packages/cli/templates/blocks/components/Lightbox/ (showcase blocks)
+ */
+
+import {
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+ type MouseEvent as ReactMouseEvent,
+ type ReactNode,
+} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {colorVars, spacingVars, typeScaleVars} from '../theme/tokens.stylex';
+import {XDSIcon} from '../Icon';
+import {XDSIconButton} from '../IconButton';
+import {useScrollLock} from '../hooks/useScrollLock';
+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
+import {xdsClassName, mergeProps} from '../utils';
+import type {XDSBaseProps} from '../XDSBaseProps';
+
+/**
+ * Media type for lightbox items.
+ */
+export type XDSLightboxMediaType = 'image' | 'video';
+
+/**
+ * Describes a single media item in a lightbox.
+ */
+export interface XDSLightboxMedia {
+ /** Media source URL */
+ src: string;
+ /** Alt text for accessibility (used as aria-label for video) */
+ alt: string;
+ /** Optional caption displayed below the media */
+ caption?: ReactNode;
+ /**
+ * Media type. Zoom/pan is disabled for video.
+ * @default 'image'
+ */
+ type?: XDSLightboxMediaType;
+}
+
+export interface XDSLightboxProps extends XDSBaseProps<HTMLDialogElement> {
+ /** Ref forwarded to the root dialog element */
+ ref?: React.Ref<HTMLDialogElement>;
+ /**
+ * Whether the lightbox is open.
+ */
+ isOpen: boolean;
+ /**
+ * Callback when the lightbox open state changes.
+ * Called with `false` on Escape, backdrop click, or close button.
+ */
+ onOpenChange: (isOpen: boolean) => void;
+ /**
+ * Media to display. Pass a single object for one item, or an array
+ * for gallery mode with prev/next navigation.
+ */
+ media: XDSLightboxMedia | XDSLightboxMedia[];
+ /**
+ * Current index in gallery mode (when `media` is an array).
+ * When provided, puts the component in controlled mode.
+ */
+ index?: number;
+ /**
+ * Initial index in gallery mode for uncontrolled usage.
+ * @default 0
+ */
+ defaultIndex?: number;
+ /**
+ * Callback when the gallery index changes via prev/next navigation.
+ */
+ onIndexChange?: (index: number) => void;
+ /**
+ * Enable zoom on double-click (images only).
+ * When zoomed, drag to pan.
+ * @default false
+ */
+ hasZoom?: boolean;
+ /**
+ * Whether video should autoplay when the lightbox opens.
+ * @default false
+ */
+ hasAutoPlay?: boolean;
+}
+
+// =============================================================================
+// Styles
+// =============================================================================
+
+const styles = stylex.create({
+ dialog: {
+ position: 'fixed',
+ inset: 0,
+ width: '100vw',
+ height: '100vh',
+ maxWidth: 'none',
+ maxHeight: 'none',
+ margin: 0,
+ padding: 0,
+ border: 'none',
+ backgroundColor: 'transparent',
+ overflow: 'hidden',
+ outline: 'none',
+ '::backdrop': {
+ backgroundColor: colorVars['--color-overlay'],
+ backdropFilter: 'blur(2px)',
+ },
+ },
+ container: {
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: '100%',
+ height: '100%',
+ position: 'relative',
+ },
+ mediaGroup: {
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ maxWidth: '100%',
+ maxHeight: '100%',
+ overflow: 'hidden',
+ },
+ imageWrapper: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ overflow: 'hidden',
+ cursor: 'default',
+ userSelect: 'none',
+ minHeight: 0,
+ },
+ imageWrapperZoomable: {
+ cursor: {
+ default: 'zoom-in',
+ '@media (hover: hover)': 'zoom-in',
+ },
+ },
+ imageWrapperZoomed: {
+ cursor: 'grab',
+ },
+ imageWrapperDragging: {
+ cursor: 'grabbing',
+ },
+ image: {
+ maxWidth: '100%',
+ maxHeight: '100%',
+ objectFit: 'contain',
+ pointerEvents: 'none',
+ transitionProperty: 'transform',
+ transitionDuration: '200ms',
+ transitionTimingFunction: 'ease-out',
+ },
+ imageDragging: {
+ transitionProperty: 'none',
+ },
+ video: {
+ maxWidth: '100%',
+ maxHeight: '100%',
+ objectFit: 'contain',
+ outline: 'none',
+ },
+ caption: {
+ color: colorVars['--color-on-dark'],
+ fontSize: typeScaleVars['--text-large-size'],
+ lineHeight: typeScaleVars['--text-large-leading'],
+ textAlign: 'center',
+ paddingTop: spacingVars['--spacing-2'],
+ paddingBottom: 0,
+ paddingLeft: spacingVars['--spacing-3'],
+ paddingRight: spacingVars['--spacing-3'],
+ maxWidth: '600px',
+ flexShrink: 0,
+ },
+ closeButton: {
+ position: 'absolute',
+ top: spacingVars['--spacing-3'],
+ right: spacingVars['--spacing-3'],
+ zIndex: 1,
+ },
+ navButton: {
+ position: 'absolute',
+ top: '50%',
+ transform: 'translateY(-50%)',
+ zIndex: 1,
+ },
+ navPrev: {
+ left: spacingVars['--spacing-3'],
+ },
+ navNext: {
+ right: spacingVars['--spacing-3'],
+ },
+ counter: {
+ position: 'absolute',
+ top: spacingVars['--spacing-3'],
+ left: spacingVars['--spacing-3'],
+ color: colorVars['--color-on-dark'],
+ fontSize: typeScaleVars['--text-body-size'],
+ lineHeight: typeScaleVars['--text-body-leading'],
+ zIndex: 1,
+ },
+ controlButton: {
+ color: colorVars['--color-on-dark'],
+ },
+});
+
+const dynamicStyles = stylex.create({
+ imageTransform: (transform: string) => ({
+ transform,
+ }),
+});
+
+/**
+ * A fullscreen overlay for viewing images at full resolution.
+ *
+ * Supports single image and gallery modes. In gallery mode, provides
+ * prev/next navigation via buttons and arrow keys. Optionally supports
+ * zoom (double-click to toggle 2x) and pan (drag when zoomed).
+ *
+ * Uses the native `<dialog>` element with `showModal()` for focus
+ * trapping and top-layer placement. Dismiss via Escape, close button,
+ * or backdrop click.
+ *
+ * @example
+ * ```
+ * <XDSLightbox
+ * isOpen={isOpen}
+ * onOpenChange={setIsOpen}
+ * media={{src: "/photo.jpg", alt: "A photo"}}
+ * />
+ * <XDSLightbox
+ * isOpen={isOpen}
+ * onOpenChange={setIsOpen}
+ * media={photos}
+ * />
+ * <XDSLightbox
+ * isOpen={isOpen}
+ * onOpenChange={setIsOpen}
+ * media={photos}
+ * index={currentIndex}
+ * onIndexChange={setCurrentIndex}
+ * />
+ * ```
+ */
+export function XDSLightbox({
+ isOpen,
+ onOpenChange,
+ media,
+ index: controlledIndex,
+ defaultIndex = 0,
+ onIndexChange,
+ hasZoom = false,
+ hasAutoPlay = false,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSLightboxProps) {
+ const dialogRef = useRef<HTMLDialogElement>(null);
+ const imageWrapperRef = useRef<HTMLDivElement>(null);
+ const triggerElementRef = useRef<Element | null>(null);
+
+ // Index state (controlled + uncontrolled)
+ const isControlled = controlledIndex !== undefined;
+ const [uncontrolledIndex, setUncontrolledIndex] = useState(defaultIndex);
+ const index = isControlled ? controlledIndex : uncontrolledIndex;
+
+ const setIndex = useCallback(
+ (value: number) => {
+ if (!isControlled) {
+ setUncontrolledIndex(value);
+ }
+ onIndexChange?.(value);
+ },
+ [isControlled, onIndexChange],
+ );
+
+ // Zoom/pan state
+ const [zoom, setZoom] = useState(1);
+ const [pan, setPan] = useState({x: 0, y: 0});
+ const [isDragging, setIsDragging] = useState(false);
+ const dragStartRef = useRef({x: 0, y: 0, panX: 0, panY: 0});
+
+ // Resolve current media item
+ const mediaArray = Array.isArray(media) ? media : [media];
+ const isGallery = mediaArray.length > 1;
+ const currentItem = mediaArray[Math.min(index, mediaArray.length - 1)];
+ const currentType = currentItem.type ?? 'image';
+ const isVideo = currentType === 'video';
+ const canPrev = isGallery && index > 0;
+ const canNext = isGallery && index < mediaArray.length - 1;
+
+ // Scroll lock
+ useScrollLock(isOpen);
+
+ // Reset zoom on image change
+ useEffect(() => {
+ setZoom(1);
+ setPan({x: 0, y: 0});
+ }, [index, currentItem.src]);
+
+ // Open/close dialog
+ useIsomorphicLayoutEffect(() => {
+ const dialog = dialogRef.current;
+ if (!dialog) {
+ return;
+ }
+
+ if (isOpen && !dialog.open) {
+ triggerElementRef.current = document.activeElement;
+ dialog.showModal();
+ } else if (!isOpen && dialog.open) {
+ dialog.close();
+ if (triggerElementRef.current instanceof HTMLElement) {
+ triggerElementRef.current.focus();
+ }
+ }
+ }, [isOpen]);
+
+ const handleClose = useCallback(() => {
+ onOpenChange(false);
+ }, [onOpenChange]);
+
+ // Escape key
+ const handleCancel = useCallback(
+ (e: React.SyntheticEvent) => {
+ e.preventDefault();
+ handleClose();
+ },
+ [handleClose],
+ );
+
+ // Backdrop click
+ const handleBackdropClick = useCallback(
+ (e: ReactMouseEvent<HTMLDialogElement>) => {
+ if (e.target === e.currentTarget) {
+ handleClose();
+ }
+ },
+ [handleClose],
+ );
+
+ // Gallery navigation
+ const goToPrev = useCallback(() => {
+ if (canPrev) {
+ setIndex(index - 1);
+ }
+ }, [canPrev, index, setIndex]);
+
+ const goToNext = useCallback(() => {
+ if (canNext) {
+ setIndex(index + 1);
+ }
+ }, [canNext, index, setIndex]);
+
+ // Keyboard navigation
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent) => {
+ if (e.key === 'ArrowLeft') {
+ e.preventDefault();
+ goToPrev();
+ } else if (e.key === 'ArrowRight') {
+ e.preventDefault();
+ goToNext();
+ }
+ },
+ [goToPrev, goToNext],
+ );
+
+ // Zoom: double-click toggles 1x ↔ 2x
+ const handleDoubleClick = useCallback(() => {
+ if (!hasZoom) {
+ return;
+ }
+ if (zoom === 1) {
+ setZoom(2);
+ setPan({x: 0, y: 0});
+ } else {
+ setZoom(1);
+ setPan({x: 0, y: 0});
+ }
+ }, [hasZoom, zoom]);
+
+ // Pan: mouse drag when zoomed
+ const handlePointerDown = useCallback(
+ (e: ReactMouseEvent<HTMLDivElement>) => {
+ if (zoom <= 1 || !hasZoom) {
+ return;
+ }
+ setIsDragging(true);
+ dragStartRef.current = {
+ x: e.clientX,
+ y: e.clientY,
+ panX: pan.x,
+ panY: pan.y,
+ };
+ },
+ [zoom, hasZoom, pan],
+ );
+
+ useEffect(() => {
+ if (!isDragging) {
+ return;
+ }
+
+ const handlePointerMove = (e: PointerEvent) => {
+ const dx = e.clientX - dragStartRef.current.x;
+ const dy = e.clientY - dragStartRef.current.y;
+ setPan({
+ x: dragStartRef.current.panX + dx,
+ y: dragStartRef.current.panY + dy,
+ });
+ };
+
+ const handlePointerUp = () => {
+ setIsDragging(false);
+ };
+
+ window.addEventListener('pointermove', handlePointerMove);
+ window.addEventListener('pointerup', handlePointerUp);
+ return () => {
+ window.removeEventListener('pointermove', handlePointerMove);
+ window.removeEventListener('pointerup', handlePointerUp);
+ };
+ }, [isDragging]);
+
+ // Merge refs
+ const setRef = useCallback(
+ (node: HTMLDialogElement | null) => {
+ (dialogRef as React.MutableRefObject<HTMLDialogElement | null>).current =
+ node;
+ if (typeof ref === 'function') {
+ ref(node);
+ } else if (ref) {
+ (ref as React.MutableRefObject<HTMLDialogElement | null>).current =
+ node;
+ }
+ },
+ [ref],
+ );
+
+ const isZoomed = zoom > 1;
+ const imageTransform =
+ zoom === 1
+ ? null
+ : `scale(${zoom}) translate(${pan.x / zoom}px, ${pan.y / zoom}px)`;
+
+ return (
+ <dialog
+ ref={setRef}
+ onCancel={handleCancel}
+ onClick={handleBackdropClick}
+ onKeyDown={handleKeyDown}
+ aria-label={currentItem.alt || 'Media viewer'}
+ {...mergeProps(
+ xdsClassName('lightbox'),
+ stylex.props(styles.dialog, xstyle),
+ className,
+ style,
+ )}
+ {...props}>
+ <div {...stylex.props(styles.container)}>
+ {/* Close button */}
+ <div {...stylex.props(styles.closeButton)}>
+ <XDSIconButton
+ icon={<XDSIcon icon="close" size="sm" color="inherit" />}
+ label="Close"
+ variant="ghost"
+ onClick={handleClose}
+ xstyle={styles.controlButton}
+ />
+ </div>
+
+ {/* Gallery nav: prev */}
+ {isGallery && canPrev && (
+ <div {...stylex.props(styles.navButton, styles.navPrev)}>
+ <XDSIconButton
+ icon={<XDSIcon icon="chevronLeft" size="sm" color="inherit" />}
+ label="Previous image"
+ variant="ghost"
+ onClick={goToPrev}
+ xstyle={styles.controlButton}
+ />
+ </div>
+ )}
+
+ {/* Media + caption group (centered together) */}
+ <div {...stylex.props(styles.mediaGroup)}>
+ <div
+ ref={imageWrapperRef}
+ {...stylex.props(
+ styles.imageWrapper,
+ !isVideo && hasZoom && !isZoomed && styles.imageWrapperZoomable,
+ !isVideo && isZoomed && styles.imageWrapperZoomed,
+ !isVideo && isDragging && styles.imageWrapperDragging,
+ )}
+ onDoubleClick={isVideo ? undefined : handleDoubleClick}
+ onPointerDown={isVideo ? undefined : handlePointerDown}>
+ {isVideo ? (
+ <video
+ src={currentItem.src}
+ aria-label={currentItem.alt}
+ controls
+ autoPlay={hasAutoPlay}
+ {...stylex.props(styles.video)}
+ />
+ ) : (
+ <img
+ src={currentItem.src}
+ alt={currentItem.alt}
+ draggable={false}
+ {...stylex.props(
+ styles.image,
+ isDragging && styles.imageDragging,
+ imageTransform != null &&
+ dynamicStyles.imageTransform(imageTransform),
+ )}
+ />
+ )}
+ </div>
+
+ {currentItem.caption && (
+ <div {...stylex.props(styles.caption)}>{currentItem.caption}</div>
+ )}
+ </div>
+
+ {/* Gallery nav: next */}
+ {isGallery && canNext && (
+ <div {...stylex.props(styles.navButton, styles.navNext)}>
+ <XDSIconButton
+ icon={<XDSIcon icon="chevronRight" size="sm" color="inherit" />}
+ label="Next image"
+ variant="ghost"
+ onClick={goToNext}
+ xstyle={styles.controlButton}
+ />
+ </div>
+ )}
+
+ {/* Gallery counter */}
+ {isGallery && mediaArray.length > 1 && (
+ <div {...stylex.props(styles.counter)}>
+ {index + 1} / {mediaArray.length}
+ </div>
+ )}
+ </div>
+ </dialog>
+ );
+}
+
+XDSLightbox.displayName = 'XDSLightbox';
diff --git a/packages/core/src/Lightbox/index.ts b/packages/core/src/Lightbox/index.ts
new file mode 100644
index 0000000000..d6501df8d5
--- /dev/null
+++ b/packages/core/src/Lightbox/index.ts
@@ -0,0 +1,20 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file Lightbox component barrel export
+ */
+
+export {XDSLightbox} from './XDSLightbox';
+export type {
+ XDSLightboxProps,
+ XDSLightboxMedia,
+ XDSLightboxMediaType,
+} from './XDSLightbox';
+
+export {useXDSLightbox} from './useXDSLightbox';
+export type {
+ UseXDSLightboxOptions,
+ UseXDSLightboxReturn,
+} from './useXDSLightbox';
diff --git a/packages/core/src/Lightbox/useXDSLightbox.tsx b/packages/core/src/Lightbox/useXDSLightbox.tsx
new file mode 100644
index 0000000000..0485f6f279
--- /dev/null
+++ b/packages/core/src/Lightbox/useXDSLightbox.tsx
@@ -0,0 +1,154 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useXDSLightbox.tsx
+ * @input Uses React, XDSLightbox
+ * @output Exports useXDSLightbox hook
+ * @position Utility hook; wraps XDSLightbox with trigger props + state management
+ *
+ * Eliminates boilerplate for lightbox usage. Instead of managing isOpen state
+ * and index separately, call open() and the hook handles the rest.
+ *
+ * @example
+ * ```
+ * const lightbox = useXDSLightbox({ media: photos });
+ * <img onClick={() => lightbox.open(2)} />
+ * {lightbox.element}
+ * ```
+ */
+
+import {useState, useCallback, useMemo, type ReactNode} from 'react';
+import {
+ XDSLightbox,
+ type XDSLightboxProps,
+ type XDSLightboxMedia,
+} from './XDSLightbox';
+
+type LightboxOptions = Omit<
+ XDSLightboxProps,
+ | 'isOpen'
+ | 'onOpenChange'
+ | 'media'
+ | 'index'
+ | 'defaultIndex'
+ | 'onIndexChange'
+>;
+
+export interface UseXDSLightboxOptions extends LightboxOptions {
+ /** Media to display in the lightbox. */
+ media: XDSLightboxMedia | XDSLightboxMedia[];
+}
+
+export interface UseXDSLightboxReturn {
+ /** Open the lightbox, optionally at a specific gallery index. */
+ open: (index?: number) => void;
+ /** Close the lightbox. */
+ close: () => void;
+ /** Whether the lightbox is currently open. */
+ isOpen: boolean;
+ /** Current gallery index. */
+ index: number;
+ /** Render this in your JSX tree. */
+ element: ReactNode;
+ /** Props to spread on a trigger element for accessibility. */
+ triggerProps: {
+ role: 'button';
+ tabIndex: 0;
+ onClick: () => void;
+ onKeyDown: (e: React.KeyboardEvent) => void;
+ };
+ /** Returns trigger props that open at a specific gallery index. */
+ getTriggerProps: (index: number) => {
+ role: 'button';
+ tabIndex: 0;
+ onClick: () => void;
+ onKeyDown: (e: React.KeyboardEvent) => void;
+ };
+}
+
+/**
+ * Hook for lightbox with trigger props and state management.
+ *
+ * @example
+ * ```
+ * const lightbox = useXDSLightbox({ media: photos });
+ *
+ * {photos.map((photo, i) => (
+ * <img
+ * key={photo.src}
+ * src={photo.src}
+ * alt={photo.alt}
+ * {...lightbox.getTriggerProps(i)}
+ * />
+ * ))}
+ * {lightbox.element}
+ * ```
+ */
+export function useXDSLightbox(
+ options: UseXDSLightboxOptions,
+): UseXDSLightboxReturn {
+ const {media, ...lightboxProps} = options;
+ const [isOpen, setIsOpen] = useState(false);
+ const [index, setIndex] = useState(0);
+
+ const open = useCallback((i: number = 0) => {
+ setIndex(i);
+ setIsOpen(true);
+ }, []);
+
+ const close = useCallback(() => {
+ setIsOpen(false);
+ }, []);
+
+ const triggerProps = useMemo(
+ () => ({
+ role: 'button' as const,
+ tabIndex: 0 as const,
+ onClick: () => open(),
+ onKeyDown: (e: React.KeyboardEvent) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ open();
+ }
+ },
+ }),
+ [open],
+ );
+
+ const getTriggerProps = useCallback(
+ (i: number) => ({
+ role: 'button' as const,
+ tabIndex: 0 as const,
+ onClick: () => open(i),
+ onKeyDown: (e: React.KeyboardEvent) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ open(i);
+ }
+ },
+ }),
+ [open],
+ );
+
+ const element = useMemo(
+ () => (
+ <XDSLightbox
+ isOpen={isOpen}
+ onOpenChange={nextOpen => {
+ if (!nextOpen) {
+ setIsOpen(false);
+ }
+ }}
+ media={media}
+ index={index}
+ onIndexChange={setIndex}
+ {...lightboxProps}
+ />
+ ),
+ [isOpen, media, index, lightboxProps],
+ );
+
+ return {open, close, isOpen, index, element, triggerProps, getTriggerProps};
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index f8b7fb5972..be19e04e0e 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -43,6 +43,7 @@ export * from './RadioList';
export * from './Resizable';
export * from './Divider';
export * from './EmptyState';
+export * from './Lightbox';
export * from './Link';
export * from './List';
export * from './MetadataList';