Skip to content

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

TypeScript

fix(core): keyboard zoom and pan for Lightbox (#4367)

Baraa Hamodi79cf94a17f33
diff --git a/.changeset/a11y-lightbox-keyboard-zoom.md b/.changeset/a11y-lightbox-keyboard-zoom.md
new file mode 100644
index 0000000000..612a0b155c
--- /dev/null
+++ b/.changeset/a11y-lightbox-keyboard-zoom.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Lightbox: add keyboard zoom (Enter/Space on the image, `+`/`-`) and arrow-key panning while zoomed, with polite announcements (WCAG 2.1.1)
+@bhamodi
diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json
index 9c4b611100..6c01fc789b 100644
--- a/packages/core/locales/en.json
+++ b/packages/core/locales/en.json
@@ -787,6 +787,18 @@
"defaultMessage": "Media viewer",
"description": "Screen-reader-only fallback name for the Lightbox dialog when the current media item has no alt text. Should rarely render — consumers should provide alt."
},
+ "@astryx.lightbox.zoom": {
+ "defaultMessage": "Zoom",
+ "description": "Screen-reader-only label on the Lightbox image acting as a zoom toggle button (aria-pressed reflects zoomed state). Verb (\"to zoom\"), very short."
+ },
+ "@astryx.lightbox.zoomedIn": {
+ "defaultMessage": "Zoomed in, use arrow keys to pan",
+ "description": "Polite screen-reader announcement after zooming into a Lightbox image, including a hint that arrow keys pan while zoomed. Pairs with `lightbox.zoomedOut`."
+ },
+ "@astryx.lightbox.zoomedOut": {
+ "defaultMessage": "Zoomed out",
+ "description": "Polite screen-reader announcement after zooming back out of a Lightbox image. Pairs with `lightbox.zoomedIn`."
+ },
"@astryx.metadataList.showMore": {
"defaultMessage": "Show more",
"description": "Button label under a MetadataList that reveals items hidden beyond the configured maximum. Toggles with `metadataList.showLess` — keep the pair parallel in your language."
diff --git a/packages/core/src/Lightbox/Lightbox.doc.mjs b/packages/core/src/Lightbox/Lightbox.doc.mjs
index a849d1bd5d..3739798b0a 100644
--- a/packages/core/src/Lightbox/Lightbox.doc.mjs
+++ b/packages/core/src/Lightbox/Lightbox.doc.mjs
@@ -44,7 +44,7 @@ export const docs = {
{
name: 'hasZoom',
type: 'boolean',
- description: 'Enable zoom on double-click (images only). When zoomed, drag to pan.',
+ description: 'Enable zoom on double-click, or Enter/Space/+/- via keyboard (images only). When zoomed, drag or use arrow keys to pan.',
default: 'false',
},
{
@@ -168,7 +168,7 @@ export const docsDense = {
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).',
+ hasZoom: 'Enable zoom (double-click, Enter/Space, or +/-) and pan (drag or arrow keys) for images.',
xstyle: 'StyleX styles for layout customization.',
},
};
diff --git a/packages/core/src/Lightbox/Lightbox.test.tsx b/packages/core/src/Lightbox/Lightbox.test.tsx
index 3d41ce6f67..396ad34e00 100644
--- a/packages/core/src/Lightbox/Lightbox.test.tsx
+++ b/packages/core/src/Lightbox/Lightbox.test.tsx
@@ -421,6 +421,184 @@ describe('Lightbox', () => {
});
});
+ describe('keyboard zoom and pan', () => {
+ const media = [
+ {src: '/a.jpg', alt: 'Image A'},
+ {src: '/b.jpg', alt: 'Image B'},
+ {src: '/c.jpg', alt: 'Image C'},
+ ];
+
+ function zoomTarget(): HTMLElement {
+ return screen.getByRole('button', {name: 'Zoom'});
+ }
+
+ it('exposes the image as a focusable zoom toggle when hasZoom is on', () => {
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={{src: '/photo.jpg', alt: 'Photo'}}
+ hasZoom
+ />,
+ );
+ const target = zoomTarget();
+ expect(target).toHaveAttribute('tabindex', '0');
+ expect(target).toHaveAttribute('aria-pressed', 'false');
+ });
+
+ it('toggles zoom with Enter on the image', () => {
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={{src: '/photo.jpg', alt: 'Photo'}}
+ hasZoom
+ />,
+ );
+ const target = zoomTarget();
+ fireEvent.keyDown(target, {key: 'Enter'});
+ expect(target).toHaveAttribute('aria-pressed', 'true');
+ fireEvent.keyDown(target, {key: 'Enter'});
+ expect(target).toHaveAttribute('aria-pressed', 'false');
+ });
+
+ it('toggles zoom with Space on the image', () => {
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={{src: '/photo.jpg', alt: 'Photo'}}
+ hasZoom
+ />,
+ );
+ const target = zoomTarget();
+ fireEvent.keyDown(target, {key: ' '});
+ expect(target).toHaveAttribute('aria-pressed', 'true');
+ fireEvent.keyDown(target, {key: ' '});
+ expect(target).toHaveAttribute('aria-pressed', 'false');
+ });
+
+ it('zooms in with + and out with - from anywhere in the dialog', () => {
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={{src: '/photo.jpg', alt: 'Photo'}}
+ hasZoom
+ />,
+ );
+ const dialog = document.querySelector('dialog')!;
+ fireEvent.keyDown(dialog, {key: '+'});
+ expect(zoomTarget()).toHaveAttribute('aria-pressed', 'true');
+ fireEvent.keyDown(dialog, {key: '-'});
+ expect(zoomTarget()).toHaveAttribute('aria-pressed', 'false');
+ // `=` (unshifted `+` on most layouts) also zooms in.
+ fireEvent.keyDown(dialog, {key: '='});
+ expect(zoomTarget()).toHaveAttribute('aria-pressed', 'true');
+ });
+
+ it('pans with arrow keys while zoomed instead of navigating the gallery', () => {
+ const onIndexChange = vi.fn();
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={media}
+ index={1}
+ onIndexChange={onIndexChange}
+ hasZoom
+ />,
+ );
+ const dialog = document.querySelector('dialog')!;
+ fireEvent.keyDown(zoomTarget(), {key: 'Enter'});
+ const img = screen.getByAltText('Image B');
+ expect(img.getAttribute('style') ?? '').toContain('translate(0px, 0px)');
+ // ArrowRight reveals content to the right (image shifts left) and must
+ // not fall through to gallery navigation.
+ fireEvent.keyDown(dialog, {key: 'ArrowRight'});
+ expect(onIndexChange).not.toHaveBeenCalled();
+ expect(img.getAttribute('style') ?? '').toContain(
+ 'translate(-25px, 0px)',
+ );
+ fireEvent.keyDown(dialog, {key: 'ArrowDown'});
+ expect(img.getAttribute('style') ?? '').toContain(
+ 'translate(-25px, -25px)',
+ );
+ fireEvent.keyDown(dialog, {key: 'ArrowLeft'});
+ fireEvent.keyDown(dialog, {key: 'ArrowUp'});
+ expect(img.getAttribute('style') ?? '').toContain('translate(0px, 0px)');
+ expect(onIndexChange).not.toHaveBeenCalled();
+ });
+
+ it('navigates the gallery with arrows when not zoomed, even with hasZoom', () => {
+ const onIndexChange = vi.fn();
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={media}
+ index={1}
+ onIndexChange={onIndexChange}
+ hasZoom
+ />,
+ );
+ const dialog = document.querySelector('dialog')!;
+ fireEvent.keyDown(dialog, {key: 'ArrowRight'});
+ expect(onIndexChange).toHaveBeenCalledWith(2);
+ });
+
+ it('announces zoom state changes politely', async () => {
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={{src: '/photo.jpg', alt: 'Photo'}}
+ hasZoom
+ />,
+ );
+ fireEvent.keyDown(zoomTarget(), {key: 'Enter'});
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent('Zoomed in');
+ });
+ fireEvent.keyDown(zoomTarget(), {key: 'Enter'});
+ await waitFor(() => {
+ expect(politeRegion()).toHaveTextContent('Zoomed out');
+ });
+ });
+
+ it('has no zoom target or key bindings when hasZoom is off', () => {
+ const onIndexChange = vi.fn();
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={media}
+ index={1}
+ onIndexChange={onIndexChange}
+ />,
+ );
+ expect(screen.queryByRole('button', {name: 'Zoom'})).toBeNull();
+ const dialog = document.querySelector('dialog')!;
+ fireEvent.keyDown(dialog, {key: '+'});
+ expect(document.querySelector('[aria-pressed]')).toBeNull();
+ // Arrows still navigate the gallery.
+ fireEvent.keyDown(dialog, {key: 'ArrowRight'});
+ expect(onIndexChange).toHaveBeenCalledWith(2);
+ });
+
+ it('does not expose a zoom target for video items', () => {
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={{src: '/clip.mp4', alt: 'A clip', type: 'video'}}
+ hasZoom
+ />,
+ );
+ expect(screen.queryByRole('button', {name: 'Zoom'})).toBeNull();
+ });
+ });
+
describe('video support', () => {
it('renders a video element when type is video', () => {
const {container} = render(
diff --git a/packages/core/src/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsx
index 40d9e5ab6d..cd43635780 100644
--- a/packages/core/src/Lightbox/Lightbox.tsx
+++ b/packages/core/src/Lightbox/Lightbox.tsx
@@ -91,8 +91,8 @@ export interface LightboxProps extends BaseProps<HTMLDialogElement> {
*/
onIndexChange?: (index: number) => void;
/**
- * Enable zoom on double-click (images only).
- * When zoomed, drag to pan.
+ * Enable zoom on double-click, or Enter/Space/`+`/`-` via keyboard
+ * (images only). When zoomed, drag or use arrow keys to pan.
* @default false
*/
hasZoom?: boolean;
@@ -158,6 +158,16 @@ const styles = stylex.create({
'@media (hover: hover)': 'zoom-in',
},
},
+ zoomTarget: {
+ outline: {
+ default: 'none',
+ ':focus-visible': `2px solid ${colorVars['--color-accent']}`,
+ },
+ outlineOffset: {
+ default: '0',
+ ':focus-visible': '2px',
+ },
+ },
imageWrapperZoomed: {
cursor: 'grab',
},
@@ -234,12 +244,28 @@ const dynamicStyles = stylex.create({
}),
});
+/**
+ * Pan distance (px) per arrow-key press while zoomed. Offsets move the
+ * viewport in the arrow's direction — pressing ArrowRight reveals content to
+ * the right, so the image itself shifts left (negative x), matching how
+ * scrolling and pointer-drag panning feel.
+ */
+const KEYBOARD_PAN_STEP = 50;
+const KEYBOARD_PAN_OFFSETS: Record<string, [number, number]> = {
+ ArrowLeft: [KEYBOARD_PAN_STEP, 0],
+ ArrowRight: [-KEYBOARD_PAN_STEP, 0],
+ ArrowUp: [0, KEYBOARD_PAN_STEP],
+ ArrowDown: [0, -KEYBOARD_PAN_STEP],
+};
+
/**
* 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).
+ * zoom (double-click, Enter/Space on the image, or `+`/`-` to toggle 2x)
+ * and pan (drag or arrow keys when zoomed; arrows navigate the gallery
+ * when not zoomed).
*
* Uses the native `<dialog>` element with `showModal()` for focus
* trapping and top-layer placement. Dismiss via Escape, close button,
@@ -423,9 +449,52 @@ export function Lightbox({
}
}, [canNext, index, setIndex]);
- // Keyboard navigation
+ // Zoom: double-click, Enter/Space on the image, or +/- keys toggle 1x ↔ 2x.
+ // Zoom changes are silent to assistive tech (only the transform changes), so
+ // mirror them in the polite live region, including a hint that arrow keys
+ // pan while zoomed.
+ const applyZoom = useCallback(
+ (next: number) => {
+ if (!hasZoom || isVideo || next === zoom) {
+ return;
+ }
+ setZoom(next);
+ setPan({x: 0, y: 0});
+ announce(
+ next > 1
+ ? t('@astryx.lightbox.zoomedIn')
+ : t('@astryx.lightbox.zoomedOut'),
+ );
+ },
+ [hasZoom, isVideo, zoom, announce, t],
+ );
+
+ const handleDoubleClick = useCallback(() => {
+ applyZoom(zoom === 1 ? 2 : 1);
+ }, [applyZoom, zoom]);
+
+ // Keyboard navigation. While zoomed, arrows pan the image (matching common
+ // lightbox conventions); when not zoomed they navigate the gallery.
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
+ if (hasZoom && !isVideo) {
+ if (e.key === '+' || e.key === '=') {
+ e.preventDefault();
+ applyZoom(2);
+ return;
+ }
+ if (e.key === '-') {
+ e.preventDefault();
+ applyZoom(1);
+ return;
+ }
+ if (zoom > 1 && KEYBOARD_PAN_OFFSETS[e.key] !== undefined) {
+ e.preventDefault();
+ const [dx, dy] = KEYBOARD_PAN_OFFSETS[e.key];
+ setPan(prev => ({x: prev.x + dx, y: prev.y + dy}));
+ return;
+ }
+ }
if (e.key === 'ArrowLeft') {
e.preventDefault();
goToPrev();
@@ -434,22 +503,19 @@ export function Lightbox({
goToNext();
}
},
- [goToPrev, goToNext],
+ [hasZoom, isVideo, zoom, applyZoom, 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]);
+ // Enter/Space on the focused image wrapper (role="button") toggles zoom.
+ const handleImageKeyDown = useCallback(
+ (e: React.KeyboardEvent<HTMLDivElement>) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ handleDoubleClick();
+ }
+ },
+ [handleDoubleClick],
+ );
// Pan: mouse drag when zoomed
const handlePointerDown = useCallback(
@@ -497,6 +563,7 @@ export function Lightbox({
}, [isDragging]);
const isZoomed = zoom > 1;
+ const isZoomTarget = hasZoom && !isVideo;
const imageTransform =
zoom === 1
? null
@@ -562,13 +629,21 @@ export function Lightbox({
<div {...stylex.props(styles.mediaGroup)}>
<div
ref={imageWrapperRef}
+ // The wrapper is a keyboard-operable zoom toggle when zoom is
+ // enabled: Enter/Space toggles, aria-pressed reflects state.
+ role={isZoomTarget ? 'button' : undefined}
+ tabIndex={isZoomTarget ? 0 : undefined}
+ aria-pressed={isZoomTarget ? isZoomed : undefined}
+ aria-label={isZoomTarget ? t('@astryx.lightbox.zoom') : undefined}
{...stylex.props(
styles.imageWrapper,
+ isZoomTarget && styles.zoomTarget,
!isVideo && hasZoom && !isZoomed && styles.imageWrapperZoomable,
!isVideo && isZoomed && styles.imageWrapperZoomed,
!isVideo && isDragging && styles.imageWrapperDragging,
)}
onDoubleClick={isVideo ? undefined : handleDoubleClick}
+ onKeyDown={isZoomTarget ? handleImageKeyDown : undefined}
onPointerDown={isVideo ? undefined : handlePointerDown}>
{isVideo ? (
<video