An open source design system that's fully customizable and agent ready
TypeScript
fix(core): announce Lightbox image changes to screen readers (#3727)
Baraa Hamodi8ae4772008e2
diff --git a/.changeset/lightbox-counter-announce.md b/.changeset/lightbox-counter-announce.mdnew file mode 100644index 0000000000..362969f898--- /dev/null+++ b/.changeset/lightbox-counter-announce.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Lightbox: navigating between images now announces the new image and its position (e.g. "Sunset over the bay, 3 of 12") to screen readers via a polite live region. Previously only the visual counter updated. (#3727)+@bhamodidiff --git a/packages/core/src/Lightbox/Lightbox.test.tsx b/packages/core/src/Lightbox/Lightbox.test.tsxindex 1e015f32f8..4fa3cbca8e 100644--- a/packages/core/src/Lightbox/Lightbox.test.tsx+++ b/packages/core/src/Lightbox/Lightbox.test.tsx@@ -1,8 +1,9 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import {describe, it, expect, vi, beforeEach} from 'vitest';-import {render, screen, fireEvent} from '@testing-library/react';+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';+import {render, screen, fireEvent, waitFor} from '@testing-library/react';import {Lightbox} from './Lightbox';+import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';// Mock showModal/close for jsdombeforeEach(() => {@@ -16,6 +17,16 @@ beforeEach(() => {});});+// useAnnounce mounts singleton live regions on <body>; reset between tests so+// stale announcements from one test don't leak into the next.+afterEach(() => {+ __resetLiveRegionsForTest();+});++function politeRegion(): HTMLElement | null {+ return document.querySelector('[data-astryx-live-region="polite"]');+}+describe('Lightbox', () => {it('renders as a dialog element', () => {render(@@ -300,6 +311,116 @@ describe('Lightbox', () => {});});+ describe('screen-reader announcements', () => {+ 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('announces the new image and position when navigating next via button', async () => {+ render(+ <Lightbox+ isOpen={true}+ onOpenChange={() => {}}+ media={media}+ defaultIndex={0}+ />,+ );+ fireEvent.click(screen.getByLabelText('Next'));+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('Image B, 2 of 3');+ });+ });++ it('announces the new image and position when navigating via arrow keys', async () => {+ render(+ <Lightbox+ isOpen={true}+ onOpenChange={() => {}}+ media={media}+ defaultIndex={1}+ />,+ );+ const dialog = document.querySelector('dialog')!;+ fireEvent.keyDown(dialog, {key: 'ArrowRight'});+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('Image C, 3 of 3');+ });+ });++ it('announces the new image and position when navigating prev', async () => {+ render(+ <Lightbox+ isOpen={true}+ onOpenChange={() => {}}+ media={media}+ defaultIndex={2}+ />,+ );+ fireEvent.click(screen.getByLabelText('Previous'));+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('Image B, 2 of 3');+ });+ });++ it('falls back to a positional label when the image has no alt', async () => {+ const unlabeled = [+ {src: '/a.jpg', alt: 'Image A'},+ {src: '/b.jpg', alt: ''},+ ];+ render(+ <Lightbox+ isOpen={true}+ onOpenChange={() => {}}+ media={unlabeled}+ defaultIndex={0}+ />,+ );+ fireEvent.click(screen.getByLabelText('Next'));+ await waitFor(() => {+ expect(politeRegion()).toHaveTextContent('Image 2 of 2');+ });+ });++ it('does not announce on initial open', async () => {+ render(+ <Lightbox+ isOpen={true}+ onOpenChange={() => {}}+ media={media}+ defaultIndex={1}+ />,+ );+ // Allow any scheduled rAF to flush; nothing should have been announced.+ await new Promise(resolve => requestAnimationFrame(() => resolve(null)));+ // The dialog's aria-label already names the current image on open, so no+ // live region is created (announce is never called).+ expect(politeRegion()).toBeNull();+ });++ it('does not announce when the lightbox opens at a new index', async () => {+ const {rerender} = render(+ <Lightbox+ isOpen={false}+ onOpenChange={() => {}}+ media={media}+ index={0}+ />,+ );+ rerender(+ <Lightbox+ isOpen={true}+ onOpenChange={() => {}}+ media={media}+ index={2}+ />,+ );+ await new Promise(resolve => requestAnimationFrame(() => resolve(null)));+ expect(politeRegion()).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.tsxindex ca75a2fd50..273433c233 100644--- a/packages/core/src/Lightbox/Lightbox.tsx+++ b/packages/core/src/Lightbox/Lightbox.tsx@@ -19,6 +19,7 @@import {useCallback,useEffect,+ useMemo,useRef,useState,type MouseEvent as ReactMouseEvent,@@ -28,6 +29,7 @@ import * as stylex from '@stylexjs/stylex';import {colorVars, spacingVars, typeScaleVars} from '../theme/tokens.stylex';import {Icon} from '../Icon';import {IconButton} from '../IconButton';+import {useAnnounce} from '../hooks/useAnnounce';import {useScrollLock} from '../hooks/useScrollLock';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import {mergeProps, mergeRefs} from '../utils';@@ -306,7 +308,10 @@ export function Lightbox({const dragStartRef = useRef({x: 0, y: 0, panX: 0, panY: 0});// Resolve current media item- const mediaArray = Array.isArray(media) ? media : [media];+ const mediaArray = useMemo(+ () => (Array.isArray(media) ? media : [media]),+ [media],+ );const isGallery = mediaArray.length > 1;const currentItem =mediaArray.length > 0@@ -329,6 +334,29 @@ export function Lightbox({setPan({x: 0, y: 0});}, [index, currentItem?.src]);+ // Announce gallery navigation to screen readers. Moving between images only+ // updates the visual counter, which is silent to assistive tech, so mirror+ // each change in a polite live region ("<alt>, 3 of 12", or "Image 3 of 12"+ // when the image has no alt). Announce only when the image changes during an+ // already-open session — not on mount, not when opening (even at a new+ // index, since the dialog's aria-label already names the current image), and+ // not on close.+ const announce = useAnnounce();+ const prevIndexRef = useRef(index);+ const wasOpenRef = useRef(isOpen);+ useEffect(() => {+ const indexChanged = prevIndexRef.current !== index;+ const wasOpen = wasOpenRef.current;+ prevIndexRef.current = index;+ wasOpenRef.current = isOpen;+ if (!indexChanged || !isOpen || !wasOpen) {+ return;+ }+ const item = mediaArray[Math.min(index, mediaArray.length - 1)];+ const position = `${index + 1} of ${mediaArray.length}`;+ announce(item?.alt ? `${item.alt}, ${position}` : `Image ${position}`);+ }, [index, isOpen, announce, mediaArray]);+// Open/close dialoguseIsomorphicLayoutEffect(() => {const dialog = dialogRef.current;