Skip to content
72 changes: 72 additions & 0 deletions .changeset/scope-keys.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
---
'react-spring-lightbox': patch
---

The lightbox's keys now act only while focus is inside it, so text fields, selects, and the page around an inline carousel keep their own keys (#65).

- With 1.9.0, the lightbox listened for keys on `document` whenever `isOpen` was true. ← and → paged the lightbox while you typed in a text field in its header or footer, and Home, End, ↑, ↓, PageUp, and PageDown did nothing in that field. Escape closed the lightbox even after the field called `preventDefault()`. An inline carousel took ←, →, and Escape from the whole page, even when it was scrolled out of view, and blocked the keys that scroll the page. Every mounted lightbox reacted to each key.
- Now the lightbox handles keys in an `onKeyDown` on its dialog, or on the carousel's root with `inline`. Keys pressed elsewhere on the page don't reach it.
- While the modal lightbox is open, it also takes keys pressed while nothing has focus, as if they were pressed in it. Focus falls to `<body>` when the focused control turns disabled or leaves the page, as a Next button rendered with `disabled={!canNext}` does on the last image. Such a key also moves focus back into the lightbox. Tab then goes to its first control and Shift+Tab to its last.
- ← and → leave text fields, selects, and other editable elements alone. Escape still closes the lightbox from a text field, unless the field calls `preventDefault()` in its own `onKeyDown`.
- ←, →, and Escape do nothing with Alt, Ctrl, or Cmd held, so browser and system shortcuts such as Alt+← keep working. Keys pressed while an input method composes text do nothing at all.
- The keys act when they go down instead of when they come up. Holding an arrow key still pages once.
- While the modal lightbox is open, ↑, ↓, PageUp, PageDown, Home, and End pressed in it don't scroll the page behind it, with or without Alt, Ctrl, or Cmd, unless a text field has focus. Space doesn't scroll it either, unless Space presses a focused button. With 1.9.0, Space scrolled the page behind the lightbox. Keys pressed in content portaled out of the lightbox, such as a menu that a header button renders into `<body>`, are left to that content, so they scroll the page behind unless that content prevents them. An `inline` carousel never blocks these keys.
- Tested with the unit tests on React 19 and React 18.3.1, the Playwright tests in Chromium, Firefox, and mobile Chromium on React 19, and the Chromium Playwright tests on React 18.3.1. CI runs the WebKit projects.

Upgrade notes:

- If keyboard users page your inline carousel with ← and → while focus is elsewhere on the page, the carousel now ignores those keys. It takes them only while focus is inside it. Render buttons with `renderPrevButton` and `renderNextButton`, so keyboard users can move focus into the carousel.

Before:

```jsx
<Lightbox
inline
isOpen
/* your other props */
/>
```

After:

```jsx
<Lightbox
inline
isOpen
renderNextButton={({ canNext }) => (
<button
disabled={!canNext}
onClick={gotoNext}
type="button"
>
Next image
</button>
)}
renderPrevButton={({ canPrev }) => (
<button
disabled={!canPrev}
onClick={gotoPrevious}
type="button"
>
Previous image
</button>
)}
/* your other props */
/>
```

A button that turns `disabled` while it has focus, as these do at the first and last image, drops focus to the page. The carousel then takes no keys until focus is back inside it.

- If a test of your app fires key events at `document`, or fires only `keyup`, the lightbox no longer sees them. Fire `keydown` at the focused element, as a browser does.

Before:

```js
fireEvent.keyUp(document, { key: 'ArrowRight' });
```

After:

```js
fireEvent.keyDown(document.activeElement, { key: 'ArrowRight' });
```
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ React-spring-lightbox is a flexible image gallery lightbox with native-feeling t
## ✨ Features

