An open source design system that's fully customizable and agent ready
TypeScript
fix(Lightbox): the gallery's arrow keys follow the writing direction (#8081)
Christopher Chedeau03e051aaa8f4
diff --git a/.changeset/lightbox-rtl-arrow-keys.md b/.changeset/lightbox-rtl-arrow-keys.mdnew file mode 100644index 0000000000..dd2c1c2237--- /dev/null+++ b/.changeset/lightbox-rtl-arrow-keys.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Lightbox's Left and Right arrow keys now follow the writing direction. In a right-to-left page the gallery's Next button sits on the left, and ArrowLeft now moves to the next item and ArrowRight to the previous one, matching the buttons. Before, ArrowLeft always went to the previous item, so in RTL the keys moved against their buttons. Panning a zoomed image with the arrow keys is unchanged in both directions: the image is not mirrored, so ArrowRight still reveals what is to its right.++@vjeuxdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex b452dcc1d3..a5d12cc813 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1536,6 +1536,17 @@ jobs:--project chromium \--output multiselector-disabled-focus-output+ # In a right-to-left page Lightbox's Next button sits on the left, and+ # the arrow keys must move toward the button on their side. The+ # direction reaches the top-layer dialog through the engine's own+ # cascade, which jsdom does not inherit.+ - name: Run Lightbox arrow-key direction contract+ run: |+ pnpm exec playwright test \+ packages/core/src/Lightbox/LightboxKeyboard.a11y.browser.spec.ts \+ --project chromium \+ --output lightbox-keyboard-output+# The same guard for Selector and ComplexSelector triggers.- name: Run disabled trigger focus contractrun: |diff --git a/packages/core/src/Lightbox/Lightbox.test.tsx b/packages/core/src/Lightbox/Lightbox.test.tsxindex e2d0cffcd4..a1030b6751 100644--- a/packages/core/src/Lightbox/Lightbox.test.tsx+++ b/packages/core/src/Lightbox/Lightbox.test.tsx@@ -322,6 +322,50 @@ describe('Lightbox', () => {fireEvent.keyDown(dialog, {key: 'ArrowLeft'});expect(onIndexChange).toHaveBeenCalledWith(0);});++ it('follows the visual direction of the arrows in RTL', () => {+ const onIndexChange = vi.fn();+ render(+ <div dir="rtl">+ <Lightbox+ isOpen={true}+ onOpenChange={() => {}}+ media={media}+ index={1}+ onIndexChange={onIndexChange}+ />+ </div>,+ );+ const dialog = document.querySelector('dialog')!;+ // The component resolves direction with getComputedStyle at keydown, and+ // jsdom does not inherit `dir` down to it, so set it on the dialog too.+ dialog.style.direction = 'rtl';+ // Next sits on the left in RTL: ArrowLeft moves to the next item.+ fireEvent.keyDown(dialog, {key: 'ArrowLeft'});+ expect(onIndexChange).toHaveBeenLastCalledWith(2);+ fireEvent.keyDown(dialog, {key: 'ArrowRight'});+ expect(onIndexChange).toHaveBeenLastCalledWith(0);+ expect(onIndexChange).toHaveBeenCalledTimes(2);+ });++ it('resolves the direction at keydown, so a direction change applies at once', () => {+ const onIndexChange = vi.fn();+ render(+ <Lightbox+ isOpen={true}+ onOpenChange={() => {}}+ media={media}+ index={1}+ onIndexChange={onIndexChange}+ />,+ );+ const dialog = document.querySelector('dialog')!;+ fireEvent.keyDown(dialog, {key: 'ArrowLeft'});+ expect(onIndexChange).toHaveBeenLastCalledWith(0);+ dialog.style.direction = 'rtl';+ fireEvent.keyDown(dialog, {key: 'ArrowLeft'});+ expect(onIndexChange).toHaveBeenLastCalledWith(2);+ });});describe('screen-reader announcements', () => {@@ -569,6 +613,30 @@ describe('Lightbox', () => {expect(onIndexChange).toHaveBeenCalledWith(2);});+ it('keeps panning physical in RTL: the image is not mirrored', () => {+ const onIndexChange = vi.fn();+ render(+ <Lightbox+ isOpen={true}+ onOpenChange={() => {}}+ media={media}+ index={1}+ onIndexChange={onIndexChange}+ hasZoom+ />,+ );+ const dialog = document.querySelector('dialog')!;+ dialog.style.direction = 'rtl';+ fireEvent.keyDown(zoomTarget(), {key: 'Enter'});+ const img = screen.getByAltText('Image B');+ // ArrowRight still reveals what is to the right of the photo.+ fireEvent.keyDown(dialog, {key: 'ArrowRight'});+ expect(img.getAttribute('style') ?? '').toContain(+ 'translate(-25px, 0px)',+ );+ expect(onIndexChange).not.toHaveBeenCalled();+ });+it('announces zoom state changes politely', async () => {render(<Lightboxdiff --git a/packages/core/src/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsxindex e86444aad4..64354c1574 100644--- a/packages/core/src/Lightbox/Lightbox.tsx+++ b/packages/core/src/Lightbox/Lightbox.tsx@@ -4,7 +4,8 @@/*** @file Lightbox.tsx- * @input Uses React, native dialog, StyleX, IconButton, theme tokens, layerTextReset, layerStructureReset+ * @input Uses React, native dialog, StyleX, IconButton, theme tokens, layerTextReset, layerStructureReset,+ * isRtlElement (gallery arrow keys follow the rendered direction)* @output Exports Lightbox component, LightboxProps, LightboxMedia* @position Core implementation; consumed by index.ts*@@ -46,6 +47,7 @@ import {useLayerDismissal} from '../Layer/useLayerDismissal';import {useTranslator} from '../i18n';import {useMergedRefs} from '../hooks/useMergedRefs';+import {isRtlElement} from '../hooks/isRtlElement';/*** Media type for lightbox items.*/@@ -274,7 +276,9 @@ const KEYBOARD_PAN_OFFSETS: Record<string, [number, number]> = {* 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+ * prev/next navigation via buttons and arrow keys; the arrow keys follow+ * the writing direction (in RTL, ArrowLeft goes to the next item, like the+ * Next button on the left). Optionally supports* 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).@@ -513,6 +517,12 @@ export function Lightbox({// Keyboard navigation. While zoomed, arrows pan the image (matching common// lightbox conventions); when not zoomed they navigate the gallery.+ //+ // Gallery arrows follow the rendered direction, resolved at keydown: in RTL+ // the Next button sits on the left, so ArrowLeft goes to the next item and+ // ArrowRight to the previous one. Panning stays physical in both directions:+ // the image itself is not mirrored, so ArrowRight still reveals what is to+ // its right.const handleKeyDown = useCallback((e: React.KeyboardEvent) => {if (hasZoom && !isVideo) {@@ -533,12 +543,15 @@ export function Lightbox({return;}}- if (e.key === 'ArrowLeft') {- e.preventDefault();- goToPrev();- } else if (e.key === 'ArrowRight') {+ if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {e.preventDefault();- goToNext();+ const towardEnd =+ (e.key === 'ArrowRight') !== isRtlElement(dialogRef.current);+ if (towardEnd) {+ goToNext();+ } else {+ goToPrev();+ }}},[hasZoom, isVideo, zoom, applyZoom, goToPrev, goToNext],diff --git a/packages/core/src/Lightbox/LightboxKeyboard.a11y.browser.spec.ts b/packages/core/src/Lightbox/LightboxKeyboard.a11y.browser.spec.tsnew file mode 100644index 0000000000..3fbe990507--- /dev/null+++ b/packages/core/src/Lightbox/LightboxKeyboard.a11y.browser.spec.ts@@ -0,0 +1,77 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file LightboxKeyboard.a11y.browser.spec.ts+ * @input Built Lightbox stories (LTR and the RTL story global) and real+ * Chromium/WebKit keyboard input+ * @output Browser evidence that the gallery's Left/Right arrow keys move in+ * the direction of the matching on-screen button, in both directions+ * @position Cross-browser proof for Lightbox's direction-aware gallery keys+ * (design:bidirectionality DR6, DR11)+ */++import {expect, test, type Page} from '@playwright/test';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++// Opens the gallery story at its second photo ("2 / 4").+async function openGallery(page: Page, direction: 'ltr' | 'rtl') {+ // The story's photos are remote; the keys do not need them to load.+ await page.route(/picsum\.photos/, async route => route.abort());+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-lightbox--gallery&viewMode=story${+ direction === 'rtl' ? '&globals=direction:rtl' : ''+ }`,+ );+ await page.getByRole('img', {name: 'Mountain lake'}).click();+ const dialog = page.getByRole('dialog');+ await expect(dialog).toBeVisible();+ await expect(dialog).toContainText('2 / 4');+ const previous = page.getByRole('button', {name: 'Previous'});+ const next = page.getByRole('button', {name: 'Next'});+ return {dialog, previous, next};+}++async function centerX(locator: ReturnType<Page['getByRole']>) {+ const box = await locator.boundingBox();+ if (box == null) {+ throw new Error('no box');+ }+ return box.x + box.width / 2;+}++for (const direction of ['ltr', 'rtl'] as const) {+ test(`${direction}: each arrow key moves toward the button on its side`, async ({+ page,+ }) => {+ const {dialog, previous, next} = await openGallery(page, direction);+ const nextIsOnTheLeft = (await centerX(next)) < (await centerX(previous));+ // The buttons swap sides in RTL; the keys must follow them.+ expect(nextIsOnTheLeft).toBe(direction === 'rtl');+ const towardNext = nextIsOnTheLeft ? 'ArrowLeft' : 'ArrowRight';+ const towardPrevious = nextIsOnTheLeft ? 'ArrowRight' : 'ArrowLeft';++ await page.keyboard.press(towardNext);+ await expect(dialog).toContainText('3 / 4');+ await page.keyboard.press(towardPrevious);+ await page.keyboard.press(towardPrevious);+ await expect(dialog).toContainText('1 / 4');+ // At the start of the range the key toward Previous does nothing, like+ // the disabled button it matches.+ await page.keyboard.press(towardPrevious);+ await expect(dialog).toContainText('1 / 4');+ });+}