diff --git a/.changeset/lightbox-double-click-point.md b/.changeset/lightbox-double-click-point.md
new file mode 100644
index 0000000000000..e490269ff42f8
--- /dev/null
+++ b/.changeset/lightbox-double-click-point.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Lightbox: a double-click now zooms 2× about the clicked point instead of about the centre, and the next goes back; the keyboard keeps its 2× zoom about the centre.
+
+@vjeux
diff --git a/.changeset/lightbox-every-pointer.md b/.changeset/lightbox-every-pointer.md
new file mode 100644
index 0000000000000..f345d5effa7ce
--- /dev/null
+++ b/.changeset/lightbox-every-pointer.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Lightbox: a ctrl-wheel or a trackpad pinch now zooms a photo, and a trackpad's scroll pans a zoomed photo.
+
+@vjeux
diff --git a/.changeset/lightbox-touch-zoom.md b/.changeset/lightbox-touch-zoom.md
new file mode 100644
index 0000000000000..48b8cbc88a41d
--- /dev/null
+++ b/.changeset/lightbox-touch-zoom.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Lightbox's zoom now works under a finger the way the iOS Photos viewer does, on a phone, a tablet or a touchscreen laptop. Pinch the photo to zoom around your fingers, and move them to pan while you zoom. Past the zoom limits the photo gives way, then springs back when you let go, at the speed your fingers had. Double-tap zooms until the photo fills the screen, at least 2×, and keeps the tapped point under your finger; double-tap again to go back. On a phone or a tablet, a zoomed photo pans with momentum, stretches past its edges and settles back. The keyboard keeps the zoom it had, 2× about the centre, and keyboard panning now stops at the photo's edges instead of carrying it out of view. Every zoom, a double tap's and a key's included, settles on the same spring.
+
+The photo's stage fills the viewer. A pinch on the photo no longer zooms the page, and a pinch on the controls or caption still does. With `hasZoom` on, a tap on the dark area beside the photo closes the viewer after the double-tap wait instead of at once; a click still closes it at once. The zoom animations run on the compositor, so they stay smooth while the page is busy. With `hasZoom` off, nothing changes. With `hasZoom`, Close, Previous, Next and the counter sit on a dark translucent backing, so they stay readable over a zoomed photo.
+
+@vjeux
diff --git a/.changeset/uikit-zoom-media.md b/.changeset/uikit-zoom-media.md
index 56a1344254a9a..7004fc39b3576 100644
--- a/.changeset/uikit-zoom-media.md
+++ b/.changeset/uikit-zoom-media.md
@@ -2,6 +2,6 @@
'@astryxdesign/core': patch
---
-[chore] Internal: the UIKit constants table gains UIScrollView zooming for a photo viewer, measured on iOS 26.2. It holds the give past the zoom limits and Photos' aspect-fill double tap and maximum zoom. The zoom stage geometry that Lightbox's touch zoom is built on comes with it. Neither is exported from the package entry point, and no component reads them yet.
+[chore] Internal: the UIKit constants table gains UIScrollView zooming for a photo viewer, measured on iOS 26.2. It holds the give past the zoom limits and Photos' aspect-fill double tap and maximum zoom. The zoom stage geometry that Lightbox's touch zoom is built on comes with it. Neither is exported from the package entry point, and Lightbox's touch zoom reads them.
@vjeux
diff --git a/apps/storybook/stories/Lightbox.stories.tsx b/apps/storybook/stories/Lightbox.stories.tsx
index e3a6b88af81f4..840c9bdd7fb59 100644
--- a/apps/storybook/stories/Lightbox.stories.tsx
+++ b/apps/storybook/stories/Lightbox.stories.tsx
@@ -104,6 +104,48 @@ export const WithZoom: Story = {
},
};
+/** Zoom on a photo with a caption, which sits under the fitted photo. */
+export const ZoomWithCaption: Story = {
+ render: () => {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+
+
+ >
+ );
+ },
+};
+
+export const GalleryWithZoom: Story = {
+ render: () => {
+ const [isOpen, setIsOpen] = useState(false);
+ const [index, setIndex] = useState(0);
+ return (
+ <>
+
+
+ >
+ );
+ },
+};
+
export const WithCaption: Story = {
render: () => {
const [isOpen, setIsOpen] = useState(false);
diff --git a/docs/specs/components/Lightbox/Lightbox.spec.md b/docs/specs/components/Lightbox/Lightbox.spec.md
index 7410e4f2a5daa..de7078ef55cad 100644
--- a/docs/specs/components/Lightbox/Lightbox.spec.md
+++ b/docs/specs/components/Lightbox/Lightbox.spec.md
@@ -51,7 +51,8 @@ same actions.
presentation (FR5–FR10) and the touch exit (FR16) are the default
(`spec:AST-094` FR13). Under a fine pointer a mouse or pen drag pages and
closes the viewer, a ctrl-wheel or trackpad pinch over the photo zooms the
- photo instead of the page, a wheel pans a zoomed photo, and a double-click
+ photo instead of the page, a trackpad's scroll pans a zoomed photo, and a
+ double-click
zooms 2× about the clicked point instead of the centre (FR11). Preserved: a
click on the photo keeps the controls, the viewer opens at once under every
pointer and closes at once under a fine pointer, keyboard zoom stays 2× about
@@ -78,15 +79,11 @@ Consumer migration instructions belong in consumer docs and release notes.
The shipped Lightbox does not yet meet every requirement below. Each gap names
the requirement it misses and the person it affects.
-- **Touch presentation (FR5–FR10, FR12).** On a touch screen a pinch zooms the
- page instead of the photo, a double tap zooms 2× about the centre, and there
- is no swipe paging, drag or pinch to close, tap to hide the controls, or
- thumbnail transition.
+- **Touch presentation (FR7–FR10, FR12).** On a touch screen there is no swipe
+ paging, drag or pinch to close, tap to hide the controls, or thumbnail
+ transition.
- **Tab containment (FR4).** Tab from the viewer's last control can move focus
to the browser's own interface.
-- **Single-pointer pan (AR2, FR11).** A double-click zooms 2× about the centre,
- not about the clicked point, so a single-pointer user can reach a zoomed
- photo's edge only by dragging.
- **Zoom reset key (AR3).** `0` does not return a zoomed photo to its fitted
size.
- **Zoom announcement (AR4).** A zoom change announces "zoomed in" or "zoomed
@@ -95,10 +92,12 @@ the requirement it misses and the person it affects.
are sent from above the modal Lightbox renders, so they reach the page body
and a screen-reader user does not hear them while the viewer is open
(`spec:AST-086` FR14).
-- **Lightbox-owned pan listeners (FR14).** The pan drag registers Lightbox's
- own `window` pointer listeners instead of using the shared touch modules.
-- **Fine-pointer gestures (FR11).** A mouse drag on a fitted photo does
- nothing, a ctrl-wheel zooms the page, and a wheel does not pan a zoomed photo.
+- **Fine-pointer gestures (FR11).** FR11's drag paging (FR7) and drag to
+ close (FR8) are not built for a mouse, a pen or a trackpad: a drag on a
+ fitted photo does nothing.
+- **Double-click listener (FR14).** A mouse's or a pen's double-click reaches
+ the zoom through the stage's own `dblclick` listener, since only the browser
+ knows the system's double-click speed.
- **Touch exit (FR16).** On a touch screen the viewer disappears at once when
it closes.
@@ -143,7 +142,7 @@ FR21). Consumer props and usage remain documented in `Lightbox.doc.mjs`.
| FR8 | On a fitted image, a downward drag moves the photo with the finger, shrinks it, and fades the backdrop. The release decides once: a projected travel past the commit point closes the viewer and reports `onOpenChange(false)` at the lift; a release moving back springs back. Video is unchanged. | `spec:AST-094` FR36–FR40 | settled; implementation gap |
| FR9 | With `hasZoom`, a pinch in from the fitted size is a release decision: below the measured fraction of the fitted size the release closes the viewer; opening the fingers again by the measured amount before the lift is moving back and cancels. A pinch that starts zoomed in never closes the viewer. | `spec:AST-094` FR36, FR37 | settled; implementation gap |
| FR10 | With `hasZoom`, under a coarse pointer only, a tap on the photo fades the controls and caption and darkens the backdrop. While they are hidden, the next tap on the photo, a tap beside the photo, or a cancelled drag brings them back, and that tap beside the photo does not close the viewer (ORD3). AR5 governs keyboard and assistive-technology access while they are hidden. | `architecture:public-component-api` INV16 | settled; implementation gap |
-| FR11 | A mouse, a pen, and a trackpad also use FR7's drag paging, FR8's drag to close, a ctrl-wheel or trackpad pinch over the photo for FR6's zoom and FR9's close, and a wheel to pan a zoomed photo; over the photo these replace the browser's page zoom and scroll. A double-click zooms 2× about the clicked point. A click on the photo keeps the controls, and the viewer opens and closes at once. | `spec:AST-094` FR43; `spec:AST-017` FR59 | settled; implementation gap |
+| FR11 | A mouse, a pen, and a trackpad also use FR7's drag paging, FR8's drag to close, a ctrl-wheel or trackpad pinch over the photo for FR6's zoom and FR9's close, and a trackpad's scroll to pan a zoomed photo; a mouse wheel's notches leave it in place (`spec:AST-094` FR43); over the photo these replace the browser's page zoom and scroll. A double-click zooms 2× about the clicked point. A click on the photo keeps the controls, and the viewer opens and closes at once. | `spec:AST-094` FR43; `spec:AST-017` FR59 | settled; implementation gap |
| FR12 | Inside `experimental` only, under a coarse pointer, the photo grows out of its source when the viewer opens, and returns into it when it closes, on springs, `springs.settle` unless the motion table names another role, since Lightbox's main interaction is a gesture (`spec:AST-094` FR7, FR45): the element `experimental.sourceFor(index)` returns, else the opener when it shows a picture. A close reports `onOpenChange(false)` at the request; the viewer stays only until the photo lands. Pointer input during the entrance is held; keys and assistive technology stay live. Without `experimental`, opening is unchanged and closing plays FR16. | `spec:AST-017` FR21; `spec:AST-094` FR35 | settled; implementation gap |
| FR13 | `hasZoom={false}` turns off FR6, FR9, and FR10. FR7 and FR8 add to the buttons, keys, and Escape and remove none of them, so Lightbox takes no `presentation` prop. | `architecture:public-component-api` INV16 | settled |
| FR14 | Gestures, paging, motion, and reduced motion run through Core's one shared set of internal touch modules; Lightbox bundles no copy of a module's primitive and adds no gesture listener outside them. | `architecture:react-component-runtime` INV13 | settled; implementation gap |
@@ -237,6 +236,14 @@ under `spec:AST-020` FR1; reduced motion cites `design:reduced-motion`.
never covers it.
- **AR8 — The page keeps its own zoom (WCAG 2.2 1.4.4).** A pinch on the
controls or the caption zooms the page, so their text stays resizable (FR6).
+- **AR9 — The controls keep their contrast over a zoomed photo (WCAG 2.2
+ 1.4.3, 1.4.11).** With `hasZoom`, a photo can lie under Close, Previous,
+ Next, and the Counter, so each sits on a translucent backing: the buttons
+ keep 3:1 and the Counter's text 4.5:1 over any photo content beneath them.
+ In a zoomable Lightbox, Close, Previous, Next and the Counter sit on
+ Lightbox's own backing, and their icons and text use the on-dark colour, so
+ a theme's restyling of these controls can't remove their contrast over a
+ photo. Without `hasZoom`, the controls have no backing.
## Design relationships
@@ -314,26 +321,27 @@ a decision that they must remain unthemeable.
## Verification map
-| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
-| ------------------- | ----------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |
-| FR1 | `Lightbox.test.tsx` render, gallery, caption, media, and zoom suites | Single image, gallery edges, caption, video | Removing a documented part fails existing role, content, media, or navigation assertions. | `audit:Lightbox/anatomy` |
-| FR2 | Source inspection and `themingTargets.test.ts` | Viewer overlay, Media, Caption, and Counter | Removing the root target or documenting an unshipped child target fails evidence or inventory. | `audit:Lightbox/theming` |
-| FR3 | Source inspection plus Button and IconButton public composition | Close and gallery navigation controls | Re-owning a control surface requires the delegated owner and this map to change. | `audit:Lightbox/theming` |
-| FR4, AR3 | Browser keyboard test: Tab and Shift+Tab at both ends, Escape, arrows in LTR and RTL, `+`, `-`, `0`, close focus | Single image, gallery, zoomed image, removed opener | Focus leaving the viewer, a key without its action, or focus not returning to a connected opener fails. | `audit:Lightbox/accessibility` |
-| AR3 | `Lightbox.test.tsx` "Lightbox unmounting while open" suite | Viewer rendered only while open and removed by the page, with the opener still on the page; a page control that removes it keeps its focus; StrictMode | Focus left on the page body after an open viewer unmounts fails. | `audit:Lightbox/accessibility` |
-| FR5–FR10 | Interaction tests on synthetic touch streams with explicit timestamps; Reduce Motion; a busy main thread | Below and past each commit point; a release moving back; a drag on a video's frame and on its scrubber; a tap beside the photo with the controls hidden | A literal timing, a second decision during a settle, a gesture that pages while pinching, a drag on a video's frame that does not page, a drag on its controls that pages, or a tap beside the photo that closes while the controls are hidden fails. | `audit:Lightbox/touch` |
-| FR11 | Fine-pointer browser tests | Double-click, click on the photo, drag, ctrl-wheel, wheel | A double-click that does not zoom 2× about the point, a click that hides the controls, or a fine-pointer close that animates fails. | `audit:Lightbox/touch` |
-| FR6, AR1 | Touch test double-tapping a photo shaped like the screen and a landscape photo | 9:16 photo on a phone viewport, 3:2 photo | A double tap that zooms less than 2×, or not about the tapped point, fails. | `audit:Lightbox/touch` |
-| FR16 | Touch tests closing by Close, Escape, platform close, and a tap beside the photo with the controls shown; Reduce Motion | With and without `experimental`; controls shown and hidden | A touch close without the exit, a literal timing, input reaching the viewer during the exit, or a tap beside the photo that closes while the controls are hidden fails. | `audit:Lightbox/touch` |
-| FR12 | Opener and `sourceFor` tests, with and without `experimental` | Image opener, text-button opener, mid-entrance close | Any change to opening or closing without `experimental` fails. | `audit:Lightbox/touch` |
-| FR13 | `hasZoom={false}` tests under a coarse pointer | Gallery, single image | A zoom, a pinch close, or a tap that hides the controls with `hasZoom={false}` fails. | `audit:Lightbox/touch` |
-| FR14 | Source boundary check and bundle analysis | A page with Lightbox and another touch component | A second copy of a touch module or a Lightbox-owned gesture listener fails. | `audit:Lightbox/touch` |
-| AR1, AR2 | Browser tests that complete every gesture's action with one pointer and no drag | Zoom, page, close, reach a zoomed photo's edge | An action reachable only by a multipoint, path, or drag gesture fails. | `audit:Lightbox/accessibility` |
-| AR4 | Accessibility-tree and announcement tests | Open, page by button, key, and swipe, zoom by every input | A missing dialog name or `alt`, a repeated or missing position announcement, a message not exposed inside the open viewer, or a zoom without its level fails. | `audit:Lightbox/accessibility` |
-| AR5, AR7 | Browser tests with the controls hidden | Tab, assistive-technology focus, a key press, keyboard zoom | A hidden control that is unfocusable, absent from the tree, or still hidden when focused fails. | `audit:Lightbox/accessibility` |
-| AR6 | Reduced-motion tests under a coarse and a fine pointer | Transition, page settle, dismiss, pinch close, controls fade | Travel, scaling, or a cross-fade over 200 ms under reduced motion fails. | `audit:Lightbox/accessibility` |
-| AR8 | Touch test pinching on the controls and on the caption | Single image, gallery | A pinch on the controls or caption that does not zoom the page fails. | `audit:Lightbox/accessibility` |
-| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target | Missing, extra, prefixed, stale, or multiply assigned mappings fail repository validation. | `audit:Lightbox/theming` |
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ |
+| FR1 | `Lightbox.test.tsx` render, gallery, caption, media, and zoom suites | Single image, gallery edges, caption, video | Removing a documented part fails existing role, content, media, or navigation assertions. | `audit:Lightbox/anatomy` |
+| FR2 | Source inspection and `themingTargets.test.ts` | Viewer overlay, Media, Caption, and Counter | Removing the root target or documenting an unshipped child target fails evidence or inventory. | `audit:Lightbox/theming` |
+| FR3 | Source inspection plus Button and IconButton public composition | Close and gallery navigation controls | Re-owning a control surface requires the delegated owner and this map to change. | `audit:Lightbox/theming` |
+| FR4, AR3 | Browser keyboard test: Tab and Shift+Tab at both ends, Escape, arrows in LTR and RTL, `+`, `-`, `0`, close focus | Single image, gallery, zoomed image, removed opener | Focus leaving the viewer, a key without its action, or focus not returning to a connected opener fails. | `audit:Lightbox/accessibility` |
+| AR3 | `Lightbox.test.tsx` "Lightbox unmounting while open" suite | Viewer rendered only while open and removed by the page, with the opener still on the page; a page control that removes it keeps its focus; StrictMode | Focus left on the page body after an open viewer unmounts fails. | `audit:Lightbox/accessibility` |
+| FR5–FR10 | Interaction tests on synthetic touch streams with explicit timestamps; Reduce Motion; a busy main thread | Below and past each commit point; a release moving back; a drag on a video's frame and on its scrubber; a tap beside the photo with the controls hidden | A literal timing, a second decision during a settle, a gesture that pages while pinching, a drag on a video's frame that does not page, a drag on its controls that pages, or a tap beside the photo that closes while the controls are hidden fails. | `audit:Lightbox/touch` |
+| FR11 | Fine-pointer browser tests | Double-click, click on the photo, drag, ctrl-wheel, trackpad scroll, mouse wheel notch | A double-click that does not zoom 2× about the point, a click that hides the controls, a fine-pointer close that animates, or a mouse wheel's notch that pans a zoomed photo fails. | `audit:Lightbox/touch` |
+| FR6, AR1 | Touch test double-tapping a photo shaped like the screen and a landscape photo | 9:16 photo on a phone viewport, 3:2 photo | A double tap that zooms less than 2×, or not about the tapped point, fails. | `audit:Lightbox/touch` |
+| FR16 | Touch tests closing by Close, Escape, platform close, and a tap beside the photo with the controls shown; Reduce Motion | With and without `experimental`; controls shown and hidden | A touch close without the exit, a literal timing, input reaching the viewer during the exit, or a tap beside the photo that closes while the controls are hidden fails. | `audit:Lightbox/touch` |
+| FR12 | Opener and `sourceFor` tests, with and without `experimental` | Image opener, text-button opener, mid-entrance close | Any change to opening or closing without `experimental` fails. | `audit:Lightbox/touch` |
+| FR13 | `hasZoom={false}` tests under a coarse pointer | Gallery, single image | A zoom, a pinch close, or a tap that hides the controls with `hasZoom={false}` fails. | `audit:Lightbox/touch` |
+| FR14 | Source boundary check and bundle analysis | A page with Lightbox and another touch component | A second copy of a touch module or a Lightbox-owned gesture listener fails. | `audit:Lightbox/touch` |
+| AR1, AR2 | Browser tests that complete every gesture's action with one pointer and no drag | Zoom, page, close, reach a zoomed photo's edge | An action reachable only by a multipoint, path, or drag gesture fails. | `audit:Lightbox/accessibility` |
+| AR4 | Accessibility-tree and announcement tests | Open, page by button, key, and swipe, zoom by every input | A missing dialog name or `alt`, a repeated or missing position announcement, a message not exposed inside the open viewer, or a zoom without its level fails. | `audit:Lightbox/accessibility` |
+| AR5, AR7 | Browser tests with the controls hidden | Tab, assistive-technology focus, a key press, keyboard zoom | A hidden control that is unfocusable, absent from the tree, or still hidden when focused fails. | `audit:Lightbox/accessibility` |
+| AR6 | Reduced-motion tests under a coarse and a fine pointer | Transition, page settle, dismiss, pinch close, controls fade | Travel, scaling, or a cross-fade over 200 ms under reduced motion fails. | `audit:Lightbox/accessibility` |
+| AR8 | Touch test pinching on the controls and on the caption | Single image, gallery | A pinch on the controls or caption that does not zoom the page fails. | `audit:Lightbox/accessibility` |
+| AR9 | Touch test zooming a white photo under the controls and measuring their contrast in every shipped theme, butter's recoloured buttons and gothic's hovered Next included | Gallery with zoom: Close, Previous, Next, and the Counter, in each shipped theme | A control under 3:1, or the Counter's text under 4.5:1, over the zoomed light photo fails. | `audit:Lightbox/accessibility` |
+| Theming anatomy map | `scripts/check-knowledge.mjs` | Canonical anatomy and current target | Missing, extra, prefixed, stale, or multiply assigned mappings fail repository validation. | `audit:Lightbox/theming` |
## Decision log
diff --git a/packages/core/src/Lightbox/Lightbox.doc.mjs b/packages/core/src/Lightbox/Lightbox.doc.mjs
index 44e9cc55bcd82..65d06ec9af390 100644
--- a/packages/core/src/Lightbox/Lightbox.doc.mjs
+++ b/packages/core/src/Lightbox/Lightbox.doc.mjs
@@ -98,7 +98,7 @@ export const docs = {
name: 'hasZoom',
type: 'boolean',
description:
- 'Enable zoom on double-click, or Enter/Space/+/- via keyboard (images only). When zoomed, drag or use arrow keys to pan.',
+ 'Enable zoom (images only): pinch (or ctrl-wheel), or double-tap or double-click to zoom in at that point and back; Enter/Space/+/- zoom 2× about the centre and back. When zoomed, drag or scroll a trackpad to pan, or use arrow keys; on a phone or a tablet, the pan has momentum.',
default: 'false',
},
{
@@ -211,7 +211,8 @@ export const docsZh = {
{
name: 'hasZoom',
type: 'boolean',
- description: '启用双击缩放(仅图片)。缩放后可拖动平移。',
+ description:
+ '启用缩放(仅图片):双指捏合(或按住 Ctrl 滚动滚轮),或双点按、双击在该处放大并还原;Enter/Space/+/- 键以中心放大 2 倍并还原。缩放后可拖动或在触控板上滚动平移,或用方向键平移;在手机或平板上,平移带惯性。',
default: 'false',
},
{
@@ -296,7 +297,7 @@ export const docsDense = {
index: 'Current index in gallery mode.',
onIndexChange: 'Callback when gallery index changes.',
hasZoom:
- 'Enable zoom (double-click, Enter/Space, or +/-) and pan (drag or arrow keys) for images.',
+ 'Enable zoom (pinch or ctrl-wheel, double-tap or double-click, Enter/Space, or +/-) and pan (drag, trackpad scroll, 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 8e441bccb7abd..2a48f08d0242a 100644
--- a/packages/core/src/Lightbox/Lightbox.test.tsx
+++ b/packages/core/src/Lightbox/Lightbox.test.tsx
@@ -1,7 +1,7 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
-import {render, screen, fireEvent, waitFor} from '@testing-library/react';
+import {act, render, screen, fireEvent, waitFor} from '@testing-library/react';
import {Profiler, StrictMode, useState} from 'react';
import {Lightbox} from './Lightbox';
import {getFocusableElements} from '../hooks/useFocusTrap';
@@ -30,6 +30,74 @@ function politeRegion(): HTMLElement | null {
return document.querySelector('[data-astryx-live-region="polite"]');
}
+/**
+ * jsdom has no layout, so give the zoom stage what a browser measures. The
+ * stage is 400 × 600, with a landscape photo fitted 400 × 200 at its vertical
+ * centre. Filling the stage zooms that photo 3×. Returns the undo.
+ */
+function stubStageLayout(): () => void {
+ const undo: (() => void)[] = [];
+ const define = (
+ proto: object,
+ key: string,
+ get: (element: HTMLElement) => number,
+ ) => {
+ const original = Object.getOwnPropertyDescriptor(proto, key);
+ Object.defineProperty(proto, key, {
+ configurable: true,
+ get(this: HTMLElement) {
+ return get(this);
+ },
+ });
+ undo.push(() => {
+ if (original) {
+ Object.defineProperty(proto, key, original);
+ } else {
+ Reflect.deleteProperty(proto, key);
+ }
+ });
+ };
+ const isPhoto = (element: Element) => element instanceof HTMLImageElement;
+ const isStage = (element: Element) =>
+ element.querySelector(':scope > img') != null;
+ define(HTMLElement.prototype, 'offsetWidth', element =>
+ isPhoto(element) ? 400 : 0,
+ );
+ define(HTMLElement.prototype, 'offsetHeight', element =>
+ isPhoto(element) ? 200 : 0,
+ );
+ define(Element.prototype, 'clientWidth', element =>
+ isStage(element) ? 400 : 0,
+ );
+ define(Element.prototype, 'clientHeight', element =>
+ isStage(element) ? 600 : 0,
+ );
+ return () => undo.reverse().forEach(restore => restore());
+}
+
+/** A phone: the primary pointer is coarse, so the touch layer is on. Returns the undo. */
+function stubCoarsePointer(): () => void {
+ const original = window.matchMedia;
+ window.matchMedia = (query: string) => ({
+ matches: query === '(pointer: coarse)',
+ media: query,
+ onchange: null,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ addListener: () => {},
+ removeListener: () => {},
+ dispatchEvent: () => false,
+ });
+ return () => {
+ window.matchMedia = original;
+ };
+}
+
+/** The photo's inline `translate` and `scale`, as the zoom stage wrote them. */
+function photoTransform(img: HTMLElement): {translate: string; scale: string} {
+ return {translate: img.style.translate, scale: img.style.scale};
+}
+
// Both position messages, supplied by the test. Overriding the pair means an
// assertion also proves which of the two keys the component reached for.
const POSITION_MESSAGES = {
@@ -527,6 +595,13 @@ describe('Lightbox', () => {
{src: '/b.jpg', alt: 'Image B'},
{src: '/c.jpg', alt: 'Image C'},
];
+ let restoreLayout: () => void = () => {};
+ beforeEach(() => {
+ restoreLayout = stubStageLayout();
+ });
+ afterEach(() => {
+ restoreLayout();
+ });
function zoomTarget(): HTMLElement {
return screen.getByRole('button', {name: 'Zoom'});
@@ -612,24 +687,53 @@ describe('Lightbox', () => {
const dialog = document.querySelector('dialog')!;
fireEvent.keyDown(zoomTarget(), {key: 'Enter'});
const img = screen.getByAltText('Image B');
- expect(img.getAttribute('style') ?? '').toContain('translate(0px, 0px)');
+ // Lightbox's released zoom: 2× about the stage's centre, so 800 × 400
+ // with its centre on the stage's centre. Filling the stage would take
+ // 3× for this photo.
+ expect(photoTransform(img)).toEqual({
+ translate: '-200px -100px',
+ scale: '2 2',
+ });
// 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)',
- );
+ expect(photoTransform(img).translate).toBe('-250px -100px');
+ // At 400 px the photo is shorter than the 600 px stage, so it stays
+ // centred vertically.
fireEvent.keyDown(dialog, {key: 'ArrowDown'});
- expect(img.getAttribute('style') ?? '').toContain(
- 'translate(-25px, -25px)',
- );
+ expect(photoTransform(img).translate).toBe('-250px -100px');
fireEvent.keyDown(dialog, {key: 'ArrowLeft'});
fireEvent.keyDown(dialog, {key: 'ArrowUp'});
- expect(img.getAttribute('style') ?? '').toContain('translate(0px, 0px)');
+ expect(photoTransform(img).translate).toBe('-200px -100px');
expect(onIndexChange).not.toHaveBeenCalled();
});
+ it('stops panning at the edges of the photo', () => {
+ render(
+ {}}
+ media={{src: '/photo.jpg', alt: 'Photo'}}
+ hasZoom
+ />,
+ );
+ const dialog = document.querySelector('dialog')!;
+ fireEvent.keyDown(dialog, {key: '+'});
+ const img = screen.getByAltText('Photo');
+ for (let i = 0; i < 12; i++) {
+ fireEvent.keyDown(dialog, {key: 'ArrowLeft'});
+ }
+ // The photo's left edge rests on the stage's left edge, no gap: on main
+ // the arrows could carry the photo out of view.
+ expect(photoTransform(img).translate).toBe('0px -100px');
+ for (let i = 0; i < 24; i++) {
+ fireEvent.keyDown(dialog, {key: 'ArrowRight'});
+ }
+ // 800 px wide on a 400 px stage: its right edge on the stage's.
+ expect(photoTransform(img).translate).toBe('-400px -100px');
+ });
+
it('navigates the gallery with arrows when not zoomed, even with hasZoom', () => {
const onIndexChange = vi.fn();
render(
@@ -665,9 +769,7 @@ describe('Lightbox', () => {
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(photoTransform(img).translate).toBe('-250px -100px');
expect(onIndexChange).not.toHaveBeenCalled();
});
@@ -747,6 +849,37 @@ describe('Lightbox', () => {
});
describe('backdrop dismiss', () => {
+ it('closes on a click on the strip a raised caption leaves below the stage', () => {
+ const onOpenChange = vi.fn();
+ render(
+ ,
+ );
+ // The media group: the stage, then the caption's place below it. A
+ // mouse's click there is below the raised caption.
+ const group = screen.getByText('A caption').parentElement!;
+ fireEvent.click(group, {detail: 1, clientY: 590});
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it('without zoom, leaves a click beside a narrower caption alone', () => {
+ const onOpenChange = vi.fn();
+ render(
+ ,
+ );
+ // The media group hugs its media and caption, as before.
+ fireEvent.click(screen.getByText('A caption').parentElement!);
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
+
it('calls onOpenChange(false) when the dark area around the media is clicked', () => {
const onOpenChange = vi.fn();
render(
@@ -780,7 +913,612 @@ describe('Lightbox', () => {
});
});
+describe('Lightbox gestures for a mouse and a pen (spec:AST-094 FR43)', () => {
+ // Gestures attach for every pointer. A mouse's or a pen's double-click
+ // zooms 2×, and a zoomed photo pans once the pan begins.
+ let restoreLayout: () => void = () => {};
+ beforeEach(() => {
+ restoreLayout = stubStageLayout();
+ });
+ afterEach(() => {
+ restoreLayout();
+ });
+
+ /** A pointer event as a browser sends it, at `time` (ms). */
+ function pointer(
+ type: 'pointerdown' | 'pointermove' | 'pointerup',
+ target: Element,
+ pointerType: 'mouse' | 'pen',
+ x: number,
+ y: number,
+ time: number,
+ ): void {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ const fields: Record = {
+ pointerType,
+ pointerId: pointerType === 'pen' ? 7 : 1,
+ isPrimary: true,
+ button: 0,
+ buttons: type === 'pointerup' ? 0 : 1,
+ clientX: x,
+ clientY: y,
+ timeStamp: time,
+ };
+ for (const [key, value] of Object.entries(fields)) {
+ Object.defineProperty(event, key, {value});
+ }
+ act(() => {
+ target.dispatchEvent(event);
+ });
+ }
+
+ /** Two clicks `gapMs` apart, then the browser's dblclick. */
+ function doubleClick(
+ target: Element,
+ pointerType: 'mouse' | 'pen',
+ x: number,
+ y: number,
+ gapMs = 80,
+ ): void {
+ const t0 = performance.now();
+ pointer('pointerdown', target, pointerType, x, y, t0);
+ pointer('pointerup', target, pointerType, x, y, t0 + 40);
+ pointer('pointerdown', target, pointerType, x, y, t0 + 40 + gapMs);
+ pointer('pointerup', target, pointerType, x, y, t0 + 80 + gapMs);
+ act(() => {
+ target.dispatchEvent(
+ new MouseEvent('dblclick', {bubbles: true, clientX: x, clientY: y}),
+ );
+ });
+ }
+
+ /** A finger's double tap, on a phone (a coarse primary pointer). */
+ function fingerDoubleTap(target: Element, x: number, y: number): void {
+ const t0 = performance.now();
+ const at = (type: string, down: boolean, time: number) => {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ const entry = {identifier: 1, clientX: x, clientY: y, target};
+ Object.defineProperty(event, 'touches', {value: down ? [entry] : []});
+ Object.defineProperty(event, 'changedTouches', {value: [entry]});
+ Object.defineProperty(event, 'timeStamp', {value: time});
+ act(() => {
+ target.dispatchEvent(event);
+ });
+ };
+ at('touchstart', true, t0);
+ at('touchend', false, t0 + 40);
+ at('touchstart', true, t0 + 120);
+ at('touchend', false, t0 + 160);
+ }
+
+ function renderPhoto() {
+ const view = render(
+ {}}
+ media={{src: '/photo.jpg', alt: 'Photo'}}
+ hasZoom
+ />,
+ );
+ return {
+ view,
+ stage: screen.getByRole('button', {name: 'Zoom'}),
+ img: screen.getByAltText('Photo'),
+ };
+ }
+
+ it('zooms a mouse double-click 2× about the clicked point, and back', async () => {
+ const {stage, img} = renderPhoto();
+ // Filling the viewer would take 3×. The clicked photo point stays under
+ // the pointer, and the photo stays centred on the axis it fits.
+ doubleClick(stage, 'mouse', 20, 220);
+ expect(photoTransform(img)).toEqual({
+ translate: '-20px -100px',
+ scale: '2 2',
+ });
+ expect(stage).toHaveAttribute('aria-pressed', 'true');
+ // The next double-click reads where the photo shows: let the zoom land.
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 400));
+ });
+ doubleClick(stage, 'mouse', 20, 220);
+ expect(stage).toHaveAttribute('aria-pressed', 'false');
+ });
+
+ it('zooms a slow double-click too, as the browser reports it', () => {
+ const {stage, img} = renderPhoto();
+ // 600 ms between the clicks: past UIKit's 350 ms tap interval, inside a
+ // system's slower double-click setting.
+ doubleClick(stage, 'mouse', 20, 220, 600);
+ expect(photoTransform(img)).toEqual({
+ translate: '-20px -100px',
+ scale: '2 2',
+ });
+ });
+
+ it("zooms a finger's double tap to fill the viewer, about the tapped point", () => {
+ const restoreCoarse = stubCoarsePointer();
+ try {
+ const {stage, img} = renderPhoto();
+ fingerDoubleTap(stage, 20, 220);
+ expect(photoTransform(img)).toEqual({
+ translate: '-40px -200px',
+ scale: '3 3',
+ });
+ } finally {
+ restoreCoarse();
+ }
+ });
+
+ it('zooms a pen double-click 2× too', () => {
+ const {stage, img} = renderPhoto();
+ doubleClick(stage, 'pen', 200, 300);
+ expect(photoTransform(img).scale).toBe('2 2');
+ expect(stage).toHaveAttribute('aria-pressed', 'true');
+ });
+
+ it('pans a zoomed photo under a mouse drag from its first move, with the grab cursor', async () => {
+ const {stage, img} = renderPhoto();
+ fireEvent.keyDown(document.querySelector('dialog')!, {key: '+'});
+ // A drag starts where the photo shows: let the zoom's spring come to
+ // rest first.
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 1500));
+ });
+ const t0 = performance.now();
+ pointer('pointerdown', stage, 'mouse', 200, 300, t0);
+ // The press holds the photo where it shows, so the drag moves from there.
+ const from = photoTransform(img).translate;
+ const [fromX, fromY] = from.split(' ').map(parseFloat);
+ const moved = () => {
+ const [x, y] = photoTransform(img).translate.split(' ').map(parseFloat);
+ return {x: x - fromX, y: y - fromY};
+ };
+ // A finger's 10 px begin threshold does not apply: 2 px already pans.
+ pointer('pointermove', stage, 'mouse', 198, 300, t0 + 16);
+ expect(moved().x).toBeCloseTo(-2, 5);
+ expect(moved().y).toBeCloseTo(0, 5);
+ expect(stage).toHaveAttribute('data-zoom-dragging');
+ pointer('pointermove', stage, 'mouse', 170, 300, t0 + 32);
+ expect(moved().x).toBeCloseTo(-30, 5);
+ pointer('pointerup', stage, 'mouse', 170, 300, t0 + 48);
+ expect(stage).not.toHaveAttribute('data-zoom-dragging');
+ });
+
+ it('leaves the viewer open on a caption click after a zoomed drag from above the photo', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ ,
+ );
+ const dialog = document.querySelector('dialog')!;
+ const stage = screen.getByRole('button', {name: 'Zoom'});
+ fireEvent.keyDown(dialog, {key: '+'});
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 400));
+ });
+ // A zoomed drag from above the fitted photo: its own click is ignored.
+ const t0 = performance.now();
+ pointer('pointerdown', stage, 'mouse', 200, 50, t0);
+ pointer('pointermove', stage, 'mouse', 180, 50, t0 + 16);
+ pointer('pointerup', stage, 'mouse', 180, 50, t0 + 32);
+ fireEvent.click(stage, {clientX: 180, clientY: 50, detail: 1});
+ fireEvent.keyDown(dialog, {key: '-'});
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 400));
+ });
+ // Each caption click reads its own press, not the drag's.
+ const caption = screen.getByText('A caption');
+ for (const at of [t0 + 1000, t0 + 2000]) {
+ pointer('pointerdown', caption, 'mouse', 200, 300, at);
+ pointer('pointerup', caption, 'mouse', 200, 300, at + 40);
+ fireEvent.click(caption, {clientX: 200, clientY: 300, detail: 1});
+ }
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
+
+ it('starts no pan for a mouse drag on a fitted photo, so its click above the photo closes', () => {
+ const onOpenChange = vi.fn();
+ render(
+ ,
+ );
+ const stage = screen.getByRole('button', {name: 'Zoom'});
+ // From the photo's middle to above it, far past a finger's threshold.
+ const t0 = performance.now();
+ pointer('pointerdown', stage, 'mouse', 200, 300, t0);
+ pointer('pointermove', stage, 'mouse', 200, 250, t0 + 16);
+ pointer('pointermove', stage, 'mouse', 200, 50, t0 + 32);
+ pointer('pointerup', stage, 'mouse', 200, 50, t0 + 48);
+ fireEvent.click(stage, {clientX: 200, clientY: 50, detail: 1});
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it('leaves the viewer open on a mouse click on the zoomed photo above its fitted box', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ ,
+ );
+ const dialog = document.querySelector('dialog')!;
+ const stage = screen.getByRole('button', {name: 'Zoom'});
+ fireEvent.keyDown(dialog, {key: '+'});
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 400));
+ });
+ // The zoomed photo spreads over the stage, past its fitted box.
+ const img = screen.getByAltText('Photo');
+ img.getBoundingClientRect = () => ({
+ x: -200,
+ y: -100,
+ left: -200,
+ top: -100,
+ right: 600,
+ bottom: 300,
+ width: 800,
+ height: 400,
+ toJSON: () => ({}),
+ });
+ const t0 = performance.now();
+ pointer('pointerdown', stage, 'mouse', 200, 50, t0);
+ pointer('pointerup', stage, 'mouse', 200, 50, t0 + 40);
+ fireEvent.click(stage, {clientX: 200, clientY: 50, detail: 1});
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
+
+ it('closes on the first click above the photo after a zoomed drag, as main does', async () => {
+ const onOpenChange = vi.fn();
+ render(
+ ,
+ );
+ const dialog = document.querySelector('dialog')!;
+ const stage = screen.getByRole('button', {name: 'Zoom'});
+ fireEvent.keyDown(dialog, {key: '+'});
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 400));
+ });
+ // A zoomed drag, whose own click the stage keeps.
+ const t0 = performance.now();
+ pointer('pointerdown', stage, 'mouse', 200, 300, t0);
+ pointer('pointermove', stage, 'mouse', 180, 300, t0 + 16);
+ pointer('pointerup', stage, 'mouse', 180, 300, t0 + 32);
+ fireEvent.click(stage, {clientX: 180, clientY: 300, detail: 1});
+ expect(onOpenChange).not.toHaveBeenCalled();
+ // A new press on the dark area above starts a new click, which closes.
+ const container =
+ screen.getByText('A caption').parentElement!.parentElement!;
+ pointer('pointerdown', container, 'mouse', 200, 10, t0 + 1000);
+ pointer('pointerup', container, 'mouse', 200, 10, t0 + 1040);
+ fireEvent.click(container, {clientX: 200, clientY: 10, detail: 1});
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+});
+
+describe('Lightbox double-click under the touch layer', () => {
+ let restoreLayout: () => void = () => {};
+ const originalMatchMedia = window.matchMedia;
+ beforeEach(() => {
+ restoreLayout = stubStageLayout();
+ window.matchMedia = (query: string) => ({
+ matches: query === '(pointer: coarse)',
+ media: query,
+ onchange: null,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ addListener: () => {},
+ removeListener: () => {},
+ dispatchEvent: () => false,
+ });
+ });
+ afterEach(() => {
+ restoreLayout();
+ window.matchMedia = originalMatchMedia;
+ });
+
+ it("leaves a finger's double-click to the touch layer's recognizers", () => {
+ render(
+ {}}
+ media={{src: '/photo.jpg', alt: 'Photo'}}
+ hasZoom
+ />,
+ );
+ const stage = screen.getByRole('button', {name: 'Zoom'});
+ const down = new Event('pointerdown', {bubbles: true, cancelable: true});
+ Object.defineProperty(down, 'pointerType', {value: 'touch'});
+ Object.defineProperty(down, 'button', {value: 0});
+ act(() => {
+ stage.dispatchEvent(down);
+ stage.dispatchEvent(
+ new MouseEvent('dblclick', {bubbles: true, clientX: 200, clientY: 300}),
+ );
+ });
+ expect(stage).toHaveAttribute('aria-pressed', 'false');
+ });
+});
+
+describe('Lightbox touch zoom (synthetic touches)', () => {
+ let restoreLayout: () => void = () => {};
+ const originalMatchMedia = window.matchMedia;
+ beforeEach(() => {
+ restoreLayout = stubStageLayout();
+ // A phone: the primary pointer is coarse, so the touch layer is on.
+ window.matchMedia = (query: string) => ({
+ matches: query === '(pointer: coarse)',
+ media: query,
+ onchange: null,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ addListener: () => {},
+ removeListener: () => {},
+ dispatchEvent: () => false,
+ });
+ });
+ afterEach(() => {
+ restoreLayout();
+ window.matchMedia = originalMatchMedia;
+ });
+
+ interface Contact {
+ id: number;
+ x: number;
+ y: number;
+ }
+
+ /** A touch event as a browser sends it: who is down, and who changed. */
+ function touch(
+ type: 'touchstart' | 'touchmove' | 'touchend',
+ target: Element,
+ down: Contact[],
+ changed: Contact[],
+ time: number,
+ ): void {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ const entry = (contact: Contact) => ({
+ identifier: contact.id,
+ clientX: contact.x,
+ clientY: contact.y,
+ target,
+ });
+ Object.defineProperty(event, 'touches', {value: down.map(entry)});
+ Object.defineProperty(event, 'changedTouches', {value: changed.map(entry)});
+ Object.defineProperty(event, 'timeStamp', {value: time});
+ act(() => {
+ target.dispatchEvent(event);
+ });
+ }
+
+ /** A finger's pointerdown, which a browser sends before its touchstart. */
+ function fingerDown(target: Element, x: number, y: number): void {
+ const event = new Event('pointerdown', {bubbles: true, cancelable: true});
+ const fields = {pointerType: 'touch', pointerId: 2, isPrimary: true};
+ for (const [key, value] of Object.entries({
+ ...fields,
+ button: 0,
+ buttons: 1,
+ clientX: x,
+ clientY: y,
+ })) {
+ Object.defineProperty(event, key, {value});
+ }
+ act(() => {
+ target.dispatchEvent(event);
+ });
+ }
+
+ it('reports a tap beside the photo to the newest onOpenChange', async () => {
+ // The stage's gestures read the props of the latest render, so a parent's
+ // new callback is the one a tap beside the photo reaches.
+ const first = vi.fn();
+ const second = vi.fn();
+ const photo = {src: '/photo.jpg', alt: 'Photo'};
+ const view = render(
+ ,
+ );
+ view.rerender(
+ ,
+ );
+ const stage = screen.getByRole('button', {name: 'Zoom'});
+ // Above the photo, which the stage centres at its fitted size.
+ const finger: Contact = {id: 6, x: 200, y: 50};
+ const t0 = performance.now();
+ touch('touchstart', stage, [finger], [finger], t0);
+ touch('touchend', stage, [], [finger], t0 + 40);
+ // A single tap waits out a double tap's interval.
+ await waitFor(() => expect(second).toHaveBeenCalledWith(false));
+ expect(first).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['a fitted photo', false],
+ ['a zoomed photo', true],
+ ])(
+ 'ignores a finger’s first tap on the strip after a finger drag on %s, as before',
+ async (_, isZoomedFirst) => {
+ const onOpenChange = vi.fn();
+ render(
+ ,
+ );
+ const stage = screen.getByRole('button', {name: 'Zoom'});
+ if (isZoomedFirst) {
+ fireEvent.keyDown(document.querySelector('dialog')!, {key: '+'});
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 400));
+ });
+ }
+ // A finger drag on the photo, which fires no click.
+ let finger: Contact = {id: 5, x: 200, y: 300};
+ touch('touchstart', stage, [finger], [finger], 1000);
+ for (let i = 1; i <= 6; i++) {
+ finger = {...finger, x: finger.x - 10};
+ touch('touchmove', stage, [finger], [finger], 1000 + i * 16);
+ }
+ touch('touchend', stage, [], [finger], 1000 + 7 * 16);
+ const group = screen.getByText('A caption').parentElement!;
+ const tapStrip = () => {
+ fingerDown(group, 200, 590);
+ fireEvent.click(group, {clientX: 200, clientY: 590, detail: 1});
+ };
+ // The first tap on the strip below the stage only clears the flag.
+ tapStrip();
+ expect(onOpenChange).not.toHaveBeenCalled();
+ tapStrip();
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ },
+ );
+
+ it('keeps panning with the finger left down after a pinch, without a jump', () => {
+ render(
+ {}}
+ media={{src: '/photo.jpg', alt: 'Photo'}}
+ hasZoom
+ />,
+ );
+ const stage = screen.getByRole('button', {name: 'Zoom'});
+ const img = screen.getByAltText('Photo');
+ const x = () => parseFloat(photoTransform(img).translate || '0');
+ // Two fingers land on the photo, spread (100 → 140 px) and drift left
+ // together (the midpoint 200 → 180).
+ let a: Contact = {id: 1, x: 150, y: 300};
+ let b: Contact = {id: 2, x: 250, y: 300};
+ touch('touchstart', stage, [a], [a], 0);
+ touch('touchstart', stage, [a, b], [b], 0);
+ for (let i = 1; i <= 10; i++) {
+ a = {...a, x: 150 - 4 * i};
+ b = {...b, x: 250};
+ touch('touchmove', stage, [a, b], [a, b], i * 16);
+ }
+ const scaled = parseFloat(photoTransform(img).scale);
+ expect(scaled).toBeGreaterThan(1.2);
+ // The right finger lifts: nothing moves.
+ const beforeLift = x();
+ touch('touchend', stage, [a], [b], 11 * 16);
+ expect(x()).toBeCloseTo(beforeLift, 6);
+ // The left finger drags on 40 px: the photo follows it 1:1, zoom kept.
+ for (let i = 1; i <= 8; i++) {
+ a = {...a, x: a.x - 5};
+ touch('touchmove', stage, [a], [a], (11 + i) * 16);
+ }
+ expect(x()).toBeCloseTo(beforeLift - 40, 6);
+ expect(parseFloat(photoTransform(img).scale)).toBeCloseTo(scaled, 6);
+ touch('touchend', stage, [], [a], 20 * 16);
+ });
+
+ it("takes a caption off the photo from a pinch's first move", () => {
+ render(
+ {}}
+ media={{src: '/photo.jpg', alt: 'Photo', caption: 'A caption'}}
+ hasZoom
+ />,
+ );
+ const stage = screen.getByRole('button', {name: 'Zoom'});
+ const caption = screen.getByText('A caption');
+ // Fitted, the caption is raised by the stage's free space below the
+ // photo: (600 - 200) / 2.
+ expect(caption.style.translate).toBe('0 -200px');
+ let a: Contact = {id: 1, x: 150, y: 300};
+ let b: Contact = {id: 2, x: 250, y: 300};
+ touch('touchstart', stage, [a], [a], 0);
+ touch('touchstart', stage, [a, b], [b], 0);
+ for (let i = 1; i <= 4; i++) {
+ a = {...a, x: 150 - 6 * i};
+ b = {...b, x: 250 + 6 * i};
+ touch('touchmove', stage, [a, b], [a, b], i * 16);
+ }
+ // Both fingers are still down, and the photo spreads over the stage.
+ expect(
+ parseFloat(photoTransform(screen.getByAltText('Photo')).scale),
+ ).toBeGreaterThan(1);
+ expect(caption.style.translate).toBe('');
+ touch('touchend', stage, [a], [b], 5 * 16);
+ touch('touchend', stage, [], [a], 6 * 16);
+ });
+
+ it('frees the pan once a pinch that outlived its photo ends', async () => {
+ const lightbox = (src: string) => (
+ {}}
+ media={{src, alt: 'Photo'}}
+ hasZoom
+ />
+ );
+ const view = render(lightbox('/first.jpg'));
+ const stage = screen.getByRole('button', {name: 'Zoom'});
+ // Two fingers pinch the first photo, and another photo arrives while
+ // they are down. Then they lift.
+ let a: Contact = {id: 1, x: 150, y: 300};
+ const b: Contact = {id: 2, x: 250, y: 300};
+ touch('touchstart', stage, [a], [a], 0);
+ touch('touchstart', stage, [a, b], [b], 0);
+ for (let i = 1; i <= 6; i++) {
+ a = {...a, x: 150 - 4 * i};
+ touch('touchmove', stage, [a, b], [a, b], i * 16);
+ }
+ view.rerender(lightbox('/second.jpg'));
+ touch('touchend', stage, [a], [b], 7 * 16);
+ touch('touchend', stage, [], [a], 8 * 16);
+ // A double tap zooms the new photo, and a drag then pans it 1:1.
+ const tapAt = {id: 3, x: 200, y: 300};
+ touch('touchstart', stage, [tapAt], [tapAt], 400);
+ touch('touchend', stage, [], [tapAt], 440);
+ touch('touchstart', stage, [tapAt], [tapAt], 520);
+ touch('touchend', stage, [], [tapAt], 560);
+ const img = screen.getByAltText('Photo');
+ expect(parseFloat(photoTransform(img).scale)).toBeGreaterThan(1.5);
+ // The drag reads where the photo shows: let the zoom's spring land.
+ await act(async () => {
+ await new Promise(resolve => setTimeout(resolve, 900));
+ });
+ const x = () => parseFloat(photoTransform(img).translate || '0');
+ const before = x();
+ let finger: Contact = {id: 4, x: 200, y: 300};
+ touch('touchstart', stage, [finger], [finger], 900);
+ for (let i = 1; i <= 8; i++) {
+ finger = {...finger, x: finger.x - 5};
+ touch('touchmove', stage, [finger], [finger], 900 + i * 16);
+ }
+ expect(x()).toBeLessThan(before - 20);
+ touch('touchend', stage, [], [finger], 900 + 9 * 16);
+ });
+});
+
describe('Lightbox zoom reset timing', () => {
+ let restoreLayout: () => void = () => {};
+ beforeEach(() => {
+ restoreLayout = stubStageLayout();
+ });
+ afterEach(() => {
+ restoreLayout();
+ });
+
it('shows the next image unzoomed in the same commit that changes it', () => {
const media = [
{src: '/a.jpg', alt: 'Image A'},
@@ -815,6 +1553,13 @@ describe('Lightbox zoom reset timing', () => {
'aria-pressed',
'false',
);
+ // The photo element is reused for the next image, and it is back at the
+ // fitted size before that image paints. An animator at rest at the
+ // identity leaves the element's own style.
+ expect(photoTransform(screen.getByAltText('Image B'))).toEqual({
+ translate: '',
+ scale: '',
+ });
});
});
diff --git a/packages/core/src/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsx
index a7df25271aa05..86e9b22856a2a 100644
--- a/packages/core/src/Lightbox/Lightbox.tsx
+++ b/packages/core/src/Lightbox/Lightbox.tsx
@@ -5,13 +5,17 @@
/**
* @file Lightbox.tsx
* @input Uses React, native dialog, StyleX, IconButton, theme tokens, layerTextReset, layerStructureReset,
- * isRtlElement (gallery arrow keys follow the rendered direction)
+ * and isRtlElement (gallery arrow keys follow the rendered direction). The
+ * zoom uses useZoomCore and useZoomStage
* @output Exports Lightbox component, LightboxProps, LightboxMedia
* @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/Lightbox.test.tsx (tests for new/changed behavior)
+ * - /packages/core/src/Lightbox/useZoomCore.ts (the zoom stage for every pointer)
+ * - /packages/core/src/Lightbox/useZoomStage.ts (the gestures, for every pointer)
+ * - /packages/core/src/Lightbox/__tests__/LightboxZoom.interaction.browser.spec.ts (touch zoom proofs)
* - /packages/core/src/Lightbox/index.ts (exports if types change)
* - /packages/core/src/Layer/useLayerDismissal.ts (dismissal stack)
* - /apps/storybook/stories/Lightbox.stories.tsx (storybook stories)
@@ -25,15 +29,26 @@ import {
useRef,
useState,
type MouseEvent as ReactMouseEvent,
+ type PointerEvent as ReactPointerEvent,
+ type ComponentProps,
type ReactNode,
} from 'react';
import * as stylex from '@stylexjs/stylex';
-import {colorVars, spacingVars, typeScaleVars} from '../theme/tokens.stylex';
+import type {StyleXStyles} from '@stylexjs/stylex';
+import {
+ colorVars,
+ focusVars,
+ radiusVars,
+ 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 {useAttachment} from '../hooks/useAttachment';
+import {observeResize} from '../utils/sharedResizeObserver';
import {mergeProps, rtlStyles} from '../utils';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
@@ -50,6 +65,9 @@ import {useFocusRegionContainment} from '../hooks/useFocusTrap';
import {useMergedRefs} from '../hooks/useMergedRefs';
import {isRtlElement} from '../hooks/isRtlElement';
+import {useZoomCore} from './useZoomCore';
+import {useZoomStage} from './useZoomStage';
+import {useTouchPresentation} from '../utils/touchPresentation';
import {
registerEnglishFallback,
useComponentTranslator,
@@ -113,8 +131,12 @@ export interface LightboxProps extends BaseProps {
*/
onIndexChange?: (index: number) => void;
/**
- * Enable zoom on double-click, or Enter/Space/`+`/`-` via keyboard
- * (images only). When zoomed, drag or use arrow keys to pan.
+ * Enable zoom (images only). A pinch or a ctrl-wheel zooms about the
+ * fingers or the pointer. A double tap fills the viewer and a double-click
+ * zooms 2×, about that point, and the next goes back. Enter, Space, `+` and
+ * `-` zoom 2× about the centre and back. When zoomed, drag or scroll a
+ * trackpad to pan, or use the arrow keys. On a phone or a tablet, the pan
+ * has momentum. The gestures work for every pointer.
* @default false
*/
hasZoom?: boolean;
@@ -129,6 +151,9 @@ export interface LightboxProps extends BaseProps {
// Styles
// =============================================================================
+/** Set on the stage while a mouse or a pen hovers over the fitted photo. */
+const OVER_PHOTO_ATTRIBUTE = 'data-lightbox-over-photo';
+
const styles = stylex.create({
dialog: {
position: 'fixed',
@@ -169,6 +194,28 @@ const styles = stylex.create({
maxHeight: '100%',
overflow: 'hidden',
},
+ // A zoomable photo's stage fills the viewer for every pointer, as a photo
+ // viewer's zooming scroll view does. A zoomed photo uses the whole screen,
+ // and a pinch can start anywhere around it. Only a zoom target does this:
+ // around any other item, a tap on the dark area still closes the viewer.
+ mediaGroupZoom: {
+ alignSelf: 'stretch',
+ flexGrow: 1,
+ minHeight: 0,
+ },
+ imageWrapperFill: {
+ alignSelf: 'stretch',
+ flexGrow: 1,
+ flexShrink: 1,
+ flexBasis: 0,
+ },
+ // The filling stage's group clips, so its focus ring sits inside its edge.
+ imageWrapperFocusInset: {
+ outlineOffset: {
+ default: '0',
+ ':focus-visible': `calc(-1 * ${focusVars['--focus-outline-width']})`,
+ },
+ },
imageWrapper: {
display: 'flex',
alignItems: 'center',
@@ -178,22 +225,27 @@ const styles = stylex.create({
userSelect: 'none',
minHeight: 0,
},
+ // The stage's own pinch, pan and double tap take every touch on it,
+ // whatever the primary pointer. Only the stage does: the controls and
+ // caption leave pinch-zoom to the page. It fills the viewer (mediaGroupZoom,
+ // imageWrapperFill).
+ imageWrapperZoomTarget: {
+ touchAction: 'none',
+ },
+ // A fitted photo's zoom-in cursor shows only over the photo, where the
+ // stage sets OVER_PHOTO_ATTRIBUTE. Beside it, a click closes the viewer.
imageWrapperZoomable: {
cursor: {
- default: 'zoom-in',
- '@media (hover: hover)': 'zoom-in',
+ default: 'default',
+ ':is([data-lightbox-over-photo])': 'zoom-in',
':is(:disabled,[aria-disabled="true"])': 'default',
},
},
imageWrapperZoomed: {
cursor: {
default: 'grab',
- ':is(:disabled,[aria-disabled="true"])': 'default',
- },
- },
- imageWrapperDragging: {
- cursor: {
- default: 'grabbing',
+ // ZOOM_DRAGGING_ATTRIBUTE, set by the stage while a drag moves the photo.
+ ':is([data-zoom-dragging])': 'grabbing',
':is(:disabled,[aria-disabled="true"])': 'default',
},
},
@@ -202,15 +254,9 @@ const styles = stylex.create({
maxHeight: '100%',
objectFit: 'contain',
pointerEvents: 'none',
- transitionProperty: 'transform',
- transitionDuration: {
- default: '200ms',
- '@media (prefers-reduced-motion: reduce)': '0ms',
- },
- transitionTimingFunction: 'ease-out',
- },
- imageDragging: {
- transitionProperty: 'none',
+ // The zoom stage scales the photo about its top-left corner and moves it
+ // with the individual `scale` and `translate` properties.
+ transformOrigin: '0 0',
},
video: {
maxWidth: '100%',
@@ -238,11 +284,10 @@ const styles = stylex.create({
navButton: {
position: 'absolute',
top: '50%',
- // The individual `translate` property, not `transform`: this style now
- // lands on the Button root, and a `transform` here replaces the Button's
- // own transform rules — measured: the `scale(0.98)` press feedback stops
- // firing. `translate` composes with them, reproducing exactly what the
- // removed wrapper element did (wrapper translated, button scaled).
+ // The individual `translate` property, not `transform`. This style lands
+ // on the Button root, or on its backing with zoom. A `transform` on the
+ // Button root would replace its own transform rules: measured, the
+ // `scale(0.98)` press feedback stops firing. `translate` composes with them.
translate: '0 -50%',
zIndex: 1,
},
@@ -264,12 +309,22 @@ const styles = stylex.create({
controlButton: {
color: colorVars['--color-on-dark'],
},
-});
-
-const dynamicStyles = stylex.create({
- imageTransform: (transform: string) => ({
- transform,
- }),
+ // With zoom a photo can lie under the controls. Lightbox's own translucent
+ // backing keeps them readable over any photo: 3:1 for the buttons, 4.5:1
+ // for the counter's text. A theme restyles the buttons, not the backing.
+ controlBacking: {
+ display: 'inline-flex',
+ backgroundColor: `color-mix(in srgb, ${colorVars['--color-on-light']} 75%, transparent)`,
+ borderRadius: radiusVars['--radius-full'],
+ },
+ controlIcon: {
+ color: colorVars['--color-on-dark'],
+ },
+ counterBacking: {
+ backgroundColor: `color-mix(in srgb, ${colorVars['--color-on-light']} 75%, transparent)`,
+ borderRadius: radiusVars['--radius-full'],
+ paddingInline: spacingVars['--spacing-2'],
+ },
});
/**
@@ -289,13 +344,18 @@ const KEYBOARD_PAN_OFFSETS: Record = {
/**
* 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; 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).
+ * Supports single image and gallery modes. In gallery mode, it provides
+ * 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 like a photo viewer. A pinch or a ctrl-wheel zooms
+ * about the fingers or the pointer, gives past the limits and springs back. A
+ * double tap or a double-click zooms in at that point and back. Enter or
+ * Space on the image, and `+` or `-` from the keyboard, zoom too. When zoomed,
+ * a drag or a trackpad's scroll pans. On a phone or a tablet, the pan has
+ * momentum and a rubber band at the edges. The arrow keys pan a zoomed photo
+ * and navigate the gallery otherwise.
*
* Uses the native `