- :point_up: &nbsp;&nbsp;&nbsp;`Mousewheel`, swipe or click+drag to page photos
- :keyboard: &nbsp;Keyboard controls <kbd>&leftarrow;</kbd> <kbd>&rightarrow;</kbd> <kbd>Esc</kbd>
- :keyboard: &nbsp;Keyboard controls <kbd>&leftarrow;</kbd> <kbd>&rightarrow;</kbd> <kbd>Esc</kbd> that leave the rest of the page alone
- :wheelchair: &nbsp;Opens as a modal dialog that takes focus and gives it back when it closes
- :mouse2: &nbsp;<kbd>Ctrl</kbd> + `Mousewheel` or `Trackpad Pinch` to zoom
- :mag_right: &nbsp;Double/Single-tap or double/single-click to zoom in/out
Expand Down Expand Up @@ -149,6 +149,11 @@ The lightbox opens as a modal dialog with `role="dialog"` and `aria-modal="true"
- Give each button that you render a text label or an `aria-label`. An icon alone gives a screen reader nothing to announce.
- Elements that you add to `<body>` after the lightbox opens, such as a menu that a header button portals to `<body>`, stay usable. Elements that were in `<body>` before it opened stay inert until it closes.

The lightbox handles <kbd>&leftarrow;</kbd>, <kbd>&rightarrow;</kbd>, and <kbd>Esc</kbd> only while focus is inside it, or while the modal lightbox is open and nothing has focus, as after a focused Next button turns disabled on the last image. Text fields and selects inside it keep their arrow, <kbd>Home</kbd>, and <kbd>End</kbd> keys. While the modal lightbox is open, the keys that scroll a page don't scroll the page behind it when pressed in the lightbox.

- To keep the lightbox open when a control inside it handles <kbd>Esc</kbd>, call `event.preventDefault()` in that control's `onKeyDown`.
- An `inline` carousel takes <kbd>&leftarrow;</kbd> and <kbd>&rightarrow;</kbd> only while focus is inside it. Render buttons with `renderPrevButton` and `renderNextButton`, so keyboard users can move focus there. A button that turns `disabled` while it has focus, as at the first or last image, drops focus to the page, and the carousel then takes no keys until focus is back inside it.

## Local Development

Clone the repo
Expand Down
38 changes: 38 additions & 0 deletions e2e/accessibility.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,16 @@ const openWithKeyboard = async (page: Page) => {
const focusIsInLightbox = (page: Page) =>
page.evaluate(() => Boolean(document.activeElement?.closest('[data-testid="lightbox-container"]')));

/** Pages to the last image with Enter on Next, which turns disabled while it has focus */
const pressNextToTheEnd = async (page: Page) => {
await openWithKeyboard(page);
await page.getByRole('button', { name: 'Next' }).focus();
await page.keyboard.press('Enter');
await page.keyboard.press('Enter');
await settle(page);
expect(await shownImage(page)).toBe('Image 5');
};

test.describe('with a keyboard', () => {
test.skip(({ isMobile }) => isMobile, 'Keyboard input');

Expand Down Expand Up @@ -73,6 +83,34 @@ test.describe('with a keyboard', () => {
await expect(page.getByRole('button', { name: 'Open Image 3' })).toBeFocused();
});

test('← and Esc still work after the Next button that had focus turns disabled on the last image', async ({
page,
}) => {
await pressNextToTheEnd(page);

await page.keyboard.press('ArrowLeft');
await settle(page);
expect(await shownImage(page)).toBe('Image 4');

await page.keyboard.press('Escape');
await expect(page.getByTestId('lightbox-container')).toHaveCount(0);
await expect(page.getByRole('button', { name: 'Open Image 3' })).toBeFocused();
});

for (const key of ['Tab', 'Shift+Tab']) {
test(`${key} goes back into the lightbox after the Next button that had focus turns disabled`, async ({
browserName,
page,
}) => {
test.skip(browserName === 'webkit', 'WebKit on macOS tabs only to text fields by default');
await pressNextToTheEnd(page);

await page.keyboard.press(key);

expect(await focusIsInLightbox(page)).toBe(true);
});
}

test('an element portaled to the body after it opens can still be focused and clicked', async ({ page }) => {
await openHarness(page, 'closed&portalMenu');
await page.getByRole('button', { name: 'Open Image 3' }).click();
Expand Down
14 changes: 13 additions & 1 deletion e2e/inline.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,21 @@ test.describe('with a mouse and keyboard', () => {

await page.keyboard.press('PageDown');

test.fail();
await expect.poll(() => scrollY(page), { timeout: 1000 }).toBeGreaterThan(before);
});

test('→ pages while its Next button has focus, and does nothing while the page has it', async ({ page }) => {
const carousel = await openCarousel(page);

await page.keyboard.press('ArrowRight');
await settle(page);
expect((await calls(page)).onNext).toBe(0);

await carousel.getByRole('button', { name: 'Next' }).focus();
await page.keyboard.press('ArrowRight');
await settle(page);
expect((await calls(page)).onNext).toBe(1);
});
});

test.describe('on a touchscreen', () => {
Expand Down
13 changes: 11 additions & 2 deletions e2e/opening-and-closing.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,20 @@ test.describe('with a mouse and keyboard', () => {
await page.waitForTimeout(300);
const scrolled = await scrollY(page);

test.fail(true, 'Space is missing from the keys the lightbox blocks');
expect(scrolled).toBe(0);
});

test('scroll keys with Alt, Ctrl, or Meta do not scroll the page behind', async ({ page }) => {
await openHarness(page);

for (const key of ['Meta+ArrowDown', 'Alt+ArrowDown', 'Control+End']) {
await page.keyboard.press(key);
}
await page.waitForTimeout(300);

expect(await scrollY(page)).toBe(0);
});

test('a text field in the footer keeps its Home and End keys (#65)', async ({ page }) => {
await openHarness(page, 'footerInput');
const caption = page.getByRole('textbox', { name: 'Caption' });
Expand All @@ -137,7 +147,6 @@ test.describe('with a mouse and keyboard', () => {
await page.waitForTimeout(100);
const prevented = await page.evaluate(() => (window as unknown as { prevented: boolean[] }).prevented);

test.fail();
expect(prevented).toEqual([false, false]);
});
});
Expand Down
1 change: 0 additions & 1 deletion e2e/paging.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,6 @@ test.describe('the keyboard', () => {
await settle(page);
const { onNext } = await calls(page);

test.fail();
expect(onNext).toBe(0);
});
});
Expand Down
75 changes: 75 additions & 0 deletions src/__tests__/accessibility.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ const pressTab = (shiftKey = false) => {
// React calls a stable ref callback once, while it mounts the element, which is when it applies autoFocus
const focusOnMount = (element: HTMLElement | null) => element?.focus();

// A control that turns disabled or leaves the page while it has focus, as Next does on the last image,
// drops focus to <body>. Blurring the focused element gets there in jsdom.
const dropFocus = () => (document.activeElement as HTMLElement).blur();

const Page = ({ focusCloseOnMount = false }) => {
const [isOpen, setIsOpen] = useState(false);

Expand Down Expand Up @@ -379,4 +383,75 @@ describe('Tab', () => {

expect(last).toHaveFocus();
});

test('from <body> moves on from the dialog, so the browser goes to the first control', async () => {
await renderWithControls();
dropFocus();

expect(pressTab().defaultPrevented).toBe(false);

expect(document.activeElement).toBe(lightboxContainer());
});

test('from <body> with Shift goes to the last control', async () => {
await renderWithControls();
dropFocus();

expect(pressTab(true).defaultPrevented).toBe(true);

expect(screen.getByRole('button', { name: 'Last' })).toHaveFocus();
});
});

describe('a key pressed after focus falls to <body>', () => {
test.each([
['Esc asks to close', 'Escape', 'onClose'],
['← pages back', 'ArrowLeft', 'onPrev'],
['→ pages on', 'ArrowRight', 'onNext'],
] as const)('%s', async (_, key, callback) => {
const props = lightboxProps();
render(<Lightbox {...props} />);
await settle();
dropFocus();

pressKey(key);

expect(props[callback]).toHaveBeenCalledTimes(1);
});

test('moves focus back into the dialog', async () => {
render(<Lightbox {...lightboxProps()} />);
await settle();
dropFocus();
expect(document.activeElement).toBe(document.body);

pressKey('Shift');

expect(document.activeElement).toBe(lightboxContainer());
});

test('does not scroll the page behind', async () => {
render(<Lightbox {...lightboxProps()} />);
await settle();
dropFocus();

expect(pressKey('ArrowDown').defaultPrevented).toBe(true);
});

test('does nothing once the lightbox has closed', async () => {
const props = lightboxProps();
const { rerender } = render(<Lightbox {...props} />);
await settle();
rerender(
<Lightbox
{...props}
isOpen={false}
/>
);
await settle();

expect(pressKey('ArrowDown', document.body).defaultPrevented).toBe(false);
pressKey('Escape', document.body);
expect(props.onClose).not.toHaveBeenCalled();
});
});
13 changes: 8 additions & 5 deletions src/__tests__/devices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,9 +242,12 @@ export const safariPinch = async (target: Element, { at, scales }: { at: Point;
safariGesture(target, 'gestureend', at, scales[scales.length - 1]);
};

/** Presses and releases `key`. Returns false when the lightbox blocked the key's default action, such as scrolling. */
export const pressKey = (key: string, target: Element | Document = document) => {
const allowed = fireEvent.keyDown(target, { key });
fireEvent.keyUp(target, { key });
return allowed;
export const pressKey = (
key: string,
target: Element | Document = document.activeElement ?? document,
init: Omit<KeyboardEventInit, 'key'> = {}
) => {
const allowed = fireEvent.keyDown(target, { ...init, key });
fireEvent.keyUp(target, { ...init, key });
return { defaultPrevented: !allowed };
};
17 changes: 10 additions & 7 deletions src/__tests__/embedding.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
advance,
containerAppearance,
image,
lightboxContainer,
lightboxProps,
mockLayout,
pageOf,
Expand Down Expand Up @@ -178,21 +179,23 @@ describe('at the last image, as a looping gallery sees it', () => {
});
});

test('holding an arrow key pages once, when the key is released', () => {
test('holding an arrow key pages once, when it goes down', () => {
const props = lightboxProps({ currentIndex: 2 });
render(<Lightbox {...props} />);
const dialog = lightboxContainer();

for (let repeat = 0; repeat < 5; repeat += 1) {
fireEvent.keyDown(document, { key: 'ArrowRight', repeat: repeat > 0 });
fireEvent.keyDown(dialog, { key: 'ArrowRight' });
expect(props.onNext).toHaveBeenCalledTimes(1);
for (let repeat = 0; repeat < 4; repeat += 1) {
fireEvent.keyDown(dialog, { key: 'ArrowRight', repeat: true });
}
expect(props.onNext).not.toHaveBeenCalled();
fireEvent.keyUp(document, { key: 'ArrowRight' });
fireEvent.keyUp(dialog, { key: 'ArrowRight' });

expect(props.onNext).toHaveBeenCalledTimes(1);
});

describe('more than one lightbox on a page', () => {
test.fails('a key press pages at most one of two inline carousels (#65)', () => {
test('a key press pages at most one of two inline carousels (#65)', () => {
const firstNext = vi.fn();
const secondNext = vi.fn();
const first = lightboxProps({ inline: true, onNext: firstNext });
Expand All @@ -209,7 +212,7 @@ describe('more than one lightbox on a page', () => {
expect(firstNext.mock.calls.length + secondNext.mock.calls.length).toBeLessThanOrEqual(1);
});

test.fails('a key press pages only the open modal, not an inline carousel behind it (#65)', () => {
test('a key press pages only the open modal, not an inline carousel behind it (#65)', () => {
const carousel = lightboxProps({ inline: true });
const modal = lightboxProps();
render(
Expand Down
Loading
Loading