Skip to content

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

TypeScript

feat(Lightbox): swipe between gallery photos like Photos (#8197)

Christopher Chedeau88ba279085c2
diff --git a/.changeset/lightbox-gallery-paging.md b/.changeset/lightbox-gallery-paging.md
new file mode 100644
index 0000000000..5fc684cece
--- /dev/null
+++ b/.changeset/lightbox-gallery-paging.md
@@ -0,0 +1,11 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] A Lightbox gallery now pages the way the iOS Photos viewer does. On a phone or tablet, drag or flick between items: the row follows your finger, and the release lands on the next or previous item, one at most. A gap of 40 px separates the items while they move. A zoomed photo pans with your finger until it reaches its edge; a new drag from that edge moves to the next item. A photo you leave zoomed returns to its fitted size once the gallery rests. Under a finger, the previous and next buttons and the arrow keys slide to the item instead of swapping it in place.
+
+Each item's caption moves with its item, right under its photo. `onIndexChange` also reports a swipe.
+
+Lightbox now loads its touch code with it, as Toast and Slider do. Its import grows from 51.4 KB to 99.6 KB gzip with the zoom and paging beneath, mostly shared touch modules that a page loads once; Lightbox's own code adds 14.1 KB minified.
+
+@vjeux
diff --git a/.changeset/pager-settle-tempo.md b/.changeset/pager-settle-tempo.md
new file mode 100644
index 0000000000..efd2890ab0
--- /dev/null
+++ b/.changeset/pager-settle-tempo.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] A page that a swipe releases now settles at the theme's `tempo`, as the rest of its motion does: in a `Carousel` given `hasSnap={useSnapPaging()}`, and in a `Lightbox` gallery. At the default tempo the settle is unchanged.
+
+@vjeux
diff --git a/apps/storybook/stories/Lightbox.stories.tsx b/apps/storybook/stories/Lightbox.stories.tsx
index 840c9bdd7f..0080f9daab 100644
--- a/apps/storybook/stories/Lightbox.stories.tsx
+++ b/apps/storybook/stories/Lightbox.stories.tsx
@@ -126,6 +126,11 @@ export const ZoomWithCaption: Story = {
},
};
+/**
+ * A gallery a phone can page through. Drag or flick between photos, with
+ * Photos' 40 pt gap. Pinch or double-tap a photo to zoom, and drag a zoomed
+ * photo to its edge before the next drag pages.
+ */
export const GalleryWithZoom: Story = {
render: () => {
const [isOpen, setIsOpen] = useState(false);
@@ -146,6 +151,64 @@ export const GalleryWithZoom: Story = {
},
};
+/**
+ * A gallery whose captions differ in length: the photo keeps one box
+ * whichever pages, and so whichever captions, are rendered.
+ */
+export const GalleryWithCaptions: Story = {
+ render: () => {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button onClick={() => setIsOpen(true)}>
+ Open gallery with captions
+ </button>
+ <Lightbox
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ media={[
+ {
+ ...GALLERY_MEDIA[0],
+ caption:
+ 'A winding path through the forest, past the old mill and down to the river, where the trail turns back toward the village',
+ },
+ GALLERY_MEDIA[1],
+ GALLERY_MEDIA[3],
+ {...GALLERY_MEDIA[2], caption: 'Golden hour'},
+ ]}
+ hasZoom
+ />
+ </>
+ );
+ },
+};
+
+/**
+ * A controlled gallery whose parent keeps its index, paging only with its own
+ * buttons, say while a change is confirmed. A swipe returns to the photo the
+ * parent shows.
+ */
+export const GalleryKeepsIndex: Story = {
+ render: () => {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button onClick={() => setIsOpen(true)}>
+ Open gallery that keeps its photo
+ </button>
+ <Lightbox
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ media={GALLERY_MEDIA}
+ index={0}
+ onIndexChange={() => {}}
+ hasZoom
+ />
+ </>
+ );
+ },
+};
+
export const WithCaption: Story = {
render: () => {
const [isOpen, setIsOpen] = useState(false);
@@ -167,6 +230,34 @@ export const WithCaption: Story = {
},
};
+/**
+ * A gallery with a video between two photos. A drag on the video's frame
+ * pages, and a drag that starts on its controls stays the video's.
+ */
+export const GalleryWithVideo: Story = {
+ render: () => {
+ const [isOpen, setIsOpen] = useState(false);
+ return (
+ <>
+ <button onClick={() => setIsOpen(true)}>Open gallery with video</button>
+ <Lightbox
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ media={[
+ GALLERY_MEDIA[0],
+ {
+ src: 'https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm',
+ alt: 'Flower blooming',
+ type: 'video',
+ },
+ GALLERY_MEDIA[1],
+ ]}
+ />
+ </>
+ );
+ },
+};
+
export const Video: Story = {
render: () => {
const [isOpen, setIsOpen] = useState(false);
diff --git a/docs/specs/AST-094-touch-presentations/spec.md b/docs/specs/AST-094-touch-presentations/spec.md
index 9e5974cee0..068161c04f 100644
--- a/docs/specs/AST-094-touch-presentations/spec.md
+++ b/docs/specs/AST-094-touch-presentations/spec.md
@@ -230,12 +230,14 @@ a measured, sourced difference exists.
component's own record states which of its roles a gesture drives.
The pager's measured settle after a release (DEC-25) is not an exit, so FR4's
- exception does not cover it. Implementation gap: it plays UIKit's measured
- settle without a named role, and it doesn't yet follow `tempo` or `character`
- (usePager calls solvePaging with no theme input). Implementation gap: the
- pager is a gesture component, so its animated scroll to a page that the
- program asks for settles on the pager's spring from rest (FR45); today it
- plays a 300 ms scroll on a sinusoidal curve.
+ exception does not cover it. It follows the theme's `tempo`: a settle from
+ rest keeps its shape and takes tempo times as long, and a release still
+ starts at 96 % of the finger's speed, as at tempo 1. Implementation gap: it
+ plays UIKit's measured settle without a named role, and it doesn't yet
+ follow `character`.
+ Implementation gap: the pager is a gesture component, so its animated scroll
+ to a page that the program asks for settles on the pager's spring from rest
+ (FR45); today it plays a 300 ms scroll on a sinusoidal curve.
Implementation gap: the sheet picker wheel's snap rate (UIKit's measured
picker deceleration) plays from an internal constant and is not yet a named
@@ -1050,7 +1052,7 @@ Motion that FR45 moves, by component. Each component's record carries its own li
| FR6 pager | Unit and browser tests of a pager's settle start | releases just under and over 225 pt/s; a catch mid-settle; a programmatic page change mid-settle | a release under the floor whose settle starts moving, a release over it whose settle starts from rest, a catch that loses the on-screen velocity, or a programmatic page change mid-settle that starts from rest fails; a page change during a drag starts from rest |
| FR6 starved | Switch frame proofs on a starved main thread (4 workers on 2 cores); unit tests of a retarget on a settle tail and a rebase toward a new rest | a second tap mid-travel, with frames read late or its lift handled 100 ms late; a first frame committed late; a retarget once the thumb is still; a value change mid-slide, whose rebase moves the travel whole | a jump out of a thumb that is still fails; a value change mid-slide shows no step; another retarget's step within the browser's commit delay is the known limit |
| FR7, FR8 | Component browser tests and storyboards with and without Reduce Motion | entrance, exit, move; a drag and its lift under Reduce Motion; a tap-, key- and program-started close of a sheet and the Lightbox | a missing exit, any travel, scale or spring under Reduce Motion other than a coast after a throw and its settle at an edge (`design:reduced-motion` DR2), an opacity fade over 200 ms, or a tap-, key- or program-started close of a gesture component on the exit curve instead of its spring, fails |
-| FR45 | Browser tests with a mouse, a pen, a trackpad and a finger at each `tempo` bound and each `character`, and with Reduce Motion | a tap, a click, a key and a programmatic change on a Switch, a menu, an alert, a sheet and a ProgressBar under a fine and a coarse pointer; a drag release, a flick and a pinch on a Switch, a Slider, a sheet, a pager and a Lightbox photo under each pointer; a tap that continues as a drag | a tap, click, key or programmatic change in a tap-classified component that plays a measured role or a spring instead of the theme's duration and easing tokens, a touch tap-started move in a gesture or gesture-capable component on a curve instead of its spring, a click, a key or a value change on Switch or SegmentedControl without a touch presentation that leaves the theme's curve, a velocity-carrying release that settles from rest or on a curve, a gesture's spring that ignores `character` or `tempo`, or a part that follows one pointer and not another, fails; the pager's measured settle, which does not yet follow `tempo` or `character`, is a recorded implementation gap |
+| FR45 | Browser tests with a mouse, a pen, a trackpad and a finger at each `tempo` bound and each `character`, and with Reduce Motion | a tap, a click, a key and a programmatic change on a Switch, a menu, an alert, a sheet and a ProgressBar under a fine and a coarse pointer; a drag release, a flick and a pinch on a Switch, a Slider, a sheet, a pager and a Lightbox photo under each pointer; a tap that continues as a drag | a tap, click, key or programmatic change in a tap-classified component that plays a measured role or a spring instead of the theme's duration and easing tokens, a touch tap-started move in a gesture or gesture-capable component on a curve instead of its spring, a click, a key or a value change on Switch or SegmentedControl without a touch presentation that leaves the theme's curve, a velocity-carrying release that settles from rest or on a curve, a gesture's spring that ignores `character` or `tempo`, or a part that follows one pointer and not another, fails; the pager's measured settle, which does not yet follow `character`, is a recorded implementation gap |
| FR45 | Component source and token tests for a tap component's motion whose record names no step, with a platform measurement | a small anchored surface (a popover, a menu, a toggle, a row) and a full-screen surface (a Dialog, an AlertDialog), each with its own measurement; a tap component's overlay exit | a token cited as nearest to the measurement in the Storybook theme passes, and a tap component's overlay exit on `--duration-exit` passes; a token chosen by role alone, or nearest at Core's unthemed defaults, fails |
| FR45 | Browser frame capture of companion motion in a gesture and a tap component | a sheet's scrim, handle and content fade; a Lightbox's chrome fade; a menu's backdrop | a companion fade on its own duration fails; one driven by the main motion's progress or settle time passes |
| FR9, FR10 | Recognizer unit tests on synthetic streams and browser tests with real touch input | drag, second finger, pinch, page zoom, main-thread block | a second finger that breaks a drag, or a page pinch blocked other than by the author's `touch-action`, fails |
diff --git a/docs/specs/components/Lightbox/Lightbox.spec.md b/docs/specs/components/Lightbox/Lightbox.spec.md
index de7078ef55..0227e9719c 100644
--- a/docs/specs/components/Lightbox/Lightbox.spec.md
+++ b/docs/specs/components/Lightbox/Lightbox.spec.md
@@ -79,9 +79,13 @@ 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 (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.
+- **Touch presentation (FR8–FR10, FR12).** On a touch screen there is no drag
+ or pinch to close, tap to hide the controls, or thumbnail transition.
+- **Paging motion roles (FR5).** The page settle plays the pager's own UIKit
+ values, which the motion role table does not list as roles.
+- **Video controls (FR7).** A video's native controls are taken as a 48 px
+ band at its bottom edge, since browsers expose no control geometry; a
+ browser that places controls elsewhere pages from them.
- **Tab containment (FR4).** Tab from the viewer's last control can move focus
to the browser's own interface.
- **Zoom reset key (AR3).** `0` does not return a zoomed photo to its fitted
@@ -98,6 +102,9 @@ the requirement it misses and the person it affects.
- **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.
+- **Press tracker (FR14).** The viewer's own `pointerdown` handler records
+ each press's pointer type and point, which the browser's `dblclick` and
+ `click` do not carry, and clears the flag a drag leaves for its click.
- **Touch exit (FR16).** On a touch screen the viewer disappears at once when
it closes.
diff --git a/packages/core/src/Lightbox/Lightbox.doc.mjs b/packages/core/src/Lightbox/Lightbox.doc.mjs
index 65d06ec9af..d65e12d9b3 100644
--- a/packages/core/src/Lightbox/Lightbox.doc.mjs
+++ b/packages/core/src/Lightbox/Lightbox.doc.mjs
@@ -80,7 +80,7 @@ export const docs = {
// the description instead (#1645).
type: 'LightboxMedia | LightboxMedia[]',
description:
- "Media to display. Pass a single object for one item, or an array for gallery mode with prev/next navigation. Each item is {src: string, alt: string, caption?: ReactNode, type?: 'image' | 'video'}; type defaults to 'image', and zoom/pan is disabled for 'video'.",
+ "Media to display. Pass a single object for one item, or an array for gallery mode with prev/next navigation (on a phone or tablet, a swipe moves between items too). Each item is {src: string, alt: string, caption?: ReactNode, type?: 'image' | 'video'}; type defaults to 'image', and zoom/pan is disabled for 'video'.",
required: true,
},
{
@@ -92,7 +92,7 @@ export const docs = {
name: 'onIndexChange',
type: '(index: number) => void',
description:
- 'Callback when the gallery index changes via prev/next navigation.',
+ 'Callback when the gallery index changes: prev/next, the arrow keys, or a swipe.',
},
{
name: 'hasZoom',
@@ -128,7 +128,7 @@ export const docs = {
usage: {
anatomy,
description:
- 'A fullscreen overlay for viewing images and videos at full resolution. Supports single-item and gallery modes with prev/next navigation, optional zoom and pan for images, and native video controls.',
+ 'A fullscreen overlay for viewing images and videos at full resolution. Supports single-item and gallery modes with prev/next navigation and swiping, optional zoom and pan for images, and native video controls.',
bestPractices: [
{
guidance: true,
@@ -195,7 +195,7 @@ export const docsZh = {
name: 'media',
type: 'LightboxMedia | LightboxMedia[]',
description:
- "要显示的媒体。传入单个对象或数组(用于画廊模式的上一张/下一张导航)。每项为 {src, alt, caption?, type?: 'image' | 'video'};type 默认为 'image','video' 禁用缩放/平移。",
+ "要显示的媒体。传入单个对象或数组(用于画廊模式的上一张/下一张导航;在手机或平板上,滑动也可在各项之间切换)。每项为 {src, alt, caption?, type?: 'image' | 'video'};type 默认为 'image','video' 禁用缩放/平移。",
required: true,
},
{
@@ -228,7 +228,7 @@ export const docsZh = {
usage: {
anatomy,
description:
- 'A fullscreen overlay for viewing images and videos at full resolution. Supports single-item and gallery modes with prev/next navigation, optional zoom and pan for images, and native video controls.',
+ 'A fullscreen overlay for viewing images and videos at full resolution. Supports single-item and gallery modes with prev/next navigation and swiping, optional zoom and pan for images, and native video controls.',
bestPractices: [
{
guidance: true,
@@ -266,7 +266,7 @@ export const docsDense = {
usage: {
anatomy,
description:
- 'A fullscreen overlay for viewing images and videos at full resolution. Supports single-item and gallery modes with prev/next navigation, optional zoom and pan for images, and native video controls.',
+ 'A fullscreen overlay for viewing images and videos at full resolution. Supports single-item and gallery modes with prev/next navigation and swiping, optional zoom and pan for images, and native video controls.',
bestPractices: [
{guidance: true, description: 'Always provide alt text for every image.'},
{
@@ -295,7 +295,8 @@ export const docsDense = {
onOpenChange: 'Callback when open state changes.',
media: 'Single media object or array for gallery mode.',
index: 'Current index in gallery mode.',
- onIndexChange: 'Callback when gallery index changes.',
+ onIndexChange:
+ 'Callback when gallery index changes (buttons, keys or a swipe).',
hasZoom:
'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 a741f14375..6a7c6299c5 100644
--- a/packages/core/src/Lightbox/Lightbox.test.tsx
+++ b/packages/core/src/Lightbox/Lightbox.test.tsx
@@ -58,8 +58,12 @@ function stubStageLayout(): () => void {
});
};
const isPhoto = (element: Element) => element instanceof HTMLImageElement;
+ // The zoom stage: a single item's photo box, or a gallery page's.
const isStage = (element: Element) =>
- element.querySelector(':scope > img') != null;
+ element.hasAttribute('data-lightbox-page-media') ||
+ (element.getAttribute('role') === 'button' &&
+ element.getAttribute('aria-label') === 'Zoom' &&
+ element.querySelector('[data-lightbox-page]') == null);
define(HTMLElement.prototype, 'offsetWidth', element =>
isPhoto(element) ? 400 : 0,
);
@@ -109,6 +113,115 @@ const POSITION_MESSAGES = {
},
};
+/** A mouse press on `target` from `from` to `to`, as a browser sends it. */
+/** A client rectangle at a place, for a test that sets an element's box. */
+function rectAt(left: number, top: number, width: number, height: number) {
+ return {
+ x: left,
+ y: top,
+ left,
+ top,
+ right: left + width,
+ bottom: top + height,
+ width,
+ height,
+ toJSON: () => ({}),
+ };
+}
+
+/**
+ * Lays out a gallery's current page for a mouse's click: its photo's box,
+ * natural width and caption, and the viewer's width. jsdom lays out nothing.
+ */
+function layOutPage(
+ page: Element,
+ {
+ photo,
+ natural,
+ caption,
+ viewer,
+ }: {
+ photo: ReturnType<typeof rectAt>;
+ natural: number;
+ caption?: ReturnType<typeof rectAt>;
+ viewer: number;
+ },
+): void {
+ const define = (element: Element, values: Record<string, unknown>) => {
+ for (const [key, value] of Object.entries(values)) {
+ Object.defineProperty(element, key, {configurable: true, value});
+ }
+ };
+ const img = page.querySelector('img')!;
+ define(img, {
+ getBoundingClientRect: () => photo,
+ offsetHeight: photo.height,
+ naturalWidth: natural,
+ });
+ // The photo's own box hugs it without zoom.
+ define(img.parentElement!, {
+ getBoundingClientRect: () => photo,
+ clientHeight: photo.height,
+ clientWidth: photo.width,
+ });
+ const text = page.querySelector('[data-lightbox-caption]');
+ if (caption != null && text != null) {
+ define(text, {
+ getBoundingClientRect: () => caption,
+ offsetWidth: caption.width,
+ });
+ }
+ define(page.closest('[data-lightbox-page]')!.parentElement!.parentElement!, {
+ clientWidth: viewer,
+ });
+}
+
+function mousePress(
+ target: Element,
+ from: {x: number; y: number},
+ to: {x: number; y: number} = from,
+): void {
+ const send = (
+ type: string,
+ {x, y}: {x: number; y: number},
+ buttons: number,
+ ) => {
+ const event = new Event(type, {bubbles: true, cancelable: true});
+ for (const [key, value] of Object.entries({
+ pointerType: 'mouse',
+ pointerId: 1,
+ isPrimary: true,
+ button: 0,
+ buttons,
+ clientX: x,
+ clientY: y,
+ timeStamp: performance.now(),
+ })) {
+ Object.defineProperty(event, key, {value});
+ }
+ act(() => {
+ target.dispatchEvent(event);
+ });
+ };
+ send('pointerdown', from, 1);
+ if (to.x !== from.x || to.y !== from.y) {
+ send('pointermove', to, 1);
+ }
+ send('pointerup', to, 0);
+ // Then the click a mouse's press and release make.
+ act(() => {
+ target.dispatchEvent(
+ new MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ detail: 1,
+ clientX: to.x,
+ clientY: to.y,
+ }),
+ );
+ });
+}
+
describe('Lightbox', () => {
it('renders as a dialog element', () => {
render(
@@ -278,6 +391,290 @@ describe('Lightbox', () => {
expect(screen.getByAltText('Image B')).toBeInTheDocument();
});
+ it('renders the current item and its neighbours as pages, each with its own caption', () => {
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={media}
+ index={1}
+ />,
+ );
+ const pages = [
+ ...document.querySelectorAll<HTMLElement>('[data-lightbox-page]'),
+ ];
+ expect(pages).toHaveLength(3);
+ const current = pages.filter(page => page.hasAttribute('data-current'));
+ expect(current).toHaveLength(1);
+ expect(current[0]).toContainElement(screen.getByAltText('Image B'));
+ expect(current[0]).toHaveTextContent('Second');
+ // The neighbours are off screen: hidden from assistive technology.
+ for (const page of pages.filter(p => p !== current[0])) {
+ const img = page.querySelector('img');
+ expect(img).toHaveAttribute('aria-hidden', 'true');
+ expect(img).toHaveAttribute('alt', '');
+ }
+ expect(pages[0]).toHaveTextContent('First');
+ });
+
+ it('closes on a click beside the photo on a page', () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={onOpenChange}
+ media={media}
+ index={0}
+ />,
+ );
+ const current = document.querySelector('[data-current]')!;
+ mousePress(current.querySelector('[data-lightbox-page-media]')!, {
+ x: 20,
+ y: 20,
+ });
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it('closes on a mouse press beside the photo that moved past the tap limit', () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={onOpenChange}
+ media={media}
+ index={0}
+ />,
+ );
+ const pageMedia = document.querySelector(
+ '[data-current] [data-lightbox-page-media]',
+ )!;
+ // 60 px straight down: past the tap's 45 px limit. A mouse's click
+ // closes it, as on the backdrop, however far the press moved.
+ mousePress(pageMedia, {x: 100, y: 100}, {x: 100, y: 160});
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it('leaves the viewer open when the keyboard activates a caption link after a mouse press', () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={onOpenChange}
+ media={[
+ {src: '/a.jpg', alt: 'A', caption: <a href="#more">More</a>},
+ {src: '/b.jpg', alt: 'B'},
+ ]}
+ index={0}
+ />,
+ );
+ const link = screen.getByRole('link', {name: 'More'});
+ // A mouse press on the stage, then Enter on the caption's link: the
+ // browser clicks the link with no pointer (detail 0, at 0, 0).
+ const down = new Event('pointerdown', {bubbles: true, cancelable: true});
+ Object.defineProperty(down, 'pointerType', {value: 'mouse'});
+ act(() => {
+ link.dispatchEvent(down);
+ });
+ act(() => {
+ link.dispatchEvent(
+ new MouseEvent('click', {bubbles: true, cancelable: true, detail: 0}),
+ );
+ });
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
+
+ it('plays a video again when paging back to it, with hasAutoPlay', () => {
+ const play = vi
+ .spyOn(HTMLMediaElement.prototype, 'play')
+ .mockImplementation(async () => {});
+ try {
+ const withVideo = [
+ {src: '/a.jpg', alt: 'Image A'},
+ {src: '/clip.webm', alt: 'Clip', type: 'video' as const},
+ ];
+ const {rerender} = render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={withVideo}
+ index={0}
+ hasAutoPlay
+ />,
+ );
+ expect(play).not.toHaveBeenCalled();
+ rerender(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={withVideo}
+ index={1}
+ hasAutoPlay
+ />,
+ );
+ expect(play).toHaveBeenCalledTimes(1);
+ expect(play.mock.contexts[0]).toBe(
+ document.querySelector('[data-current] video'),
+ );
+ } finally {
+ play.mockRestore();
+ }
+ });
+
+ it('shows the last item as the current one for an index past the end', () => {
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={media}
+ index={media.length + 2}
+ />,
+ );
+ const photo = screen.getByAltText('Image C');
+ expect(photo).not.toHaveAttribute('aria-hidden');
+ const page = photo.closest('[data-lightbox-page]')!;
+ expect(page).toHaveAttribute('data-current');
+ expect(page).not.toHaveAttribute('inert');
+ expect(
+ screen.getByText(`${media.length} / ${media.length}`),
+ ).toBeTruthy();
+ });
+
+ it('pauses a playing video once the viewer moves to another item', () => {
+ const items = [
+ {src: '/clip.mp4', alt: 'A clip', type: 'video' as const},
+ {src: '/b.jpg', alt: 'Image B'},
+ ];
+ const {rerender} = render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={items}
+ index={0}
+ />,
+ );
+ const video = document.querySelector('video')!;
+ // Started by someone: playing, with its sound.
+ const pause = vi.fn();
+ video.pause = pause;
+ Object.defineProperty(video, 'paused', {
+ configurable: true,
+ get: () => pause.mock.calls.length > 0,
+ });
+ rerender(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={() => {}}
+ media={items}
+ index={1}
+ />,
+ );
+ // Still mounted as the pager's neighbour, and stopped.
+ expect(document.querySelector('video')).toBe(video);
+ expect(pause).toHaveBeenCalledTimes(1);
+ });
+
+ it('stays open on a click on the photo, with zoom off', () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={onOpenChange}
+ media={media}
+ index={0}
+ />,
+ );
+ const current = document.querySelector('[data-current]')!;
+ const box = current.querySelector<HTMLElement>(
+ '[data-lightbox-page-media]',
+ )!;
+ // The photo takes no pointer events: a press on it lands on its box.
+ layOutPage(current, {
+ photo: rectAt(100, 100, 400, 200),
+ natural: 400,
+ viewer: 1000,
+ });
+ mousePress(box, {x: 300, y: 200});
+ expect(onOpenChange).not.toHaveBeenCalled();
+ // Beside the photo, past its natural width, the click is the backdrop's.
+ mousePress(box, {x: 20, y: 200});
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it('closes on a mouse press beside the photo that is released on it', () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={onOpenChange}
+ media={media}
+ index={0}
+ />,
+ );
+ const current = document.querySelector('[data-current]')!;
+ layOutPage(current, {
+ photo: rectAt(100, 100, 400, 200),
+ natural: 400,
+ viewer: 1000,
+ });
+ // A press that starts on the backdrop closes, wherever it ends.
+ mousePress(
+ current.querySelector('[data-lightbox-page-media]')!,
+ {x: 20, y: 200},
+ {x: 300, y: 200},
+ );
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it("stays open on a mouse click beside a narrow photo, within its caption's width", () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={onOpenChange}
+ media={media}
+ index={0}
+ />,
+ );
+ const current = document.querySelector('[data-current]')!;
+ const box = current.querySelector('[data-lightbox-page-media]')!;
+ layOutPage(current, {
+ photo: rectAt(250, 100, 100, 300),
+ natural: 100,
+ caption: rectAt(100, 410, 400, 30),
+ viewer: 1000,
+ });
+ // The media is as wide as the caption here, so this point is on it.
+ mousePress(box, {x: 150, y: 250});
+ expect(onOpenChange).not.toHaveBeenCalled();
+ // Past the caption's width, the click is the backdrop's.
+ mousePress(box, {x: 50, y: 250});
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ it('stays open on a mouse click beside a large photo, level with it, since its media spans the viewer', () => {
+ const onOpenChange = vi.fn();
+ render(
+ <Lightbox
+ isOpen={true}
+ onOpenChange={onOpenChange}
+ media={media}
+ index={0}
+ />,
+ );
+ const current = document.querySelector('[data-current]')!;
+ // A photo wider than the viewer, shown at 400 px.
+ layOutPage(current, {
+ photo: rectAt(300, 100, 400, 200),
+ natural: 3000,
+ viewer: 1000,
+ });
+ mousePress(current.querySelector('[data-lightbox-page-media]')!, {
+ x: 990,
+ y: 200,
+ });
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
+
it('shows gallery counter', () => {
render(
<Lightbox
@@ -1089,6 +1486,24 @@ describe('Lightbox gestures for a mouse and a pen (spec:AST-094 FR43)', () => {
expect(stage).not.toHaveAttribute('data-zoom-dragging');
});
+ it('takes the zoom pan\u2019s begin threshold from the shared pan, with no pointerdown listener of its own on the stage', () => {
+ const added = vi.spyOn(EventTarget.prototype, 'addEventListener');
+ try {
+ const {stage} = renderPhoto();
+ // The gesture host's own press listener is passive. Any other press
+ // listener on the stage would be Lightbox's own.
+ const ownPress = added.mock.calls.filter(
+ ([type, , options], index) =>
+ added.mock.contexts[index] === stage &&
+ type === 'pointerdown' &&
+ !(typeof options === 'object' && options.passive === true),
+ );
+ expect(ownPress).toHaveLength(0);
+ } finally {
+ added.mockRestore();
+ }
+ });
+
it('leaves the viewer open on a caption click after a zoomed drag from above the photo', async () => {
const onOpenChange = vi.fn();
render(
@@ -1355,7 +1770,7 @@ describe('Lightbox touch zoom (synthetic touches)', () => {
['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',
+ 'closes on a finger’s tap on the strip after a finger drag on %s, once the drag’s flag is clear',
async (_, isZoomedFirst) => {
const onOpenChange = vi.fn();
render(
@@ -1386,9 +1801,10 @@ describe('Lightbox touch zoom (synthetic touches)', () => {
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.
+ // A zoomed drag's flag takes the first tap. A fitted photo's drag starts
+ // no zoom pan, since paging owns it, so it leaves no flag.
tapStrip();
- expect(onOpenChange).not.toHaveBeenCalled();
+ expect(onOpenChange).toHaveBeenCalledTimes(isZoomedFirst ? 0 : 1);
tapStrip();
expect(onOpenChange).toHaveBeenCalledWith(false);
},
diff --git a/packages/core/src/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsx
index 86e9b22856..0cefcc0600 100644
--- a/packages/core/src/Lightbox/Lightbox.tsx
+++ b/packages/core/src/Lightbox/Lightbox.tsx
@@ -6,7 +6,7 @@
* @file Lightbox.tsx
* @input Uses React, native dialog, StyleX, IconButton, theme tokens, layerTextReset, layerStructureReset,
* and isRtlElement (gallery arrow keys follow the rendered direction). The
- * zoom uses useZoomCore and useZoomStage
+ * zoom uses useZoomCore and useZoomStage, and a gallery pages with usePager
* @output Exports Lightbox component, LightboxProps, LightboxMedia
* @position Core implementation; consumed by index.ts
*
@@ -16,6 +16,7 @@
* - /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/__tests__/LightboxPaging.interaction.browser.spec.ts (gallery paging 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)
@@ -66,6 +67,11 @@ import {useFocusRegionContainment} from '../hooks/useFocusTrap';
import {useMergedRefs} from '../hooks/useMergedRefs';
import {isRtlElement} from '../hooks/isRtlElement';
import {useZoomCore} from './useZoomCore';
+import {usePager} from '../hooks/usePager';
+import {TapGestureRecognizer} from '../gestures/TapGestureRecognizer';
+import type {GestureTouch} from '../gestures/types';
+import {useGestureRecognizer} from '../gestures/useGestureRecognizer';
+import {zoomMedia} from '../motion/uikit/zoomMedia';
import {useZoomStage} from './useZoomStage';
import {useTouchPresentation} from '../utils/touchPresentation';
import {
@@ -127,7 +133,8 @@ export interface LightboxProps extends BaseProps<HTMLDialogElement> {
*/
defaultIndex?: number;
/**
- * Callback when the gallery index changes via prev/next navigation.
+ * Callback when the gallery index changes: the previous and next buttons,
+ * the arrow keys or a swipe.
*/
onIndexChange?: (index: number) => void;
/**
@@ -232,6 +239,73 @@ const styles = stylex.create({
imageWrapperZoomTarget: {
touchAction: 'none',
},
+ // In a gallery the photo rows take the stage's touches, for every pointer
+ // (as imageWrapperZoomTarget). A descendant cannot allow what an ancestor's
+ // `touch-action` rules out. So the track allows only the page's pinch-zoom,
+ // and a pinch on a caption still zooms the page. The pager's pan manages the
+ // stage's own `touch-action`.
+ trackZoomTarget: {
+ touchAction: 'pinch-zoom',
+ },
+ // A zoomable page's photo box fills the page above its caption, as a
+ // single item's stage does.
+ pageMediaZoomTarget: {
+ touchAction: 'none',
+ alignSelf: 'stretch',
+ flexGrow: 1,
+ flexShrink: 1,
+ flexBasis: 0,
+ },
+ // A gallery's stage is the pager's viewport: it fills the viewer on every
+ // presentation, so its pages have a size of their own.
+ mediaGroupGallery: {
+ alignSelf: 'stretch',
+ flexGrow: 1,
+ minHeight: 0,
+ },
+ imageWrapperGallery: {
+ alignSelf: 'stretch',
+ flexGrow: 1,
+ flexShrink: 1,
+ flexBasis: 0,
+ position: 'relative',
+ },
+ // The pages stack in the track's one cell, each offset by its relative
+ // inset.
+ track: {
+ position: 'absolute',
+ inset: 0,
+ display: 'grid',
+ gridTemplateColumns: '100%',
+ gridTemplateRows: '100%',
+ },
+ // One page per item, the stage's size, at index × (width + gap). A page
+ // lays out its photo and caption as a single item does: the caption right
+ // under the photo, and the pair centred. Each page has its own layer.
+ // Through a busy main thread, Mobile Safari moves the track but cannot
+ // paint what it had not painted. So a page that slides in must be painted
+ // whole before it moves.
+ page: {
+ position: 'relative',
+ gridArea: '1 / 1',
+ display: 'flex',
+ flexDirection: 'column',
+ alignItems: 'center',
+ justifyContent: 'center',
+ minHeight: 0,
+ minWidth: 0,
+ willChange: 'transform',
+ },
+ // A page's photo box: the zoom stage of the current page.
+ pageMedia: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ overflow: 'hidden',
+ minHeight: 0,
+ minWidth: 0,
+ maxWidth: '100%',
+ },
// 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: {
@@ -327,6 +401,12 @@ const styles = stylex.create({
},
});
+const pageStyles = stylex.create({
+ position: (index: number) => ({
+ insetInlineStart: `calc(${index} * (100% + ${zoomMedia.viewer.pageGap}px))`,
+ }),
+});
+
/**
* Pan distance (px) per arrow-key press while zoomed. Offsets move the
* viewport in the arrow's direction — pressing ArrowRight reveals content to
@@ -341,6 +421,9 @@ const KEYBOARD_PAN_OFFSETS: Record<string, [number, number]> = {
ArrowDown: [0, -KEYBOARD_PAN_STEP],
};
+/** The height of a video's native controls, px: no browser reports it. */
+const VIDEO_CONTROLS_BAND = 48;
+
/**
* A fullscreen overlay for viewing images at full resolution.
*
@@ -407,12 +490,15 @@ export function Lightbox({
useFocusRegionContainment(dialogRef, isOpen);
const containerRef = useRef<HTMLDivElement>(null);
const imageWrapperRef = useRef<HTMLDivElement>(null);
+ const trackRef = useRef<HTMLDivElement>(null);
+ // A gallery's zoom stage: the current page's photo box.
+ const pageMediaRef = useRef<HTMLDivElement>(null);
const triggerElementRef = useRef<Element | null>(null);
// Index state (controlled + uncontrolled)
const isControlled = controlledIndex !== undefined;
const [uncontrolledIndex, setUncontrolledIndex] = useState(defaultIndex);
- const index = isControlled ? controlledIndex : uncontrolledIndex;
+ const requestedIndex = isControlled ? controlledIndex : uncontrolledIndex;
const setIndex = useCallback(
(value: number) => {
@@ -435,10 +521,11 @@ export function Lightbox({
[media],
);
const isGallery = mediaArray.length > 1;
- const currentItem =
- mediaArray.length > 0
- ? mediaArray[Math.min(index, mediaArray.length - 1)]
- : null;
+ // The item shown, current in every respect (its page, the counter, the
+ // pager, the announcement): an index past either end shows the nearest
+ // item. A NaN index stays NaN (the viewed-item check below).
+ const index = Math.max(0, Math.min(requestedIndex, mediaArray.length - 1));
+ const currentItem = mediaArray.length > 0 ? mediaArray[index] : null;
const currentType = currentItem?.type ?? 'image';
const isVideo = currentType === 'video';
const canPrev = isGallery && index > 0;
@@ -479,7 +566,7 @@ export function Lightbox({
if (!indexChanged || !isOpen || !wasOpen) {
return;
}
- const item = mediaArray[Math.min(index, mediaArray.length - 1)];
+ const item = mediaArray[index];
const position = {index: index + 1, total: mediaArray.length};
announce(
item?.alt
@@ -488,6 +575,30 @@ export function Lightbox({
);
}, [index, isOpen, announce, mediaArray, t]);
+ // A video left on another page stops: the pager keeps the neighbours
+ // mounted, and a playing one would go on, with its sound, off screen. With
+ // `hasAutoPlay`, the video paged to plays again, as a newly shown one does.
+ useEffect(() => {
+ const container = containerRef.current;
+ if (container == null) {
+ return;
+ }
+ for (const video of container.querySelectorAll<HTMLVideoElement>(
+ '[data-lightbox-page]:not([data-current]) video',
+ )) {
+ if (!video.paused) {
+ video.pause();
+ }
+ }
+ const current = container.querySelector<HTMLVideoElement>(
+ '[data-lightbox-page][data-current] video',
+ );
+ if (hasAutoPlay && current != null && current.paused) {
+ // A browser can refuse playback without a user's gesture.
+ void current.play()?.catch(() => {});
+ }
+ }, [index, hasAutoPlay]);
+
// Open/close dialog. The dialog renders only with an item, so a viewer
// opened before its first item arrives opens when that item does.
const hasItem = currentItem != null;
@@ -562,56 +673,69 @@ export function Lightbox({
[handleClose, shouldDismissOnCloseRequest],
);
- // The last press's pointer type. A finger's double tap is the stage's own.
- // A mouse's or a pen's is the browser's `dblclick`.
+ // The last press's pointer type, which the browser's `dblclick` does not
+ // carry. A finger's double tap is the stage's own. A mouse's or a pen's is
+ // the browser's `dblclick`.
const pointerTypeRef = useRef('');
+ // Where the last press on the media started, which a click does not carry.
+ const pressPointRef = useRef<{x: number; y: number} | null>(null);
// Without zoom, a click on the dark area lands on the container or the
- // dialog, and both close. With zoom, the stage covers that area. A finger's
- // tap beside the photo closes on the stage's own tap, and so does its tap on
- // the media group's strip below the stage. A mouse's or a pen's click
- // closes only outside the media (`isClickOutsideMedia`). A zoomed drag sets
- // `didDragRef`, so its click is ignored. The next press clears the flag, and
- // a finger's only on the stage.
+ // dialog, and both close. A finger's tap on a gallery's stage, or on the
+ // zoom stage beside the photo, closes on the stage's own tap. So does its
+ // tap on the media group's strip below a single photo's stage. A mouse's or
+ // a pen's click closes only outside the media (`isClickOutsideMedia`). A
+ // zoomed drag sets `didDragRef`, so its click is ignored. The next press
+ // clears the flag, and a finger's only on the stage.
const didDragRef = useRef(false);
const mediaGroupRef = useRef<HTMLDivElement | null>(null);
const captionRef = useRef<HTMLDivElement | null>(null);
- const pressPointRef = useRef<{x: number; y: number} | null>(null);
- // Whether a mouse's or a pen's click on the zoom target's media closes the
- // viewer. It does when its press or its release lands outside the media.
- // The media runs from the fitted photo's top to the caption's bottom. It is
- // as wide as the photo's natural width or the caption, up to the viewer's.
- // While zoomed, the photo's shown box is media too.
+ // Whether a mouse's or a pen's click on the media closes the viewer. It
+ // does when its press or its release lands outside the media: a single
+ // item's, or a gallery's current page's. The media runs from the fitted
+ // photo's top to the caption's bottom. It is as wide as the photo's
+ // natural width or the caption, up to the viewer's. While zoomed, the
+ // photo's shown box is media too.
const isClickOutsideMedia = useCallback((e: ReactMouseEvent<HTMLElement>) => {
- const stageElement = imageWrapperRef.current;
- const photo = stageElement?.querySelector('img');
+ const viewer = imageWrapperRef.current;
+ const page = viewer?.querySelector('[data-current]') ?? viewer;
+ const media = page?.querySelector('img') ?? page?.querySelector('video');
+ // The photo's own box, which centres it: the stage, or a page's.
+ const box = media?.parentElement;
const group = mediaGroupRef.current;
if (
e.detail === 0 ||
pointerTypeRef.current === 'touch' ||
- stageElement == null ||
- photo == null ||
+ viewer == null ||
+ page == null ||
+ media == null ||
+ box == null ||
group == null ||
!(e.target instanceof Node) ||
!group.contains(e.target)
) {
return false;
}
- const space = (stageElement.clientHeight - photo.offsetHeight) / 2;
- const box = stageElement.getBoundingClientRect();
- const top = box.top + space;
- let bottom = top + photo.offsetHeight;
- const caption = captionRef.current;
+ const space = (box.clientHeight - media.offsetHeight) / 2;
+ const boxRect = box.getBoundingClientRect();
+ const top = boxRect.top + space;
+ let bottom = top + media.offsetHeight;
+ const caption =
+ page === viewer
+ ? captionRef.current
+ : page.querySelector<HTMLElement>('[data-lightbox-caption]');
if (caption != null) {
// The caption's place under the fitted photo, also while zoomed.
const lift = caption.style.translate === '' ? space : 0;
bottom = Math.max(bottom, caption.getBoundingClientRect().bottom - lift);
}
+ const natural =
+ media instanceof HTMLImageElement ? media.naturalWidth : media.videoWidth;
const width = Math.min(
- stageElement.clientWidth,
- Math.max(photo.naturalWidth, caption?.offsetWidth ?? 0),
+ viewer.clientWidth,
+ Math.max(natural, caption?.offsetWidth ?? 0),
);
- const middle = box.left + stageElement.clientWidth / 2;
- const shown = photo.getBoundingClientRect();
+ const middle = boxRect.left + box.clientWidth / 2;
+ const shown = media.getBoundingClientRect();
const isOutside = ({x, y}: {x: number; y: number}) =>
(y < top || y > bottom || Math.abs(x - middle) > width / 2) &&
!(
@@ -632,34 +756,21 @@ export function Lightbox({
didDragRef.current = false;
return;
}
+ const isMediaClose =
+ pointerTypeRef.current === 'touch'
+ ? hasZoom && !isVideo && e.target === mediaGroupRef.current
+ : (isGallery || (hasZoom && !isVideo)) && isClickOutsideMedia(e);
if (
e.target === e.currentTarget ||
e.target === containerRef.current ||
- (hasZoom &&
- !isVideo &&
- (pointerTypeRef.current === 'touch'
- ? e.target === mediaGroupRef.current
- : isClickOutsideMedia(e)))
+ isMediaClose
) {
handleClose();
}
},
- [handleClose, hasZoom, isVideo, isClickOutsideMedia],
+ [handleClose, hasZoom, isVideo, isGallery, isClickOutsideMedia],
);
- // Gallery navigation
- const goToPrev = useCallback(() => {
- if (canPrev) {
- setIndex(index - 1);
- }
- }, [canPrev, index, setIndex]);
-
- const goToNext = useCallback(() => {
- if (canNext) {
- setIndex(index + 1);
- }
- }, [canNext, index, setIndex]);
-
const isZoomTarget = hasZoom && !isVideo;
const onDragStart = () => {
didDragRef.current = true;
@@ -672,21 +783,35 @@ export function Lightbox({
// Meanwhile the caption goes back to its own place below the stage.
const isShownAtFitRef = useRef(true);
const placeCaption = useCallback(() => {
- const caption = captionRef.current;
- if (caption == null) {
- return;
+ // The stage's space below its fitted photo: the photo's laid-out height,
+ // not its zoomed box.
+ const place = (
+ caption: HTMLElement | null,
+ stageElement: HTMLElement | null,
+ isAtFit: boolean,
+ ) => {
+ const photo = stageElement?.querySelector('img');
+ if (caption == null) {
+ return;
+ }
+ const below =
+ isZoomTarget && isAtFit && stageElement != null && photo != null
+ ? (stageElement.clientHeight - photo.offsetHeight) / 2
+ : 0;
+ caption.style.translate = below > 0 ? `0 ${-below}px` : '';
+ };
+ place(captionRef.current, imageWrapperRef.current, isShownAtFitRef.current);
+ // A gallery's pages, each with its own caption under its own photo. Only
+ // the current one can be zoomed.
+ for (const page of trackRef.current?.querySelectorAll<HTMLElement>(
+ ':scope > [data-lightbox-page]',
+ ) ?? []) {
+ place(
+ page.querySelector<HTMLElement>(':scope > [data-lightbox-caption]'),
+ page.querySelector<HTMLElement>(':scope > [data-lightbox-page-media]'),
+ !page.hasAttribute('data-current') || isShownAtFitRef.current,
+ );
}
- const stageElement = imageWrapperRef.current;
- const photo = stageElement?.querySelector('img');
- // The photo's laid-out height, not its zoomed box.
- const below =
- isZoomTarget &&
- isShownAtFitRef.current &&
- stageElement != null &&
- photo != null
- ? (stageElement.clientHeight - photo.offsetHeight) / 2
- : 0;
- caption.style.translate = below > 0 ? `0 ${-below}px` : '';
}, [isZoomTarget]);
useAttachment(
imageWrapperRef,
@@ -701,7 +826,9 @@ export function Lightbox({
// The zoom stage takes the keyboard's zoom and pan and every pointer's
// gestures. Past a limit, a pinch or a pan gives way and returns.
const zoom = useZoomCore({
- stageRef: imageWrapperRef,
+ stageRef: isGallery ? pageMediaRef : imageWrapperRef,
+ surfaceRef: isGallery ? trackRef : imageWrapperRef,
+ isEnabled: isOpen && isZoomTarget,
itemKey: viewedItem,
// Zoom changes are silent to assistive tech, since only the transform
// changes. Announce them in the polite live region.
@@ -717,12 +844,41 @@ export function Lightbox({
},
});
const {isTouch} = useTouchPresentation();
+ const startsOnCaption = (touch: GestureTouch | undefined) => {
+ const target = touch?.target;
+ return (
+ target instanceof Element &&
+ target.closest('[data-lightbox-caption]') != null
+ );
+ };
const stage = useZoomStage(zoom, {
- stageRef: imageWrapperRef,
+ stageRef: isGallery ? pageMediaRef : imageWrapperRef,
+ surfaceRef: isGallery ? trackRef : imageWrapperRef,
isEnabled: isOpen && isZoomTarget,
- onTapOutside: handleClose,
+ // A gallery's stage shares its surface with the page around it. A tap
+ // there closes, as on the backdrop, unless it lands on the caption.
+ onTapOutside: ({x, y}) => {
+ const caption = trackRef.current
+ ?.querySelector('[data-current] [data-lightbox-caption]')
+ ?.getBoundingClientRect();
+ if (
+ caption != null &&
+ x >= caption.left &&
+ x <= caption.right &&
+ y >= caption.top &&
+ y <= caption.bottom
+ ) {
+ return;
+ }
+ handleClose();
+ },
onDragStart,
isTouchPresentation: isTouch,
+ // Only a gallery's touch pager takes a drag past a zoomed photo's edge.
+ hasOuterPager: isGallery && isTouch,
+ // A pinch whose first finger lands on a gallery's caption is the page's.
+ shouldBeginPinch: recognizer =>
+ !startsOnCaption(recognizer.trackedTouches[0]),
});
// Whether a mouse or a pen hovers over the fitted photo, for its cursor. The
// stage fills the viewer, so the photo's box is read, not the event target.
@@ -731,7 +887,10 @@ export function Lightbox({
if (e.pointerType === 'touch' || e.buttons !== 0) {
return;
}
- const r = e.currentTarget.querySelector('img')?.getBoundingClientRect();
+ const photo =
+ e.currentTarget.querySelector('[data-current] img') ??
+ e.currentTarget.querySelector('img');
+ const r = photo?.getBoundingClientRect();
e.currentTarget.toggleAttribute(
OVER_PHOTO_ATTRIBUTE,
r != null &&
@@ -741,6 +900,133 @@ export function Lightbox({
e.clientY <= r.bottom,
);
};
+ // A gallery pages like Photos, on a UIKit paging scroll view's release. A
+ // drag or a flick moves one page at most, with Photos' 40 pt gap. A zoomed
+ // photo keeps the drag until its edge, then the pager takes the next one.
+ // As in Photos, the photo left behind returns to the fitted size once the
+ // pager rests.
+ // A controlled parent can refuse a swipe by keeping its index. The pager
+ // then goes back to the photo the parent shows.
+ // A video's native controls are taken as a band at its bottom edge, since
+ // browsers expose no control geometry. A drag that starts there stays the
+ // video's, as a scrubber's or a volume slider's drag.
+ const startsOnVideoControls = (touch: GestureTouch | undefined) => {
+ const video = trackRef.current?.querySelector(
+ '[data-current] video[controls]',
+ );
+ if (touch == null || video == null) {
+ return false;
+ }
+ const box = video.getBoundingClientRect();
+ return (
+ touch.startX >= box.left &&
+ touch.startX <= box.right &&
+ touch.startY <= box.bottom &&
+ touch.startY >= box.bottom - VIDEO_CONTROLS_BAND
+ );
+ };
+ usePager({
+ viewportRef: imageWrapperRef,
+ trackRef,
+ count: mediaArray.length,
+ gap: zoomMedia.viewer.pageGap,
+ index,
+ // The drag paging is part of the touch presentation. Under a fine pointer
+ // the buttons and the arrow keys page, and the page keeps its scroll.
+ isPanEnabled: isOpen && isGallery && isTouch,
+ // Under the touch presentation a change of `index` slides the pager, and
+ // a refused drag springs back. Under a fine pointer it moves the pager at
+ // once, so a refused button shows nothing.
+ isControlledChangeAnimated: isTouch,
+ // In the touch presentation every pointer pages. A drag that starts on a
+ // video's controls stays the video's.
+ panOptions: {
+ allowedPointerTypes: ['touch', 'pen', 'mouse'],
+ maximumNumberOfTouches: 1,
+ shouldBegin: pan => !startsOnVideoControls(pan.trackedTouches[0]),
+ },
+ shouldBeginPan: direction => !stage.isZoomed() || stage.isAtEdge(direction),
+ onIndexChange: (next, reason) => {
+ if (reason === 'drag') {
+ setIndex(next);
+ }
+ },
+ // The pager names the page it rests on. Its report can come before the
+ // render that marks that page current, so the page, not the mark, decides.
+ onSettle: settled => {
+ for (const page of trackRef.current?.querySelectorAll<HTMLElement>(
+ ':scope > [data-lightbox-page]',
+ ) ?? []) {
+ const img = page.querySelector<HTMLElement>('img');
+ if (img != null && page.dataset.lightboxPage !== String(settled)) {
+ img.style.translate = '';
+ img.style.scale = '';
+ }
+ }
+ },
+ });
+
+ // Whether a point is on the current page's media group: its photo or video
+ // and its caption, as one box. The photo takes no pointer events, so a
+ // press on it lands on its box. An element with no size yet (a photo still
+ // loading) adds nothing to the box.
+ const isOnCurrentMedia = (x: number, y: number) => {
+ const page = imageWrapperRef.current?.querySelector('[data-current]');
+ const boxes = [
+ page?.querySelector('img'),
+ page?.querySelector('video'),
+ page?.querySelector('[data-lightbox-caption]'),
+ ]
+ .map(element => element?.getBoundingClientRect())
+ .filter((r): r is DOMRect => r != null && r.width > 0 && r.height > 0);
+ return (
+ boxes.length > 0 &&
+ x >= Math.min(...boxes.map(r => r.left)) &&
+ x <= Math.max(...boxes.map(r => r.right)) &&
+ y >= Math.min(...boxes.map(r => r.top)) &&
+ y <= Math.max(...boxes.map(r => r.bottom))
+ );
+ };
+ // Without zoom, a gallery's stage fills the viewer. So a finger's tap on it
+ // beside the media closes the viewer, as a click on the backdrop does. A
+ // press that moves past the tap's movement limit is no tap. A mouse's or a
+ // pen's click closes it only outside the media (`isClickOutsideMedia`).
+ // With zoom, the stage's own tap closes it.
+ useGestureRecognizer(
+ imageWrapperRef,
+ () =>
+ new TapGestureRecognizer({
+ name: 'lightbox-backdrop-tap',
+ allowedPointerTypes: ['touch'],
+ }),
+ tap => {
+ if (tap.state !== 'ended') {
+ return;
+ }
+ const {x, y} = tap.location();
+ if (!isOnCurrentMedia(x, y)) {
+ handleClose();
+ }
+ },
+ {isEnabled: isOpen && isGallery && !isZoomTarget, manageStyle: false},
+ );
+
+ // Gallery navigation. The buttons and the arrow keys ask for the new item.
+ // Under the touch presentation the pager then slides there, as a paging
+ // scroll view's `setContentOffset` does. Under a fine pointer it moves at
+ // once.
+
+ const goToPrev = useCallback(() => {
+ if (canPrev) {
+ setIndex(index - 1);
+ }
+ }, [canPrev, index, setIndex]);
+
+ const goToNext = useCallback(() => {
+ if (canNext) {
+ setIndex(index + 1);
+ }
+ }, [canNext, index, setIndex]);
// Keyboard navigation. While zoomed, arrows pan the image (matching common
// lightbox conventions); when not zoomed they navigate the gallery.
@@ -845,6 +1131,35 @@ export function Lightbox({
);
};
+ const renderMedia = (
+ {src, alt, type: kind = 'image'}: LightboxMedia,
+ isCurrent: boolean,
+ ) =>
+ kind === 'video' ? (
+ <video
+ src={src}
+ aria-label={alt}
+ controls
+ autoPlay={isCurrent && hasAutoPlay}
+ preload={isCurrent ? 'auto' : 'metadata'}
+ {...stylex.props(styles.video)}
+ />
+ ) : (
+ <img
+ ref={isCurrent ? stage.contentRef : undefined}
+ onLoad={placeCaption}
+ src={src}
+ alt={isCurrent ? alt : ''}
+ aria-hidden={isCurrent ? undefined : true}
+ draggable={false}
+ {...stylex.props(styles.image)}
+ />
+ );
+ // The current item and its neighbours; the pager shows one at rest.
+ const pageIndexes = isGallery
+ ? [index - 1, index, index + 1].filter(i => i >= 0 && i < mediaArray.length)
+ : [];
+
return (
<dialog
ref={mergedDialogRef}
@@ -918,7 +1233,8 @@ export function Lightbox({
ref={mediaGroupRef}
{...stylex.props(
styles.mediaGroup,
- isZoomTarget && styles.mediaGroupZoom,
+ isZoomTarget && !isGallery && styles.mediaGroupZoom,
+ isGallery && styles.mediaGroupGallery,
)}>
<div
ref={imageWrapperRef}
@@ -932,8 +1248,9 @@ export function Lightbox({
}
{...stylex.props(
styles.imageWrapper,
- isZoomTarget && styles.imageWrapperZoomTarget,
- isZoomTarget && styles.imageWrapperFill,
+ isGallery && styles.imageWrapperGallery,
+ isZoomTarget && !isGallery && styles.imageWrapperZoomTarget,
+ isZoomTarget && !isGallery && styles.imageWrapperFill,
isZoomTarget && focusOutlineStyles.focusVisible,
isZoomTarget && styles.imageWrapperFocusInset,
isZoomTarget && !isZoomed && styles.imageWrapperZoomable,
@@ -959,27 +1276,52 @@ export function Lightbox({
}
: undefined
}>
- {isVideo ? (
- <video
- src={currentItem.src}
- aria-label={currentItem.alt}
- controls
- autoPlay={hasAutoPlay}
- {...stylex.props(styles.video)}
- />
+ {isGallery ? (
+ <div
+ ref={trackRef}
+ {...stylex.props(
+ styles.track,
+ isZoomTarget && styles.trackZoomTarget,
+ )}>
+ {pageIndexes.map(i => (
+ <div
+ key={i}
+ data-lightbox-page={i}
+ data-current={i === index ? '' : undefined}
+ // Only the current page is on screen at rest: the
+ // others stay out of the tab order and the
+ // accessibility tree.
+ inert={i !== index ? true : undefined}
+ aria-hidden={i !== index ? true : undefined}
+ {...stylex.props(
+ styles.page,
+ pageStyles.position(i),
+ )}>
+ <div
+ ref={i === index ? pageMediaRef : undefined}
+ data-lightbox-page-media=""
+ {...stylex.props(
+ styles.pageMedia,
+ isZoomTarget && styles.pageMediaZoomTarget,
+ )}>
+ {renderMedia(mediaArray[i], i === index)}
+ </div>
+ {isRenderable(mediaArray[i].caption) && (
+ <div
+ data-lightbox-caption=""
+ {...stylex.props(styles.caption)}>
+ {mediaArray[i].caption}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
) : (
- <img
- ref={stage.contentRef}
- src={currentItem.src}
- alt={currentItem.alt}
- draggable={false}
- onLoad={placeCaption}
- {...stylex.props(styles.image)}
- />
+ renderMedia(currentItem, true)
)}
</div>
- {isRenderable(currentItem.caption) && (
+ {!isGallery && isRenderable(currentItem.caption) && (
<div ref={captionRef} {...stylex.props(styles.caption)}>
{currentItem.caption}
</div>
diff --git a/packages/core/src/Lightbox/LightboxFinePointer.a11y.browser.spec.ts b/packages/core/src/Lightbox/LightboxFinePointer.a11y.browser.spec.ts
index 914b66651d..e0d0e36f1c 100644
--- a/packages/core/src/Lightbox/LightboxFinePointer.a11y.browser.spec.ts
+++ b/packages/core/src/Lightbox/LightboxFinePointer.a11y.browser.spec.ts
@@ -4,14 +4,11 @@
* @file LightboxFinePointer.a11y.browser.spec.ts
* @input The built Lightbox "with zoom" story, a desktop browser (a fine
* primary pointer) and real mouse input; in Chromium, pen input
- * @output Browser evidence that the zoom's gestures attach for every
- * pointer where the primary pointer is fine too. The zoom target takes its
- * touches as on a phone. A mouse's double-click zooms 2× about the clicked
- * point, and the next zooms back; a pen's double-click zooms 2× too. The
- * keyboard's and a double-click's zoom settle on `springs.settle`, a pen
- * drag pans a zoomed photo, and a mouse drag stops at the photo's edges
- * @position Cross-browser proof for Lightbox's mouse, pen and keyboard zoom
- * where the primary pointer is fine
+ * @output Evidence that the gestures take every pointer where the primary
+ * pointer is fine too. It covers the zoom's touches as on a phone, the
+ * double-click's 2× zoom and the keyboard's spring. It also covers pen and
+ * mouse drags, and a gallery's Next, arrow keys and dark-area click
+ * @position Cross-browser proof for Lightbox under a fine primary pointer
*/
import {
@@ -177,16 +174,217 @@ test('a caption sits under the fitted photo, as it does without zoom', async ({
.toBeGreaterThanOrEqual(-0.5);
});
+/** Opens the gallery story (zoom on) at its first photo with the mouse. */
+async function openGallery(page: Page) {
+ await page.route('https://picsum.photos/**', async route =>
+ route.fulfill({
+ contentType: 'image/svg+xml',
+ body: photoSvg(PHOTO.width, PHOTO.height),
+ }),
+ );
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-lightbox--gallery-with-zoom&viewMode=story`,
+ );
+ await page.getByRole('button', {name: 'Open gallery with zoom'}).click();
+ const dialog = page.getByRole('dialog');
+ await expect(dialog).toBeVisible();
+ await expect(dialog).toContainText('1 / 4');
+ const current = dialog.locator('[data-current] img');
+ await expect
+ .poll(async () =>
+ current.evaluate(el => (el as HTMLImageElement).naturalWidth),
+ )
+ .toBe(PHOTO.width);
+ await settled(page);
+ return {dialog, current};
+}
+
+/** Clicks `point`, which must be the dark area, and expects the viewer gone. */
+async function expectBackdropClickCloses(
+ page: Page,
+ dialog: Locator,
+ point: {x: number; y: number},
+): Promise<void> {
+ const hit = await page.evaluate(({x, y}) => {
+ const el = document.elementFromPoint(x, y);
+ return {
+ isControl: el?.closest('button, a, input') != null,
+ isPhoto: el instanceof HTMLImageElement,
+ inDialog: el?.closest('dialog') != null,
+ };
+ }, point);
+ expect(hit).toEqual({isControl: false, isPhoto: false, inDialog: true});
+ await page.mouse.click(point.x, point.y);
+ await expect(dialog).toBeHidden();
+}
+
+/** The computed touch-action of the photo and each ancestor below the dialog. */
+async function touchActionsAbove(photo: Locator): Promise<string[]> {
+ return photo.evaluate(el => {
+ const actions: string[] = [];
+ for (
+ let node: Element | null = el;
+ node != null && node.tagName !== 'DIALOG';
+ node = node.parentElement
+ ) {
+ actions.push(getComputedStyle(node).touchAction);
+ }
+ return actions;
+ });
+}
+
test('the zoom target takes its touches as on a phone where the primary pointer is fine too', async ({
page,
}) => {
- const {stage} = await openViewer(page);
+ const {stage, img} = await openViewer(page);
// Gestures attach for every pointer. A touchscreen laptop's finger pinches
// and pans the photo as on a phone, so the zoom target claims its touches,
// as under a coarse pointer.
expect(await stage.evaluate(el => getComputedStyle(el).touchAction)).toBe(
'none',
);
+ expect(await touchActionsAbove(img)).toEqual([
+ 'auto',
+ 'none',
+ 'auto',
+ 'auto',
+ ]);
+});
+
+test('a gallery leaves its sideways touches to the page where the primary pointer is fine', async ({
+ page,
+}) => {
+ // The current photo's row claims its touches for the zoom, as under a
+ // coarse pointer. The track, the zoom stage's surface, leaves only the
+ // page's pinch-zoom. The drag paging is the touch presentation's, so the
+ // pager's viewport claims no pan.
+ const {current} = await openGallery(page);
+ expect(await touchActionsAbove(current)).toEqual([
+ 'auto',
+ 'none',
+ 'auto',
+ 'pinch-zoom',
+ 'auto',
+ 'auto',
+ 'auto',
+ ]);
+});
+
+for (const via of ['the Next button', 'the arrow key'] as const) {
+ test(`${via} shows the next photo at once where the primary pointer is fine`, async ({
+ page,
+ }) => {
+ const {dialog} = await openGallery(page);
+ // The track's place every frame from the press on. Under a finger the
+ // pager slides; with a mouse or the keyboard the new photo shows at once,
+ // as it always has. The sampler is installed and awaited before the press,
+ // since a press the page gets first would leave it waiting. It runs for
+ // 600 ms and at least 12 frames, since a busy runner paints few frames.
+ // At half the test's timeout it gives up, so too few frames fail by name.
+ const giveUpMs = test.info().timeout / 2;
+ await page.evaluate(giveUpMs => {
+ (window as unknown as {__places: Promise<number[]>}).__places =
+ new Promise<number[]>(resolve => {
+ const track = document.querySelector(
+ 'dialog [data-lightbox-page]',
+ )?.parentElement;
+ const places: number[] = [];
+ let start: number | null = null;
+ const begin = () => {
+ start = performance.now();
+ window.setTimeout(() => resolve(places), giveUpMs);
+ };
+ window.addEventListener('click', begin, {capture: true, once: true});
+ window.addEventListener('keydown', begin, {
+ capture: true,
+ once: true,
+ });
+ const tick = (now: number) => {
+ if (start != null && track != null) {
+ places.push(Math.round(track.getBoundingClientRect().x));
+ }
+ if (start == null || now - start < 600 || places.length < 12) {
+ requestAnimationFrame(tick);
+ } else {
+ resolve(places);
+ }
+ };
+ requestAnimationFrame(tick);
+ });
+ }, giveUpMs);
+ if (via === 'the Next button') {
+ await dialog.getByRole('button', {name: 'Next'}).click();
+ } else {
+ await page.keyboard.press('ArrowRight');
+ }
+ const places = await page.evaluate(
+ async () => (window as unknown as {__places: Promise<number[]>}).__places,
+ );
+ await expect(dialog).toContainText('2 / 4');
+ expect(places.length, 'too few frames to judge').toBeGreaterThanOrEqual(12);
+ // One place from the first frame after the press: no frame in between.
+ expect(new Set(places).size).toBe(1);
+ });
+}
+
+test('a mouse click above the photo closes the viewer with zoom on, as before', async ({
+ page,
+}) => {
+ // A window taller than the photo's fitted height leaves the dark area
+ // above it, outside the media, where a click closes the viewer.
+ await page.setViewportSize({width: 1280, height: 1000});
+ const {dialog, img} = await openViewer(page);
+ const shown = await boxOf(img);
+ expect(shown.y).toBeGreaterThan(40);
+ await expectBackdropClickCloses(page, dialog, {
+ x: shown.x + shown.width / 2,
+ y: shown.y / 2,
+ });
+});
+
+test('in a gallery, a mouse click beside a large photo, level with it, leaves the viewer open, as on main', async ({
+ page,
+}) => {
+ // A photo wider than the viewer: the media spans the viewer's width, so
+ // a click beside the photo stays on it, as on main.
+ const {dialog, current} = await openGallery(page);
+ const shown = await boxOf(current);
+ expect(shown.x).toBeGreaterThan(40);
+ const level = shown.y + shown.height * 0.15;
+ await page.mouse.click(shown.x / 2, level);
+ await page.waitForTimeout(400);
+ await expect(dialog).toBeVisible();
+});
+
+test('without zoom, a mouse click at the far edge beside a large gallery photo leaves the viewer open, as on main', async ({
+ page,
+}) => {
+ await page.setViewportSize({width: 1280, height: 800});
+ await page.route('https://picsum.photos/**', async route =>
+ route.fulfill({
+ contentType: 'image/svg+xml',
+ body: photoSvg(PHOTO.width, PHOTO.height),
+ }),
+ );
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-lightbox--gallery&viewMode=story`,
+ );
+ await page.locator('#storybook-root img').first().click();
+ const dialog = page.getByRole('dialog');
+ await expect(dialog).toBeVisible();
+ const current = dialog.locator('[data-current] img');
+ await expect
+ .poll(async () =>
+ current.evaluate(el => (el as HTMLImageElement).naturalWidth),
+ )
+ .toBe(PHOTO.width);
+ await settled(page);
+ const shown = await boxOf(current);
+ // The photo leaves dark area at the window's right edge, level with it.
+ expect(1280 - (shown.x + shown.width)).toBeGreaterThan(20);
+ await page.mouse.click(1276, shown.y + shown.height / 2);
+ await page.waitForTimeout(400);
+ await expect(dialog).toBeVisible();
});
test('a mouse double-click zooms 2× about the clicked point, and the next zooms back', async ({
@@ -556,13 +754,13 @@ test('in a gallery with zoom, a mouse click beside a small photo closes past its
.toBe(200);
await settled(page);
const photo = await boxOf(img);
- // The caption follows the stage in the media group.
- const caption = await dialog
- .getByRole('button', {name: 'Zoom'})
- .evaluate(stage => {
- const r = stage.nextElementSibling?.getBoundingClientRect();
- return r == null ? null : {x: r.x, width: r.width};
- });
+ // The current page's own caption.
+ const caption = await dialog.evaluate(viewer => {
+ const r = viewer
+ .querySelector('[data-current] [data-lightbox-caption]')
+ ?.getBoundingClientRect();
+ return r == null ? null : {x: r.x, width: r.width};
+ });
if (caption == null) {
throw new Error('no caption');
}
diff --git a/packages/core/src/Lightbox/__tests__/LightboxEveryPointer.interaction.browser.spec.ts b/packages/core/src/Lightbox/__tests__/LightboxEveryPointer.interaction.browser.spec.ts
index 50d89c3501..552f709b31 100644
--- a/packages/core/src/Lightbox/__tests__/LightboxEveryPointer.interaction.browser.spec.ts
+++ b/packages/core/src/Lightbox/__tests__/LightboxEveryPointer.interaction.browser.spec.ts
@@ -2,14 +2,15 @@
/**
* @file LightboxEveryPointer.interaction.browser.spec.ts
- * @input The built "With zoom" and "Default" Lightbox stories, with a
- * 3000 × 2000 test photo. A desktop context (1280 × 800, a fine primary
- * pointer) has a mouse and a trackpad's wheel. Chromium also has timed
- * mouse events through the Chrome DevTools Protocol
- * @output Proofs that Lightbox's gestures work for every pointer. A ctrl-wheel
+ * @input The built "With zoom", "Gallery with zoom" and "Default" Lightbox
+ * stories, with a 3000 × 2000 test photo. A desktop context (1280 × 800, a
+ * fine primary pointer) has a mouse and a trackpad's wheel. Chromium also
+ * has timed mouse events through the Chrome DevTools Protocol
+ * @output Proofs for Lightbox's gestures under every pointer. A ctrl-wheel
* zooms, and a trackpad's scroll pans a zoomed photo and stops at its edge.
* A mouse wheel's notch leaves it in place, and a mouse drag's release
- * stops it
+ * stops it. A mouse drag sideways and a trackpad's horizontal scroll leave a
+ * gallery on its photo
* @position Interaction tests for Lightbox (browser), beside
* LightboxZoomModes.interaction.browser.spec.ts
*/
@@ -32,10 +33,11 @@ import {
const storybook = withStorybook(test);
-type Story = 'with-zoom' | 'default';
+type Story = 'with-zoom' | 'gallery-with-zoom' | 'default';
const TRIGGER: Record<Story, string> = {
'with-zoom': 'Open with zoom',
+ 'gallery-with-zoom': 'Open gallery with zoom',
default: 'Open lightbox',
};
@@ -87,7 +89,10 @@ async function openDesktop(
await page.getByRole('button', {name: TRIGGER[story]}).click();
const dialog = page.getByRole('dialog');
await expect(dialog).toBeVisible();
- const img = dialog.getByRole('img').first();
+ const img =
+ story === 'gallery-with-zoom'
+ ? dialog.locator('[data-current] img')
+ : dialog.getByRole('img').first();
await expect
.poll(async () => img.evaluate(el => (el as HTMLImageElement).naturalWidth))
.toBe(3000);
@@ -119,6 +124,19 @@ async function boxOf(locator: Locator) {
return box;
}
+/** A mouse pressed at `from` and moved to `to` in `steps`, one a frame. */
+async function mouseDrag(page: Page, from: Point, to: Point, steps: number) {
+ await page.mouse.move(from.x, from.y);
+ await page.mouse.down();
+ for (let i = 1; i <= steps; i++) {
+ await page.mouse.move(
+ from.x + ((to.x - from.x) * i) / steps,
+ from.y + ((to.y - from.y) * i) / steps,
+ );
+ await frames(page, 1);
+ }
+}
+
/**
* Mouse or pen events with exact timestamps through the Chrome DevTools
* Protocol: a release's velocity is the move's, whatever the runner's pace.
@@ -147,6 +165,82 @@ async function timedPointer(page: Page, pointerType: 'mouse' | 'pen') {
};
}
+test('a mouse drag sideways leaves a gallery on its photo, as on main', async ({
+ browser,
+}) => {
+ const {context, page, dialog, centre} = await openDesktop(
+ browser,
+ 'gallery-with-zoom',
+ );
+ try {
+ const counter = dialog.getByText(/^\d+ \/ \d+$/);
+ await expect(counter).toHaveText('1 / 4');
+ // Past half a page from the photo's right side: under a finger, the
+ // release pages on its travel alone.
+ await mouseDrag(page, {x: 1100, y: centre.y}, {x: 250, y: centre.y}, 17);
+ await page.mouse.up();
+ await frames(page, 30);
+ await expect(counter).toHaveText('1 / 4');
+ } finally {
+ await context.close();
+ }
+});
+
+const WHEEL_DRIVERS =
+ "Chromium's driver sends each wheel as a mouse wheel's notch; WebKit's sends a trackpad's precise deltas.";
+
+test('a trackpad’s horizontal scroll leaves a gallery on its photo', async ({
+ browser,
+ browserName,
+}) => {
+ test.skip(browserName !== 'webkit', WHEEL_DRIVERS);
+ const {wheel, context, page, dialog, centre} = await openDesktop(
+ browser,
+ 'gallery-with-zoom',
+ );
+ try {
+ const counter = dialog.getByText(/^\d+ \/ \d+$/);
+ await expect(counter).toHaveText('1 / 4');
+ await page.mouse.move(centre.x, centre.y);
+ // Past half a page, which pages under a finger. No delta is a multiple
+ // of 40 px, which would read as a mouse wheel's notch.
+ for (let i = 0; i < 24; i++) {
+ await wheel(30, 0);
+ await frames(page, 1);
+ }
+ await frames(page, 30);
+ await expect(counter).toHaveText('1 / 4');
+ } finally {
+ await context.close();
+ }
+});
+
+test("a mouse wheel's notches leave a gallery on its photo", async ({
+ browser,
+ browserName,
+}) => {
+ test.skip(browserName !== 'chromium', WHEEL_DRIVERS);
+ const {wheel, context, page, dialog, centre} = await openDesktop(
+ browser,
+ 'gallery-with-zoom',
+ );
+ try {
+ const counter = dialog.getByText(/^\d+ \/ \d+$/);
+ await expect(counter).toHaveText('1 / 4');
+ await page.mouse.move(centre.x, centre.y);
+ for (let i = 0; i < 8; i++) {
+ await wheel(120, 0);
+ await frames(page, 1);
+ }
+ // The host ends a notch's stream 100 ms after its last event. Fifteen
+ // frames pass that at up to 120 Hz.
+ await frames(page, 15);
+ await expect(counter).toHaveText('1 / 4');
+ } finally {
+ await context.close();
+ }
+});
+
test('a ctrl-wheel zooms the photo', async ({browser}) => {
const {wheel, context, page, dialog, img, centre} = await openDesktop(
browser,
@@ -172,9 +266,6 @@ test('a ctrl-wheel zooms the photo', async ({browser}) => {
}
});
-const WHEEL_DRIVERS =
- "Chromium's driver sends each wheel as a mouse wheel's notch; WebKit's sends a trackpad's precise deltas.";
-
test("a trackpad's scroll pans a zoomed photo", async ({
browser,
browserName,
diff --git a/packages/core/src/Lightbox/__tests__/LightboxPaging.interaction.browser.spec.ts b/packages/core/src/Lightbox/__tests__/LightboxPaging.interaction.browser.spec.ts
new file mode 100644
index 0000000000..403abf5d52
--- /dev/null
+++ b/packages/core/src/Lightbox/__tests__/LightboxPaging.interaction.browser.spec.ts
@@ -0,0 +1,1077 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file LightboxPaging.interaction.browser.spec.ts
+ * @input The built "Gallery with zoom" Lightbox story on the phone project,
+ * real touch input and the interaction harness
+ * @output Proofs for Lightbox's pager under a finger, in Chromium and WebKit.
+ * They cover paging with Photos' 40 pt gap, a zoomed photo's edge, RTL, the
+ * Next button and a pinch that never pages. They also cover a settle
+ * through a blocked main thread, focus, a refused swipe, rotation and a
+ * storyboard. usePager's own spec proves the physics.
+ * @position Interaction tests for Lightbox (browser), beside
+ * LightboxZoom.interaction.browser.spec.ts
+ */
+
+import {
+ expect,
+ test,
+ type Locator,
+ type Page,
+} from '@astryxdesign/a11y-spec/playwright';
+import {
+ type BlockedWindow,
+ blockMainThread,
+ type BusyRun,
+ BusyWindowTooLateError,
+ castStoryboard,
+ CONTROL_RGB,
+ drag,
+ frames,
+ markElement,
+ openStory,
+ pinch,
+ pooledBusyProof,
+ startBusyControl,
+ startScreencast,
+ touchDriver,
+ type TouchDriver,
+ type TouchScript,
+ touchStoryboard,
+ trackMarker,
+ waitForAnimation,
+ waitForRest,
+ withStorybook,
+ writeEvidence,
+} from '@astryxdesign/interaction-harness';
+import {slowViewer} from './viewerTempo';
+
+const storybook = withStorybook(test);
+
+// Photos' gap between pages (motion/uikit/zoomMedia.ts), restated.
+const GAP = 40;
+
+/** A checkerboard photo with a disc whose colour tells the photos apart. */
+function photoSvg(color: string): string {
+ let squares = '';
+ for (let y = 0; y < 2000; y += 50) {
+ for (let x = 0; x < 3000; x += 50) {
+ if ((x + y) % 100 === 0) {
+ squares += `<rect x="${x}" y="${y}" width="50" height="50"/>`;
+ }
+ }
+ }
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="3000" height="2000" viewBox="0 0 3000 2000" shape-rendering="crispEdges"><rect width="3000" height="2000" fill="#fff"/><g fill="#000">${squares}</g><circle cx="1500" cy="1000" r="250" fill="${color}"/></svg>`;
+}
+
+const COLORS: Record<string, string> = {
+ '10': '#d22',
+ '15': '#2a2',
+ '20': '#22d',
+ '25': '#d80',
+};
+
+interface Gallery {
+ driver: TouchDriver;
+ dialog: Locator;
+ /** The pager's viewport (the stage), and the track it translates. */
+ viewport: Locator;
+ track: Locator;
+ /** The viewport's box on the page. */
+ box: {x: number; y: number; width: number; height: number};
+ counter: () => Promise<string>;
+ trackX: () => Promise<number>;
+ /** The current photo's zoom transform. */
+ photo: () => Promise<{x: number; scale: number}>;
+}
+
+async function openGallery(
+ page: Page,
+ {
+ rtl = false,
+ story = 'core-lightbox--gallery-with-zoom',
+ trigger: triggerName = 'Open gallery with zoom',
+ } = {},
+): Promise<Gallery> {
+ await page.route('https://picsum.photos/**', async route => {
+ const id = /\/id\/(\d+)\//.exec(route.request().url())?.[1] ?? '10';
+ await route.fulfill({
+ contentType: 'image/svg+xml',
+ body: photoSvg(COLORS[id] ?? '#888'),
+ });
+ });
+ if (rtl) {
+ // Storybook's direction global sets the story's `dir` (and its
+ // providers'); openStory has no globals.
+ await page.goto(
+ `${storybook()}/iframe.html?id=core-lightbox--gallery-with-zoom&viewMode=story&globals=direction:rtl`,
+ );
+ await page.locator('#storybook-root > *').first().waitFor();
+ await frames(page, 2);
+ } else {
+ await openStory(page, storybook(), story);
+ }
+ const driver = await touchDriver(page);
+ const trigger = page.getByRole('button', {name: triggerName});
+ const t = await trigger.boundingBox();
+ if (t == null) {
+ throw new Error('no trigger');
+ }
+ await driver.tap({x: t.x + t.width / 2, y: t.y + t.height / 2});
+ const dialog = page.getByRole('dialog');
+ await expect(dialog).toBeVisible();
+ const viewport = dialog.getByRole('button', {name: 'Zoom'});
+ const track = viewport.locator(':scope > div').first();
+ await expect
+ .poll(async () =>
+ viewport.evaluate(el =>
+ [...el.querySelectorAll('img')].every(img => img.naturalWidth === 3000),
+ ),
+ )
+ .toBe(true);
+ await frames(page, 2);
+ const box = await viewport.evaluate(el => {
+ const r = el.getBoundingClientRect();
+ return {
+ x: r.left,
+ y: r.top,
+ width: el.clientWidth,
+ height: el.clientHeight,
+ };
+ });
+ return {
+ driver,
+ dialog,
+ viewport,
+ track,
+ box,
+ counter: async () =>
+ (await dialog.getByText(/^\d+ \/ \d+$/).textContent()) ?? '',
+ trackX: async () =>
+ track.evaluate(el => {
+ const value = getComputedStyle(el).translate;
+ return value === 'none' ? 0 : parseFloat(value);
+ }),
+ photo: async () =>
+ viewport.evaluate(el => {
+ const img = el.querySelector<HTMLElement>('[data-current] img');
+ if (img == null) {
+ return {x: 0, scale: 1};
+ }
+ const style = getComputedStyle(img);
+ return {
+ x: style.translate === 'none' ? 0 : parseFloat(style.translate),
+ scale: style.scale === 'none' ? 1 : parseFloat(style.scale),
+ };
+ }),
+ };
+}
+
+function doubleTap(at: {x: number; y: number}): TouchScript {
+ return [
+ {t: 0, fingers: [{id: 0, ...at}]},
+ {t: 50, fingers: []},
+ {t: 170, fingers: [{id: 0, ...at}]},
+ {t: 220, fingers: []},
+ ];
+}
+
+/** A slow drag by dx, held still before the lift (no release velocity). */
+function slowDrag(from: {x: number; y: number}, dx: number): TouchScript {
+ return drag(
+ from,
+ {x: from.x + dx, y: from.y},
+ {durationMs: 600, restMs: 150},
+ );
+}
+
+/** Two fingers spreading while their centroid drifts sideways. */
+function driftingPinch(
+ centre: {x: number; y: number},
+ driftX: number,
+): TouchScript {
+ const script: TouchScript[number][] = [];
+ for (let i = 0; i <= 24; i++) {
+ const p = i / 24;
+ const half = 50 + 50 * p;
+ const x = centre.x + driftX * p;
+ script.push({
+ t: i * 16,
+ fingers: [
+ {id: 0, x: x - half, y: centre.y},
+ {id: 1, x: x + half, y: centre.y},
+ ],
+ });
+ }
+ script.push({t: 25 * 16 + 100, fingers: []});
+ return script;
+}
+
+test("a drag past half a photo pages to the next one, Photos' 40 pt gap between them", async ({
+ page,
+}) => {
+ const g = await openGallery(page);
+ expect(await g.counter()).toBe('1 / 4');
+ const mid = {x: g.box.x + g.box.width * 0.8, y: g.box.y + g.box.height / 2};
+ // Mid-drag: the next page sits one page width plus the gap away.
+ let gap = Number.NaN;
+ await g.driver.play(slowDrag(mid, -g.box.width * 0.6), {
+ onEvent: async step => {
+ if (step.type === 'touchMove' && Number.isNaN(gap)) {
+ gap = await g.track.evaluate(el => {
+ const pages = [...el.children] as HTMLElement[];
+ const current = pages.find(p => p.hasAttribute('data-current'));
+ const next = current?.nextElementSibling as HTMLElement | null;
+ if (current == null || next == null) {
+ return Number.NaN;
+ }
+ return (
+ next.getBoundingClientRect().left -
+ current.getBoundingClientRect().right
+ );
+ });
+ }
+ },
+ });
+ expect(gap).toBeCloseTo(GAP, 0);
+ await waitForRest(g.track);
+ expect(await g.counter()).toBe('2 / 4');
+ expect(await g.trackX()).toBeCloseTo(-(g.box.width + GAP), 0);
+ await expect(g.dialog).toHaveAccessibleName('Mountain lake');
+});
+
+test('a zoomed photo keeps the drag until its edge; the next drag from the edge pages', async ({
+ page,
+}) => {
+ const g = await openGallery(page);
+ const centre = {x: g.box.x + g.box.width / 2, y: g.box.y + g.box.height / 2};
+ const current = g.viewport.locator('[data-current] img');
+ await g.driver.play(doubleTap(centre));
+ await waitForAnimation(current);
+ await waitForRest(current);
+ const zoomed = await g.photo();
+ expect(zoomed.scale).toBeGreaterThan(1.5);
+ // A drag left pans the photo 1:1 once past the pan's 10 px threshold; the
+ // track stays.
+ await g.driver.play(slowDrag(centre, -100));
+ await waitForRest(current);
+ const panned = await g.photo();
+ expect(panned.x).toBeCloseTo(zoomed.x - 90, 0);
+ expect(await g.trackX()).toBe(0);
+ expect(await g.counter()).toBe('1 / 4');
+ // Further left than the photo's right edge: it stops there (the drag
+ // started inside the photo, so the pager never takes it).
+ await g.driver.play(slowDrag(centre, -g.box.width));
+ await waitForAnimation(current);
+ await waitForRest(current);
+ const atEdge = await g.photo();
+ expect(await g.trackX()).toBe(0);
+ expect(await g.counter()).toBe('1 / 4');
+ // From the edge, the next drag left goes to the pager.
+ await g.driver.play(slowDrag(centre, -g.box.width * 0.6));
+ await waitForRest(g.track);
+ expect(await g.counter()).toBe('2 / 4');
+ expect((await g.photo()).scale).toBe(1);
+ // The photo left behind is back at the fitted size (Photos resets it).
+ const leftBehind = await g.track.evaluate(el => {
+ const img = el.querySelector<HTMLElement>(
+ '[data-lightbox-page]:not([data-current]) img',
+ );
+ return img == null ? null : getComputedStyle(img).scale;
+ });
+ expect(['none', '1']).toContain(leftBehind);
+ expect(atEdge.scale).toBeCloseTo(zoomed.scale, 3);
+});
+
+test('right to left, a drag to the right pages to the next photo', async ({
+ page,
+}) => {
+ const g = await openGallery(page, {rtl: true});
+ expect(await g.dialog.evaluate(el => getComputedStyle(el).direction)).toBe(
+ 'rtl',
+ );
+ const from = {x: g.box.x + g.box.width * 0.2, y: g.box.y + g.box.height / 2};
+ await g.driver.play(slowDrag(from, g.box.width * 0.6));
+ await waitForRest(g.track);
+ expect(await g.counter()).toBe('2 / 4');
+ expect(await g.trackX()).toBeCloseTo(g.box.width + GAP, 0);
+});
+
+test('the Next button pages on setContentOffset(animated:)', async ({page}) => {
+ const g = await openGallery(page);
+ const next = g.dialog.getByRole('button', {name: 'Next'});
+ const b = await next.boundingBox();
+ if (b == null) {
+ throw new Error('no Next button');
+ }
+ await g.driver.tap({x: b.x + b.width / 2, y: b.y + b.height / 2});
+ const [move] = await waitForAnimation(g.track);
+ expect(move.to - move.from).toBeGreaterThan(250);
+ expect(move.to - move.from).toBeLessThan(350);
+ await waitForRest(g.track);
+ expect(await g.counter()).toBe('2 / 4');
+ expect(await g.trackX()).toBeCloseTo(-(g.box.width + GAP), 0);
+});
+
+/** A grey WebM, 0.2 s at 320 × 180 (VP8), as base64. */
+const SHORT_WEBM =
+ 'GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAJtEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHWTbuMU6uEElTDZ1OsggEkTbuMU6uEHFO7a1OsggJX7AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmsCrXsYMPQkBNgIxMYXZmNjIuMy4xMDNXQYxMYXZmNjIuMy4xMDNEiYhAaQAAAAAAABZUrmvJrgEAAAAAAABA14EBc8WIWwKS0fV89mOcgQAitZyDdW5kiIEAhoVWX1ZQOIOBASPjg4QF9eEA4JGwggFAuoG0moECVbCEVbmBARJUw2f7c3OfY8CAZ8iZRaOHRU5DT0RFUkSHjExhdmY2Mi4zLjEwM3Nz1mPAi2PFiFsCktH1fPZjZ8ihRaOHRU5DT0RFUkSHlExhdmM2Mi4xMS4xMDMgbGlidnB4Z8ihRaOIRFVSQVRJT05Eh5MwMDowMDowMC4yMDAwMDAwMDAAH0O2dUCt54EAo0CIgQAAgPAOAJ0BKkABtAAARwiFhYiFhIgCAgAGFgYde3Nk5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9k5w9egP5oAKOdgQBkALECAAEQEAAYABhYL/QACIAEM1+tck+VgAAcU7trkbuPs4EAt4r3gQHxggGk8IED';
+
+/**
+ * Opens the story's video gallery and pages to the video (2 / 3). A video
+ * that failed to load gives Chromium's controls every touch on it, so the
+ * story's video is served SHORT_WEBM, which loads.
+ */
+async function openVideoGallery(page: Page) {
+ await page.route(
+ 'https://interactive-examples.mdn.mozilla.net/**',
+ async route =>
+ route.fulfill({
+ contentType: 'video/webm',
+ body: Buffer.from(SHORT_WEBM, 'base64'),
+ }),
+ );
+ await page.route('https://picsum.photos/**', async route =>
+ route.fulfill({contentType: 'image/svg+xml', body: photoSvg('#888')}),
+ );
+ // Without zoom the gallery's viewport is no Zoom button, so this opens the
+ // story itself rather than through openGallery.
+ await openStory(page, storybook(), 'core-lightbox--gallery-with-video');
+ const driver = await touchDriver(page);
+ const trigger = await page
+ .getByRole('button', {name: 'Open gallery with video'})
+ .boundingBox();
+ if (trigger == null) {
+ throw new Error('no trigger');
+ }
+ await driver.tap({
+ x: trigger.x + trigger.width / 2,
+ y: trigger.y + trigger.height / 2,
+ });
+ const dialog = page.getByRole('dialog');
+ await expect(dialog).toBeVisible();
+ const track = dialog.locator('[data-lightbox-page]').first().locator('..');
+ const counter = async () =>
+ (await dialog.getByText(/^\d+ \/ \d+$/).textContent()) ?? '';
+ const next = await dialog.getByRole('button', {name: 'Next'}).boundingBox();
+ if (next == null) {
+ throw new Error('no Next button');
+ }
+ await driver.tap({x: next.x + next.width / 2, y: next.y + next.height / 2});
+ await waitForRest(track);
+ expect(await counter()).toBe('2 / 3');
+ const video = dialog.locator('[data-current] video');
+ const box = await video.boundingBox();
+ if (box == null) {
+ throw new Error('no video');
+ }
+ return {driver, track, counter, video, box};
+}
+
+test("a drag that starts on a video's controls stays the video's; a drag on its frame pages", async ({
+ page,
+}) => {
+ const {driver, track, counter, box: v} = await openVideoGallery(page);
+ const width = page.viewportSize()?.width ?? 0;
+ // In the 48 px band at its bottom edge, where its controls are taken to be.
+ await driver.play(
+ slowDrag({x: v.x + v.width * 0.8, y: v.y + v.height - 20}, -width * 0.6),
+ );
+ await waitForRest(track);
+ expect(await counter()).toBe('2 / 3');
+ // On its frame, the drag pages.
+ await driver.play(
+ slowDrag({x: v.x + v.width * 0.8, y: v.y + v.height / 2}, -width * 0.6),
+ );
+ await waitForRest(track);
+ expect(await counter()).toBe('3 / 3');
+});
+
+test('a video that ends during a drag on its frame leaves the drag to page', async ({
+ page,
+}) => {
+ const {driver, track, counter, video, box: v} = await openVideoGallery(page);
+ const width = page.viewportSize()?.width ?? 0;
+ // The 0.2 s video starts at the press, so it ends early in the 600 ms drag.
+ await video.evaluate((el: HTMLVideoElement) => {
+ const at: Record<string, number> = {};
+ (window as unknown as {__at: Record<string, number>}).__at = at;
+ el.muted = true;
+ el.loop = false;
+ el.addEventListener('ended', () => {
+ at.ended = performance.now();
+ });
+ window.addEventListener(
+ 'pointerdown',
+ () => {
+ at.down = performance.now();
+ void el.play();
+ },
+ {capture: true, once: true},
+ );
+ for (const type of ['pointerup', 'pointercancel']) {
+ window.addEventListener(
+ type,
+ () => {
+ at[type] = performance.now();
+ },
+ {capture: true, once: true},
+ );
+ }
+ });
+ await driver.play(
+ slowDrag({x: v.x + v.width * 0.8, y: v.y + v.height / 2}, -width * 0.6),
+ );
+ await waitForRest(track);
+ const at = await page.evaluate(
+ () => (window as unknown as {__at: Record<string, number>}).__at,
+ );
+ expect(at.ended).toBeGreaterThan(at.down);
+ expect(at.ended).toBeLessThan(at.pointerup);
+ expect(at.pointercancel).toBeUndefined();
+ expect(await counter()).toBe('3 / 3');
+});
+
+/** The centre of the current page's caption, in client px. */
+async function captionCentre(g: Gallery): Promise<{x: number; y: number}> {
+ return g.dialog.locator('[data-current]').evaluate(page => {
+ const caption = page.querySelector('[data-lightbox-caption]');
+ if (caption == null) {
+ throw new Error('no caption');
+ }
+ const r = caption.getBoundingClientRect();
+ return {x: r.left + r.width / 2, y: r.top + r.height / 2};
+ });
+}
+
+test("a pinch on a zoomable gallery's caption still zooms the page", async ({
+ page,
+ browserName,
+}) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'native pinch-zoom from scripted touches is Chromium-only',
+ );
+ const g = await openGallery(page, {
+ story: 'core-lightbox--gallery-with-captions',
+ trigger: 'Open gallery with captions',
+ });
+ await g.driver.play(
+ pinch({
+ center: await captionCentre(g),
+ fromDistance: 30,
+ toDistance: 200,
+ durationMs: 400,
+ }),
+ );
+ await expect
+ .poll(async () => page.evaluate(() => window.visualViewport?.scale ?? 1))
+ .toBeGreaterThan(1.5);
+ expect((await g.photo()).scale).toBe(1);
+});
+
+test('a swipe that starts on a caption pages', async ({page}) => {
+ const g = await openGallery(page, {
+ story: 'core-lightbox--gallery-with-captions',
+ trigger: 'Open gallery with captions',
+ });
+ const from = await captionCentre(g);
+ await g.driver.play(slowDrag(from, -g.box.width * 0.6));
+ await waitForRest(g.track);
+ expect(await g.counter()).toMatch(/^2 \/ \d+$/);
+});
+
+test('a pinch zooms the photo and never pages', async ({page}) => {
+ const g = await openGallery(page);
+ const centre = {x: g.box.x + g.box.width / 2, y: g.box.y + g.box.height / 2};
+ await g.driver.play(driftingPinch(centre, -60));
+ await frames(page, 30);
+ expect((await g.photo()).scale).toBeGreaterThan(1.5);
+ expect(await g.trackX()).toBe(0);
+ expect(await g.counter()).toBe('1 / 4');
+});
+
+/**
+ * A drag by 60 % of a page. It holds still 300 ms before the lift, so the
+ * settle starts at rest on a loaded runner too.
+ */
+function swipeAtRest(
+ g: Gallery,
+ toward: 'next' | 'previous' = 'next',
+): TouchScript {
+ const sign = toward === 'next' ? 1 : -1;
+ const from = {
+ x: g.box.x + g.box.width * (0.5 + sign * 0.3),
+ y: g.box.y + g.box.height / 2,
+ };
+ return drag(
+ from,
+ {x: from.x - sign * g.box.width * 0.6, y: from.y},
+ {durationMs: 600, restMs: 300},
+ );
+}
+
+/** A run of the track's, on the page clock: its start and its curve's length. */
+interface TrackRun {
+ readonly from: number;
+ readonly curveMs: number;
+}
+
+/**
+ * Records every animation the track starts from here on. Lightbox retires a
+ * curve once it ends, and a block can outlast a curve at tempo 1. So a run
+ * is read from this record, which keeps it. Resolves with the reader.
+ */
+async function recordTrackRuns(
+ track: Locator,
+): Promise<() => Promise<TrackRun[]>> {
+ await track.evaluate(element => {
+ const runs: {animation: Animation; from: number}[] = [];
+ (window as unknown as {__trackRuns: typeof runs}).__trackRuns = runs;
+ const animate = Element.prototype.animate;
+ Element.prototype.animate = function (keyframes, options) {
+ const animation = animate.call(this, keyframes, options);
+ if (this === element) {
+ const run = {animation, from: Number.NaN};
+ runs.push(run);
+ // A retired run loses its start time, so it is kept as it starts.
+ void animation.ready.then(
+ () => {
+ run.from = performance.timeOrigin + Number(animation.startTime);
+ },
+ // Cancelled before it started: it has no start to keep.
+ () => undefined,
+ );
+ }
+ return animation;
+ };
+ });
+ return async () =>
+ track.page().evaluate(() =>
+ (
+ window as unknown as {
+ __trackRuns: {animation: Animation; from: number}[];
+ }
+ ).__trackRuns.map(({animation, from}) => {
+ const effect = animation.effect as KeyframeEffect;
+ const frames = effect.getKeyframes();
+ const xs = frames.map(frame =>
+ typeof frame.translate === 'string' ? parseFloat(frame.translate) : 0,
+ );
+ const end = xs[xs.length - 1];
+ // The curve ends where its hold of the end value begins.
+ let hold = xs.length - 1;
+ while (hold > 0 && Math.abs(xs[hold - 1] - end) < 0.01) {
+ hold -= 1;
+ }
+ const duration = Number(effect.getComputedTiming().duration);
+ return {
+ from,
+ curveMs: (frames[hold].computedOffset ?? 1) * duration,
+ };
+ }),
+ );
+}
+
+/** The slowed tempo the busy page-settle proofs play the viewer at. */
+const SETTLE_TEMPO = 5;
+
+/**
+ * Where a run's judgment starts. It is the block's start, or just after the
+ * block's first presented frame when that frame shows the photo unmoved. A
+ * compositor can present a frame it began before the block. Only that one
+ * frame is skipped, so a settle that stays still for two frames or more
+ * still fails.
+ */
+function afterInFlightFrame(
+ tracked: BusyRun['tracked'],
+ blockFrom: number,
+): number {
+ const before = tracked.filter(f => f.box != null && f.t <= blockFrom).at(-1);
+ const first = tracked.find(f => f.box != null && f.t > blockFrom);
+ if (before?.box == null || first?.box == null) {
+ return blockFrom;
+ }
+ return Math.abs(first.box.x - before.box.x) < 1 ? first.t + 1 : blockFrom;
+}
+
+/**
+ * Blocks the main thread for `ms` once the track's settle shows on screen.
+ * The rendering update that first sees the settle hands it to the
+ * compositor. A starved compositor can draw a frame or two before it applies
+ * it. WebKit runs the next rendering update only once its compositor has
+ * drawn the last one. So the block starts after that update, with the settle
+ * already moving on screen.
+ */
+async function blockOnceShown(
+ track: Locator,
+ ms: number,
+): Promise<BlockedWindow> {
+ return track.evaluate(
+ async (element, {duration}) =>
+ new Promise<BlockedWindow>((resolve, reject) => {
+ const deadline = performance.now() + 5_000;
+ const spin = () => {
+ const start = performance.now();
+ let now = start;
+ while (now - start < duration) {
+ now = performance.now();
+ }
+ resolve({
+ from: performance.timeOrigin + start,
+ to: performance.timeOrigin + now,
+ spanMs: now - start,
+ });
+ };
+ const tick = () => {
+ const isRunning = element
+ .getAnimations()
+ .some(
+ a =>
+ a.playState === 'running' &&
+ !a.pending &&
+ Number(a.currentTime ?? 0) >= 16,
+ );
+ if (!isRunning) {
+ if (performance.now() > deadline) {
+ reject(new Error('blockOnceShown: no settle started'));
+ } else {
+ requestAnimationFrame(tick);
+ }
+ return;
+ }
+ // This frame's rendering update hands the settle over. The block
+ // starts from a task after the next one.
+ requestAnimationFrame(() => {
+ setTimeout(spin, 0);
+ });
+ };
+ requestAnimationFrame(tick);
+ }),
+ {duration: ms},
+ );
+}
+
+/** The slowed settles a pooled proof judged, and what it read off them. */
+interface PooledSettles {
+ readonly proof: ReturnType<typeof pooledBusyProof>;
+ readonly blocks: ReadonlyArray<BlockedWindow>;
+ /** Each settle's run on the track, in order. */
+ readonly settles: ReadonlyArray<TrackRun>;
+}
+
+/**
+ * Plays a page settle toward each of `toward`, with the main thread blocked
+ * in each, and judges the runs pooled against the control. `shown` blocks
+ * once the settle shows on screen. `after-lift` blocks a moment after the
+ * lift, for a settle that never runs on the compositor. `onFirst` gets the
+ * first run's cast, for its storyboard.
+ */
+async function pooledSettleProof(
+ page: Page,
+ g: Gallery,
+ toward: ReadonlyArray<'next' | 'previous'>,
+ {
+ start = 'shown',
+ onFirst,
+ }: {
+ start?: 'shown' | 'after-lift';
+ onFirst?: (
+ castFrames: Parameters<typeof castStoryboard>[1],
+ tracked: BusyRun['tracked'],
+ block: BlockedWindow,
+ ) => Promise<void>;
+ } = {},
+): Promise<PooledSettles> {
+ const trackRuns = await recordTrackRuns(g.track);
+ const runs: BusyRun[] = [];
+ const blocks: BlockedWindow[] = [];
+ const settles: TrackRun[] = [];
+ for (const direction of toward) {
+ // The tracked photo keeps its left edge on screen as the page settles.
+ // Toward the next page it is the next photo, which slides in from the
+ // right. Back, it is the current one, which slides out to the right. A box
+ // clipped at the screen's edge reads as settled at once, and so does the
+ // track, which is wider than the screen.
+ const unmark = await markElement(
+ g.dialog.locator(
+ direction === 'next'
+ ? '[data-current] + [data-lightbox-page] img'
+ : '[data-current] img',
+ ),
+ {mode: 'outline'},
+ );
+ // A touch on a settle's held end catches it, and the block would start
+ // at that touch. So each run starts once the track runs no animation.
+ await expect
+ .poll(async () =>
+ g.track.evaluate(el =>
+ el.getAnimations().some(a => a.playState === 'running'),
+ ),
+ )
+ .toBe(false);
+ const cast = await startScreencast(page);
+ let block: BlockedWindow;
+ if (start === 'shown') {
+ // The page itself waits for the settle and blocks. A round trip from
+ // the test would start the block later still.
+ const blocking = blockOnceShown(g.track, 600);
+ await g.driver.play(swipeAtRest(g, direction));
+ block = await blocking;
+ } else {
+ await g.driver.play(swipeAtRest(g, direction));
+ await page.waitForTimeout(150);
+ block = await blockMainThread(page, 750);
+ }
+ // A few frames after the block, so the screencast holds its end.
+ await frames(page, 6);
+ const castFrames = await cast.stop();
+ const settle = (await trackRuns()).at(-1);
+ if (settle == null) {
+ throw new Error('no settle recorded');
+ }
+ const tracked = await trackMarker(page, castFrames);
+ runs.push({
+ tracked,
+ control: await trackMarker(page, castFrames, {rgb: CONTROL_RGB}),
+ window: {
+ from: afterInFlightFrame(tracked, block.from),
+ to: Math.min(block.to, settle.from + settle.curveMs),
+ },
+ });
+ blocks.push(block);
+ settles.push(settle);
+ if (runs.length === 1) {
+ await onFirst?.(castFrames, tracked, block);
+ }
+ await waitForRest(g.track);
+ await unmark();
+ }
+ // The settle slows at its end. Near the end a 60 Hz frame moves less than
+ // one cast step, so the cast shows plateaus there. Judging stops 12 cast
+ // steps from the end.
+ return {
+ proof: pooledBusyProof(runs, {axis: 'x', settledWithinSteps: 12}),
+ blocks,
+ settles,
+ };
+}
+
+test('the page settle keeps advancing every frame while the main thread is blocked', async ({
+ page,
+}, testInfo) => {
+ const g = await openGallery(page);
+ // A compositor-only control animation in the same windows: what the
+ // compositor presented while the main thread spun, on this machine.
+ await startBusyControl(page);
+ // While the main thread is blocked, a starved runner's compositor presents
+ // a frame only every 100 to 200 ms. At tempo 1 the settle moves for a
+ // third of a second, which leaves too few frames to judge. At tempo 5 it
+ // moves visibly for about 900 ms. A block of 600 ms that starts once the
+ // settle shows then ends well before the settle does. Six settles, to page
+ // 4 and back, are judged as one pool. A run whose control presented
+ // nothing is left out by name, and the pool needs three judged runs.
+ const restoreTempo = await slowViewer(page, SETTLE_TEMPO);
+ const {proof, blocks, settles} = await pooledSettleProof(
+ page,
+ g,
+ ['next', 'next', 'next', 'previous', 'previous', 'previous'],
+ {
+ onFirst: async (castFrames, tracked, block) => {
+ const film = await castStoryboard(page, castFrames, {
+ name: 'lightbox-page-settle-busy-main-thread',
+ zero: block.from,
+ from: block.from - 40,
+ to: block.to + 40,
+ columns: 8,
+ cellScale: 0.35,
+ data: t => ({x: tracked.find(f => f.t === t)?.box?.x ?? -1}),
+ });
+ await film.write(testInfo, {block});
+ },
+ },
+ );
+ expect(await g.counter()).toBe('1 / 4');
+ // The same settle at the default tempo, to compare the slowed ones with.
+ await restoreTempo();
+ const trackRuns = await recordTrackRuns(g.track);
+ await g.driver.play(swipeAtRest(g));
+ await waitForRest(g.track);
+ expect(await g.counter()).toBe('2 / 4');
+ const atTempo1 = (await trackRuns()).at(-1);
+ if (atTempo1 == null) {
+ throw new Error('no settle recorded at tempo 1');
+ }
+ const ratios = settles.map(settle => settle.curveMs / atTempo1.curveMs);
+ await writeEvidence(
+ 'busy-main-thread/lightbox-page-settle',
+ {
+ [`${testInfo.project.name}.json`]: JSON.stringify(
+ {blocks, settles, atTempo1, ratios, summary: proof.summary},
+ null,
+ 1,
+ ),
+ },
+ testInfo,
+ );
+ // The pager's own settle at tempo 5: five times as long as at tempo 1,
+ // and still running on the compositor when each block ends.
+ for (const [index, settle] of settles.entries()) {
+ expect(ratios[index], JSON.stringify(settles)).toBeGreaterThan(
+ SETTLE_TEMPO - 0.1,
+ );
+ expect(ratios[index], JSON.stringify(settles)).toBeLessThan(
+ SETTLE_TEMPO + 0.1,
+ );
+ expect(settle.from + settle.curveMs).toBeGreaterThan(blocks[index].to);
+ }
+ // Judged against the control. A two-core runner's software compositor and
+ // the screencast share the core the block spins on. So every compositor
+ // animation presents fewer frames there, the control's too. The photo keeps
+ // pace with the control, and a main-thread animation would not. A pool too
+ // short to judge fails too.
+ expect(proof.verdict.failures, proof.summary).toEqual([]);
+ for (const [index, run] of proof.runs.entries()) {
+ if (proof.judged[index]) {
+ expect(run?.monotonic, proof.summary).toBe(true);
+ }
+ }
+});
+
+/**
+ * Breaks the page settle for the busy proof's controls. `main-thread` pauses
+ * the track's animation and moves its time from frame callbacks, and
+ * `frozen` pauses it. `delayed` holds it still on the compositor for
+ * `delayMs` before it moves.
+ */
+async function breakSettle(
+ g: Gallery,
+ pace: 'main-thread' | 'frozen' | 'delayed',
+ delayMs = 0,
+): Promise<void> {
+ await g.track.evaluate(
+ (track, {mode, delay}) => {
+ const animate = Element.prototype.animate;
+ Element.prototype.animate = function (keyframes, options) {
+ if (this === track && mode === 'delayed') {
+ const timing =
+ typeof options === 'number' ? {duration: options} : {...options};
+ return animate.call(this, keyframes, {
+ ...timing,
+ delay: (timing.delay ?? 0) + delay,
+ });
+ }
+ const animation = animate.call(this, keyframes, options);
+ if (this !== track) {
+ return animation;
+ }
+ animation.pause();
+ if (mode === 'main-thread') {
+ const from = performance.now();
+ const start = Number(animation.currentTime ?? 0);
+ const step = (now: number) => {
+ if (animation.playState !== 'idle') {
+ animation.currentTime = start + now - from;
+ requestAnimationFrame(step);
+ }
+ };
+ requestAnimationFrame(step);
+ }
+ return animation;
+ };
+ },
+ {mode: pace, delay: delayMs},
+ );
+}
+
+for (const pace of ['main-thread', 'frozen'] as const) {
+ test(`the busy proof fails a slowed page settle that ${pace === 'frozen' ? 'freezes' : 'the main thread drives'}`, async ({
+ page,
+ }) => {
+ const g = await openGallery(page);
+ await startBusyControl(page);
+ await slowViewer(page, SETTLE_TEMPO);
+ await breakSettle(g, pace);
+ let failures: ReadonlyArray<string>;
+ try {
+ // Neither runs on the compositor, so the block starts after the lift.
+ const {proof} = await pooledSettleProof(page, g, ['next', 'next'], {
+ start: 'after-lift',
+ });
+ failures = proof.verdict.failures;
+ } catch (error) {
+ // A settle that never moved has settled before the window: a red too.
+ expect(error).toBeInstanceOf(BusyWindowTooLateError);
+ failures = [(error as Error).message];
+ }
+ expect(failures.length).toBeGreaterThan(0);
+ });
+}
+
+for (const late of ['two frames', '450 ms'] as const) {
+ test(`the busy proof fails a slowed page settle that stays still ${late} into the block`, async ({
+ page,
+ }) => {
+ const g = await openGallery(page);
+ await startBusyControl(page);
+ await slowViewer(page, SETTLE_TEMPO);
+ // A settle judged first gives this machine's numbers: how long after a
+ // settle starts its block starts, and the cast's frame interval. The
+ // delayed settle then stays still for that long, then for two frames and
+ // a little more or for 450 ms. That is past the one frame the proof
+ // skips.
+ const first = await pooledSettleProof(page, g, ['next']);
+ const blockAfterMs = first.blocks[0].from - first.settles[0].from;
+ // A run the pool left out has no frame interval to measure by.
+ const cadenceMs = first.proof.runs[0]?.cadenceMs;
+ expect(cadenceMs, first.proof.summary).toBeGreaterThan(0);
+ const stillMs = late === 'two frames' ? 2.2 * (cadenceMs ?? 0) : 450;
+ await breakSettle(g, 'delayed', blockAfterMs + stillMs);
+ const {proof} = await pooledSettleProof(page, g, ['next', 'next']);
+ // The photo misses a frame the control moved on, past the in-flight one.
+ expect(proof.verdict.failures.join('\n'), proof.summary).toMatch(
+ /moved on \d+ of the \d+ frames the control moved/,
+ );
+ });
+}
+
+test(
+ 'storyboard: a page swipe in the gallery',
+ {tag: '@storyboard'},
+ async ({page}, testInfo) => {
+ const g = await openGallery(page);
+ const from = {
+ x: g.box.x + g.box.width * 0.8,
+ y: g.box.y + g.box.height / 2,
+ };
+ const board = await touchStoryboard(
+ page,
+ g.driver,
+ drag(
+ from,
+ {x: from.x - g.box.width * 0.6, y: from.y},
+ {
+ durationMs: 300,
+ hz: 20,
+ restMs: 100,
+ },
+ ),
+ {
+ name: 'lightbox-page-swipe',
+ measure: async () => ({x: +(await g.trackX()).toFixed(1)}),
+ columns: 4,
+ cellScale: 0.35,
+ },
+ );
+ await board.write(testInfo);
+ await waitForRest(g.track);
+ expect(await g.counter()).toBe('2 / 4');
+ },
+);
+
+test('only the current page takes focus and is in the accessibility tree', async ({
+ page,
+}) => {
+ const g = await openGallery(page);
+ const next = g.dialog.getByRole('button', {name: 'Next'});
+ const b = await next.boundingBox();
+ if (b == null) {
+ throw new Error('no Next button');
+ }
+ await g.driver.tap({x: b.x + b.width / 2, y: b.y + b.height / 2});
+ await waitForRest(g.track);
+ expect(await g.counter()).toBe('2 / 4');
+ const pages = await g.track.evaluate(el =>
+ ([...el.children] as HTMLElement[]).map(p => ({
+ current: p.hasAttribute('data-current'),
+ inert: p.inert,
+ hidden: p.getAttribute('aria-hidden'),
+ })),
+ );
+ expect(pages.length).toBe(3);
+ for (const p of pages) {
+ expect(p.inert).toBe(!p.current);
+ expect(p.hidden).toBe(p.current ? null : 'true');
+ }
+ // Tab through the dialog: focus never enters a page off screen, and the
+ // stage never scrolls to show one.
+ for (let i = 0; i < 8; i++) {
+ await page.keyboard.press('Tab');
+ const where = await page.evaluate(() => {
+ const page = document.activeElement?.closest('[data-lightbox-page]');
+ if (page == null) {
+ return 'outside';
+ }
+ return page.hasAttribute('data-current') ? 'current' : 'off screen';
+ });
+ expect(where).not.toBe('off screen');
+ }
+ expect(await g.viewport.evaluate(el => el.scrollLeft)).toBe(0);
+});
+
+test('a controlled parent that keeps its index brings a swiped photo back', async ({
+ page,
+}) => {
+ const g = await openGallery(page, {
+ story: 'core-lightbox--gallery-keeps-index',
+ trigger: 'Open gallery that keeps its photo',
+ });
+ expect(await g.counter()).toBe('1 / 4');
+ const mid = {x: g.box.x + g.box.width * 0.8, y: g.box.y + g.box.height / 2};
+ await g.driver.play(slowDrag(mid, -g.box.width * 0.6));
+ await waitForRest(g.track);
+ await frames(page, 2);
+ await waitForRest(g.track);
+ expect(await g.counter()).toBe('1 / 4');
+ expect(await g.trackX()).toBeCloseTo(0, 0);
+ await expect(g.dialog).toHaveAccessibleName('Forest path');
+});
+
+test("two pages on, a rotation keeps a zoomed photo's centre point", async ({
+ page,
+}) => {
+ const g = await openGallery(page);
+ const next = g.dialog.getByRole('button', {name: 'Next'});
+ for (const expected of ['2 / 4', '3 / 4']) {
+ const b = await next.boundingBox();
+ if (b == null) {
+ throw new Error('no Next button');
+ }
+ await g.driver.tap({x: b.x + b.width / 2, y: b.y + b.height / 2});
+ await waitForRest(g.track);
+ expect(await g.counter()).toBe(expected);
+ }
+ const img = g.dialog.locator('[data-current] img');
+ const fitted = await img.boundingBox();
+ if (fitted == null) {
+ throw new Error('no photo');
+ }
+ await g.driver.play(
+ doubleTap({
+ x: fitted.x + fitted.width * 0.4,
+ y: fitted.y + fitted.height / 2,
+ }),
+ );
+ await waitForAnimation(img);
+ await waitForRest(img);
+ // Where the stage's centre falls on the photo, as a fraction of it.
+ const centreOnPhoto = async () => {
+ const photo = await img.boundingBox();
+ const stage = await g.viewport.boundingBox();
+ if (photo == null || stage == null) {
+ throw new Error('no photo');
+ }
+ return {
+ u: (stage.x + stage.width / 2 - photo.x) / photo.width,
+ v: (stage.y + stage.height / 2 - photo.y) / photo.height,
+ };
+ };
+ const before = await centreOnPhoto();
+ const size = page.viewportSize() ?? {width: 402, height: 714};
+ await page.setViewportSize({width: size.height, height: size.width});
+ await frames(page, 6);
+ await waitForRest(img);
+ const after = await centreOnPhoto();
+ expect(Math.abs(after.u - before.u)).toBeLessThan(0.02);
+ expect(Math.abs(after.v - before.v)).toBeLessThan(0.02);
+});
diff --git a/packages/core/src/Lightbox/__tests__/LightboxPagingModes.interaction.browser.spec.ts b/packages/core/src/Lightbox/__tests__/LightboxPagingModes.interaction.browser.spec.ts
new file mode 100644
index 0000000000..f9ac40d40b
--- /dev/null
+++ b/packages/core/src/Lightbox/__tests__/LightboxPagingModes.interaction.browser.spec.ts
@@ -0,0 +1,714 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file LightboxPagingModes.interaction.browser.spec.ts
+ * @input The built "Gallery with zoom" Lightbox story on the phone project,
+ * real touch input, the mouse and the interaction harness
+ * @output Proofs for Lightbox's pager outside plain touch. Under Reduce
+ * Motion, a swipe and the Next button on a touch screen page by a fade of
+ * 200 ms or less, with no slide. The Next button with a mouse pages at
+ * once, and a drag the owner refuses springs back over frames
+ * @position Interaction tests for Lightbox (browser), beside
+ * LightboxPaging.interaction.browser.spec.ts
+ */
+
+import {
+ expect,
+ test,
+ type Locator,
+ type Page,
+} from '@astryxdesign/a11y-spec/playwright';
+import {
+ drag,
+ frames,
+ openStory,
+ touchDriver,
+ waitForRest,
+ watchAnimations,
+ withStorybook,
+ type TouchDriver,
+ type TouchScript,
+} from '@astryxdesign/interaction-harness';
+
+const storybook = withStorybook(test);
+
+// Photos' gap between pages (motion/uikit/zoomMedia.ts), restated.
+const GAP = 40;
+
+/** A checkerboard photo with a disc whose colour tells the photos apart. */
+function photoSvg(color: string): string {
+ let squares = '';
+ for (let y = 0; y < 2000; y += 50) {
+ for (let x = 0; x < 3000; x += 50) {
+ if ((x + y) % 100 === 0) {
+ squares += `<rect x="${x}" y="${y}" width="50" height="50"/>`;
+ }
+ }
+ }
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="3000" height="2000" viewBox="0 0 3000 2000" shape-rendering="crispEdges"><rect width="3000" height="2000" fill="#fff"/><g fill="#000">${squares}</g><circle cx="1500" cy="1000" r="250" fill="${color}"/></svg>`;
+}
+
+const COLORS: Record<string, string> = {
+ '10': '#d22',
+ '15': '#2a2',
+ '20': '#22d',
+ '25': '#d80',
+};
+
+interface Gallery {
+ driver: TouchDriver;
+ dialog: Locator;
+ /** The pager's viewport (the stage), and the track it translates. */
+ viewport: Locator;
+ track: Locator;
+ /** The viewport's box on the page. */
+ box: {x: number; y: number; width: number; height: number};
+ counter: () => Promise<string>;
+ trackX: () => Promise<number>;
+ /** The current photo's zoom transform. */
+ photo: () => Promise<{x: number; scale: number}>;
+}
+
+async function openGallery(
+ page: Page,
+ {
+ rtl = false,
+ mouse = false,
+ story = 'core-lightbox--gallery-with-zoom',
+ trigger: triggerName = 'Open gallery with zoom',
+ } = {},
+): Promise<Gallery> {
+ await page.route('https://picsum.photos/**', async route => {
+ const id = /\/id\/(\d+)\//.exec(route.request().url())?.[1] ?? '10';
+ await route.fulfill({
+ contentType: 'image/svg+xml',
+ body: photoSvg(COLORS[id] ?? '#888'),
+ });
+ });
+ if (rtl) {
+ // Storybook's direction global sets the story's `dir` (and its
+ // providers'); openStory has no globals.
+ await page.goto(
+ `${storybook()}/iframe.html?id=core-lightbox--gallery-with-zoom&viewMode=story&globals=direction:rtl`,
+ );
+ await page.locator('#storybook-root > *').first().waitFor();
+ await frames(page, 2);
+ } else {
+ await openStory(page, storybook(), story);
+ }
+ const trigger = page.getByRole('button', {name: triggerName});
+ // A desktop has no touch input: its cases use the mouse alone.
+ const driver = mouse
+ ? (new Proxy(
+ {},
+ {
+ get: () => {
+ throw new Error('no touch on a desktop');
+ },
+ },
+ ) as TouchDriver)
+ : await touchDriver(page);
+ if (mouse) {
+ await trigger.click();
+ } else {
+ const t = await trigger.boundingBox();
+ if (t == null) {
+ throw new Error('no trigger');
+ }
+ await driver.tap({x: t.x + t.width / 2, y: t.y + t.height / 2});
+ }
+ const dialog = page.getByRole('dialog');
+ await expect(dialog).toBeVisible();
+ const viewport = dialog.getByRole('button', {name: 'Zoom'});
+ const track = viewport.locator(':scope > div').first();
+ await expect
+ .poll(async () =>
+ viewport.evaluate(el =>
+ [...el.querySelectorAll('img')].every(img => img.naturalWidth === 3000),
+ ),
+ )
+ .toBe(true);
+ await frames(page, 2);
+ const box = await viewport.evaluate(el => {
+ const r = el.getBoundingClientRect();
+ return {
+ x: r.left,
+ y: r.top,
+ width: el.clientWidth,
+ height: el.clientHeight,
+ };
+ });
+ return {
+ driver,
+ dialog,
+ viewport,
+ track,
+ box,
+ counter: async () =>
+ (await dialog.getByText(/^\d+ \/ \d+$/).textContent()) ?? '',
+ trackX: async () =>
+ track.evaluate(el => {
+ const value = getComputedStyle(el).translate;
+ return value === 'none' ? 0 : parseFloat(value);
+ }),
+ photo: async () =>
+ viewport.evaluate(el => {
+ const img = el.querySelector<HTMLElement>('[data-current] img');
+ if (img == null) {
+ return {x: 0, scale: 1};
+ }
+ const style = getComputedStyle(img);
+ return {
+ x: style.translate === 'none' ? 0 : parseFloat(style.translate),
+ scale: style.scale === 'none' ? 1 : parseFloat(style.scale),
+ };
+ }),
+ };
+}
+
+/** A slow drag by dx, held still before the lift (no release velocity). */
+function slowDrag(from: {x: number; y: number}, dx: number): TouchScript {
+ return drag(
+ from,
+ {x: from.x + dx, y: from.y},
+ {durationMs: 600, restMs: 150},
+ );
+}
+
+/**
+ * What an action starts on the track under Reduce Motion. A watch taken
+ * before the action catches its animations, since a 200 ms fade can end
+ * before the test looks. It returns their longest length, whether any of them
+ * moves the track, and the track's place every frame until rest.
+ */
+async function trackMotion(
+ page: Page,
+ track: Locator,
+ act: () => Promise<unknown>,
+) {
+ const watch = await watchAnimations(track);
+ await act();
+ // Installed before anything is awaited further (an awaited evaluate): the
+ // landing comes while the track is faded out, after this.
+ await track.evaluate(el => {
+ const places: number[] = [];
+ let running = true;
+ const tick = () => {
+ const value = getComputedStyle(el).translate;
+ places.push(value === 'none' ? 0 : parseFloat(value));
+ if (running) {
+ requestAnimationFrame(tick);
+ }
+ };
+ tick();
+ (
+ window as unknown as {__trackPlaces: {places: number[]; stop(): void}}
+ ).__trackPlaces = {
+ places,
+ stop: () => {
+ running = false;
+ },
+ };
+ });
+ const started = await watch.started();
+ await waitForRest(track);
+ const xs = await page.evaluate(() => {
+ const record = (
+ window as unknown as {__trackPlaces: {places: number[]; stop(): void}}
+ ).__trackPlaces;
+ record.stop();
+ return record.places;
+ });
+ return {
+ // Each curve's own length: a held end value is not part of it.
+ duration: Math.max(...started.map(a => a.to - a.from)),
+ travels: started.some(a =>
+ a.keyframes.some(k => 'translate' in k || 'transform' in k),
+ ),
+ xs,
+ };
+}
+
+test('under Reduce Motion a swipe pages by a fade of 200 ms or less: the track never slides', async ({
+ page,
+}) => {
+ // Under Reduce Motion, what a touch release starts fades in place; it never
+ // moves.
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ const g = await openGallery(page);
+ const mid = {x: g.box.x + g.box.width * 0.8, y: g.box.y + g.box.height / 2};
+ const {duration, travels, xs} = await trackMotion(page, g.track, async () => {
+ await g.driver.play(slowDrag(mid, -g.box.width * 0.6));
+ });
+ const page2 = -(g.box.width + GAP);
+ expect(duration).toBeLessThanOrEqual(205);
+ // The track lands with a style write while it is faded out. No animation
+ // moves it, and every frame shows where the finger left it or the next
+ // page, nothing between.
+ expect(travels).toBe(false);
+ for (const x of xs) {
+ expect(Math.min(Math.abs(x - xs[0]), Math.abs(x - page2))).toBeLessThan(
+ 0.5,
+ );
+ }
+ expect(await g.counter()).toBe('2 / 4');
+ expect(await g.trackX()).toBeCloseTo(page2, 0);
+});
+
+test('under Reduce Motion the Next button pages by a fade on a touch screen, never a slide', async ({
+ page,
+}) => {
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ const g = await openGallery(page);
+ const next = await g.dialog.getByRole('button', {name: 'Next'}).boundingBox();
+ if (next == null) {
+ throw new Error('no Next');
+ }
+ const {duration, travels, xs} = await trackMotion(page, g.track, async () => {
+ await g.driver.tap({
+ x: next.x + next.width / 2,
+ y: next.y + next.height / 2,
+ });
+ });
+ const page2 = -(g.box.width + GAP);
+ expect(duration).toBeLessThanOrEqual(205);
+ expect(travels).toBe(false);
+ for (const x of xs) {
+ expect(Math.min(Math.abs(x), Math.abs(x - page2))).toBeLessThan(0.5);
+ }
+ await waitForRest(g.track);
+ expect(await g.counter()).toBe('2 / 4');
+});
+
+test('under Reduce Motion the Next button pages at once with a mouse', async ({
+ browser,
+}) => {
+ // Under Reduce Motion, any pointer but a coarse one pages at once.
+ const context = await browser.newContext({
+ viewport: {width: 1280, height: 800},
+ hasTouch: false,
+ isMobile: false,
+ reducedMotion: 'reduce',
+ });
+ try {
+ const page = await context.newPage();
+ // A fine primary pointer in this context (the interaction config can report
+ // a coarse one without touch).
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ const g = await openGallery(page, {mouse: true});
+ await g.dialog.getByRole('button', {name: 'Next'}).click();
+ await frames(page, 1);
+ expect(await g.counter()).toBe('2 / 4');
+ expect(
+ await g.track.evaluate(
+ el => el.getAnimations().filter(a => a.playState === 'running').length,
+ ),
+ ).toBe(0);
+ } finally {
+ await context.close();
+ }
+});
+
+test('with a mouse the Next button shows the next photo at once', async ({
+ browser,
+}) => {
+ const context = await browser.newContext({
+ viewport: {width: 1280, height: 800},
+ hasTouch: false,
+ isMobile: false,
+ });
+ try {
+ const page = await context.newPage();
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ const g = await openGallery(page, {mouse: true});
+ await g.dialog.getByRole('button', {name: 'Next'}).click();
+ await frames(page, 1);
+ expect(await g.counter()).toBe('2 / 4');
+ expect(
+ await g.track.evaluate(
+ el => el.getAnimations().filter(a => a.playState === 'running').length,
+ ),
+ ).toBe(0);
+ } finally {
+ await context.close();
+ }
+});
+
+test('with a mouse a Next the owner refuses never moves the photo', async ({
+ browser,
+}) => {
+ const context = await browser.newContext({
+ viewport: {width: 1280, height: 800},
+ hasTouch: false,
+ isMobile: false,
+ });
+ try {
+ const page = await context.newPage();
+ const g = await openGallery(page, {
+ mouse: true,
+ story: 'core-lightbox--gallery-keeps-index',
+ trigger: 'Open gallery that keeps its photo',
+ });
+ // Reads the track's offset on every frame from the press on.
+ await g.track.evaluate(track => {
+ const offsets: number[] = [];
+ (window as unknown as {__offsets: number[]}).__offsets = offsets;
+ const tick = () => {
+ const value = getComputedStyle(track).translate;
+ offsets.push(value === 'none' ? 0 : parseFloat(value));
+ if (offsets.length < 40) {
+ requestAnimationFrame(tick);
+ }
+ };
+ requestAnimationFrame(tick);
+ });
+ await g.dialog.getByRole('button', {name: 'Next'}).click();
+ await expect
+ .poll(async () =>
+ page.evaluate(
+ () => (window as unknown as {__offsets: number[]}).__offsets.length,
+ ),
+ )
+ .toBe(40);
+ const offsets = await page.evaluate(
+ () => (window as unknown as {__offsets: number[]}).__offsets,
+ );
+ expect(offsets.every(x => Math.abs(x) < 0.5)).toBe(true);
+ expect(await g.counter()).toBe('1 / 4');
+ } finally {
+ await context.close();
+ }
+});
+
+test('a drag the owner refuses springs back over frames', async ({page}) => {
+ const g = await openGallery(page, {
+ story: 'core-lightbox--gallery-keeps-index',
+ trigger: 'Open gallery that keeps its photo',
+ });
+ const mid = {x: g.box.x + g.box.width * 0.8, y: g.box.y + g.box.height / 2};
+ // Records the positions of every animation the track starts from here on.
+ await g.track.evaluate(track => {
+ const runs: string[][] = [];
+ (window as unknown as {__trackRuns: string[][]}).__trackRuns = runs;
+ const animate = Element.prototype.animate;
+ Element.prototype.animate = function (keyframes, options) {
+ const animation = animate.call(this, keyframes, options);
+ if (this === track && animation.effect instanceof KeyframeEffect) {
+ runs.push(
+ animation.effect
+ .getKeyframes()
+ .map(frame =>
+ typeof frame.translate === 'string' ? frame.translate : '',
+ ),
+ );
+ }
+ return animation;
+ };
+ });
+ // Past half a page: the release pages, and the owner keeps its photo.
+ await g.driver.play(
+ drag(
+ mid,
+ {x: mid.x - g.box.width * 0.6, y: mid.y},
+ {durationMs: 400, restMs: 100},
+ ),
+ );
+ await waitForRest(g.track);
+ expect(Math.abs(await g.trackX())).toBeLessThan(0.5);
+ expect(await g.counter()).toBe('1 / 4');
+ // It springs back over frames. The track's last animation brought the
+ // photo back, from more than half a page away to rest, through positions
+ // in between. They are read from its keyframes, which a loaded runner's
+ // slow main thread does not thin out.
+ const runs = await page.evaluate(
+ () => (window as unknown as {__trackRuns: string[][]}).__trackRuns,
+ );
+ const xs = (runs.at(-1) ?? []).map(x => parseFloat(x) || 0);
+ const detail = JSON.stringify(runs);
+ expect(Math.abs(xs[0] ?? 0), detail).toBeGreaterThan(g.box.width / 2);
+ expect(Math.abs(xs.at(-1) ?? Number.NaN), detail).toBeLessThan(0.5);
+ const between = xs.filter(
+ x => Math.abs(x) >= 0.5 && Math.abs(x) <= Math.abs(xs[0] ?? 0) - 0.5,
+ );
+ expect(between.length, detail).toBeGreaterThanOrEqual(4);
+});
+
+test('with a mouse (a fine pointer) a click beside the photo closes the gallery, one on it does not', async ({
+ browser,
+}) => {
+ // A tall viewport leaves stage below the photo: the stage fills the viewer,
+ // the photo keeps its 3:2 aspect.
+ const context = await browser.newContext({
+ viewport: {width: 1280, height: 1400},
+ hasTouch: false,
+ isMobile: false,
+ });
+ try {
+ const page = await context.newPage();
+ // A fine primary pointer in this context (the interaction config can report
+ // a coarse one without touch).
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ const g = await openGallery(page, {mouse: true});
+ const photo = await g.dialog.locator('[data-current] img').boundingBox();
+ if (photo == null) {
+ throw new Error('no photo');
+ }
+ const below = {
+ x: photo.x + photo.width / 2,
+ y: (photo.y + photo.height + g.box.y + g.box.height) / 2,
+ };
+ // The point is on the stage beside the photo, not on a control.
+ expect(
+ await page.evaluate(({x, y}) => {
+ const el = document.elementFromPoint(x, y);
+ return (
+ el != null &&
+ el.closest('[data-lightbox-chrome]') == null &&
+ el.tagName !== 'IMG'
+ );
+ }, below),
+ ).toBe(true);
+ // A click on the photo itself leaves the viewer open.
+ await page.mouse.click(
+ photo.x + photo.width / 2,
+ photo.y + photo.height / 2,
+ );
+ // A single tap waits out the double tap's 300 ms. Forty frames pass that
+ // at up to 120 Hz.
+ await frames(page, 40);
+ await expect(g.dialog).toBeVisible();
+ await page.mouse.click(below.x, below.y);
+ await expect(g.dialog).toBeHidden();
+ } finally {
+ await context.close();
+ }
+});
+
+for (const [label, hold] of [
+ ['moves 60 px before its release', false],
+ ['is held 1.6 s before its release', true],
+] as const) {
+ test(`without zoom, a mouse press beside the photo that ${label} closes the gallery, as on main`, async ({
+ browser,
+ }) => {
+ // A tall viewport leaves stage above the photo. The tap's movement and
+ // time limits are a finger's; a mouse's click closes as on the backdrop.
+ const context = await browser.newContext({
+ viewport: {width: 1280, height: 1400},
+ hasTouch: false,
+ isMobile: false,
+ });
+ try {
+ const page = await context.newPage();
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ await page.route('https://picsum.photos/**', async route =>
+ route.fulfill({contentType: 'image/svg+xml', body: photoSvg('#888')}),
+ );
+ await openStory(page, storybook(), 'core-lightbox--gallery');
+ await page.locator('#storybook-root img').first().click();
+ const dialog = page.getByRole('dialog');
+ await expect(dialog).toBeVisible();
+ const img = dialog.locator('[data-current] img');
+ await expect
+ .poll(async () => (await img.boundingBox())?.width ?? 0)
+ .toBeGreaterThan(100);
+ const photo = await img.boundingBox();
+ if (photo == null) {
+ throw new Error('no photo');
+ }
+ const above = {x: photo.x + photo.width / 2, y: photo.y - 40};
+ // The point is on the stage beside the photo, not on a control.
+ expect(
+ await page.evaluate(({x, y}) => {
+ const el = document.elementFromPoint(x, y);
+ return (
+ el != null &&
+ el.closest('dialog') != null &&
+ el.closest('[data-lightbox-chrome]') == null &&
+ el.closest('[data-lightbox-caption]') == null &&
+ el.tagName !== 'IMG'
+ );
+ }, above),
+ ).toBe(true);
+ await page.mouse.move(above.x, above.y);
+ await page.mouse.down();
+ if (hold) {
+ await page.waitForTimeout(1600);
+ } else {
+ await page.mouse.move(above.x + 60, above.y, {steps: 6});
+ }
+ await page.mouse.up();
+ await expect(dialog).toBeHidden();
+ } finally {
+ await context.close();
+ }
+ });
+}
+
+test('without zoom, a mouse press beside the photo that is released on it closes the gallery, as on main', async ({
+ browser,
+}) => {
+ const context = await browser.newContext({
+ viewport: {width: 1280, height: 1400},
+ hasTouch: false,
+ isMobile: false,
+ });
+ try {
+ const page = await context.newPage();
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ await page.route('https://picsum.photos/**', async route =>
+ route.fulfill({contentType: 'image/svg+xml', body: photoSvg('#888')}),
+ );
+ await openStory(page, storybook(), 'core-lightbox--gallery');
+ await page.locator('#storybook-root img').first().click();
+ const dialog = page.getByRole('dialog');
+ await expect(dialog).toBeVisible();
+ const img = dialog.locator('[data-current] img');
+ await expect
+ .poll(async () => (await img.boundingBox())?.width ?? 0)
+ .toBeGreaterThan(100);
+ const photo = await img.boundingBox();
+ if (photo == null) {
+ throw new Error('no photo');
+ }
+ const above = {x: photo.x + photo.width / 2, y: photo.y - 40};
+ expect(
+ await page.evaluate(({x, y}) => {
+ const el = document.elementFromPoint(x, y);
+ return (
+ el != null &&
+ el.closest('dialog') != null &&
+ el.closest('[data-lightbox-chrome]') == null &&
+ el.closest('[data-lightbox-caption]') == null &&
+ el.tagName !== 'IMG'
+ );
+ }, above),
+ ).toBe(true);
+ // The press starts on the dark area and ends on the photo.
+ await page.mouse.move(above.x, above.y);
+ await page.mouse.down();
+ await page.mouse.move(above.x, photo.y + photo.height / 2, {steps: 6});
+ await page.mouse.up();
+ await expect(dialog).toBeHidden();
+ } finally {
+ await context.close();
+ }
+});
+
+test('without zoom, a mouse click beside a photo narrower than its caption leaves the gallery open, as on main', async ({
+ browser,
+}) => {
+ const context = await browser.newContext({
+ viewport: {width: 1280, height: 800},
+ hasTouch: false,
+ isMobile: false,
+ });
+ try {
+ const page = await context.newPage();
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ // A tall, narrow photo fits narrower than its caption.
+ await page.route('https://picsum.photos/**', async route =>
+ route.fulfill({
+ contentType: 'image/svg+xml',
+ body: '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="1200"><rect width="200" height="1200" fill="#888"/></svg>',
+ }),
+ );
+ await openStory(page, storybook(), 'core-lightbox--gallery');
+ await page.locator('#storybook-root img').first().click();
+ const dialog = page.getByRole('dialog');
+ await expect(dialog).toBeVisible();
+ const img = dialog.locator('[data-current] img');
+ const caption = dialog.locator('[data-current] [data-lightbox-caption]');
+ await expect
+ .poll(async () => (await img.boundingBox())?.height ?? 0)
+ .toBeGreaterThan(100);
+ const photo = await img.boundingBox();
+ const text = await caption.boundingBox();
+ if (photo == null || text == null) {
+ throw new Error('no photo or caption');
+ }
+ // The caption is wider than the photo, with room beside the photo.
+ expect(text.x + text.width).toBeGreaterThan(photo.x + photo.width + 20);
+ const beside = {
+ x: (photo.x + photo.width + text.x + text.width) / 2,
+ y: photo.y + photo.height / 2,
+ };
+ expect(
+ await page.evaluate(({x, y}) => {
+ const el = document.elementFromPoint(x, y);
+ return (
+ el != null &&
+ el.closest('dialog') != null &&
+ el.closest('[data-lightbox-chrome]') == null &&
+ el.closest('[data-lightbox-caption]') == null &&
+ el.tagName !== 'IMG'
+ );
+ }, beside),
+ ).toBe(true);
+ await page.mouse.click(beside.x, beside.y);
+ await frames(page, 40);
+ await expect(dialog).toBeVisible();
+ } finally {
+ await context.close();
+ }
+});
+
+test('with a mouse a click in the slot a moved-up caption leaves closes the gallery', async ({
+ browser,
+}) => {
+ // With zoom a caption moves up under its fitted photo. The strip it leaves
+ // at the page's bottom edge is the backdrop, as without zoom.
+ const context = await browser.newContext({
+ viewport: {width: 1280, height: 1100},
+ hasTouch: false,
+ isMobile: false,
+ });
+ try {
+ const page = await context.newPage();
+ expect(
+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),
+ ).toBe(false);
+ const g = await openGallery(page, {
+ mouse: true,
+ story: 'core-lightbox--gallery-with-captions',
+ trigger: 'Open gallery with captions',
+ });
+ const slot = await g.dialog.locator('[data-current]').evaluate(current => {
+ const r = current.getBoundingClientRect();
+ const caption = current
+ .querySelector('[data-lightbox-caption]')
+ ?.getBoundingClientRect();
+ return {
+ x: r.left + r.width / 2,
+ y: r.bottom - 4,
+ captionBottom: caption?.bottom ?? Number.NaN,
+ };
+ });
+ // The caption sits above the strip, so the point is the page's own.
+ expect(slot.captionBottom).toBeLessThan(slot.y);
+ expect(
+ await page.evaluate(
+ ({x, y}) =>
+ document.elementFromPoint(x, y)?.hasAttribute('data-lightbox-page') ??
+ false,
+ slot,
+ ),
+ ).toBe(true);
+ await page.mouse.click(slot.x, slot.y);
+ await expect(g.dialog).toBeHidden();
+ } finally {
+ await context.close();
+ }
+});
diff --git a/packages/core/src/Lightbox/__tests__/LightboxZoom.interaction.browser.spec.ts b/packages/core/src/Lightbox/__tests__/LightboxZoom.interaction.browser.spec.ts
index 2068496225..c8d2abb5ec 100644
--- a/packages/core/src/Lightbox/__tests__/LightboxZoom.interaction.browser.spec.ts
+++ b/packages/core/src/Lightbox/__tests__/LightboxZoom.interaction.browser.spec.ts
@@ -19,7 +19,6 @@ import {
type Locator,
type Page,
} from '@astryxdesign/a11y-spec/playwright';
-import {themeTempo} from '../../motion/themeTempo';
// @ts-expect-error -- pngjs ships no declarations; runtime support is pinned.
import {PNG} from 'pngjs';
import {
@@ -68,6 +67,7 @@ import {
type TouchScript,
} from '@astryxdesign/interaction-harness';
import {recordLiftOffset} from './liftOffset';
+import {slowViewer} from './viewerTempo';
const storybook = withStorybook(test);
@@ -793,6 +793,51 @@ test('a zoomed pan tracks the finger, rubber-bands past the edge and returns', a
expect(back.scale).toBeCloseTo(zoomed.scale, 6);
});
+test("a single zoomed photo's drag outward from the edge it rests at rubber-bands and returns", async ({
+ page,
+}) => {
+ const {driver, photo, state} = await openViewer(page);
+ const before = await state();
+ const mid = {x: 201, y: before.stage.y + before.stage.height / 2};
+ await driver.play(doubleTap(mid));
+ await waitForAnimation(photo);
+ await waitForRest(photo);
+ const zoomed = await state();
+ // First the photo comes to rest with its left edge on the screen's.
+ const room = -(zoomed.fit.x + zoomed.x);
+ await driver.play(
+ drag(mid, {x: mid.x + room + 10, y: mid.y}, {durationMs: 400, restMs: 150}),
+ );
+ await waitForRest(photo);
+ const atEdge = await state();
+ expect(atEdge.fit.x + atEdge.x).toBeCloseTo(0, 1);
+ // Then a drag that starts there and heads outward. With no pager to take
+ // it, the pan begins and gives past the edge, as on main.
+ const overshoot = 120;
+ const xs: number[] = [];
+ await driver.play(
+ drag(
+ mid,
+ {x: mid.x + overshoot + 10, y: mid.y},
+ {durationMs: 500, restMs: 150},
+ ),
+ {
+ onEvent: async step => {
+ if (step.type === 'touchMove') {
+ xs.push((await state()).x);
+ }
+ },
+ },
+ );
+ const d = zoomed.stage.width;
+ const banded = (1 - 1 / ((overshoot * 0.55) / d + 1)) * d;
+ expect(xs.at(-1)).toBeCloseTo(atEdge.x + banded, 0);
+ await waitForRest(photo);
+ const back = await state();
+ expect(back.fit.x + back.x).toBeCloseTo(0, 1);
+ expect(back.scale).toBeCloseTo(zoomed.scale, 6);
+});
+
test('a zoomed flick coasts and stops at the far edge', async ({page}) => {
const {driver, photo, state} = await openViewer(page);
const before = await state();
@@ -956,6 +1001,9 @@ test('a finger left down after a pinch keeps panning without a jump', async ({
const xs: {type: string; x: number}[] = [];
await driver.play(script, {
onEvent: async step => {
+ // A touchmove nothing has cancelled yet reaches the page with the next
+ // frame (Chromium aligns them to it): read once it has.
+ await frames(page, 1);
xs.push({type: step.type, x: (await state()).x});
},
});
@@ -1007,7 +1055,7 @@ test('the double-tap zoom keeps advancing every frame while the main thread is b
// With the main thread blocked, a loaded runner's compositor presents a
// frame every 100 to 250 ms. The spring moves for half a second, which
// leaves too few frames to judge. So the zoom plays at a slow tempo.
- await slowZoom(page);
+ await slowViewer(page, ZOOM_TEMPO);
const since = await page.evaluate(() => performance.now());
const cast = await startScreencast(page);
// The page itself waits for the zoom and blocks one frame into it. The
@@ -1078,27 +1126,6 @@ test('the double-tap zoom keeps advancing every frame while the main thread is b
expect(proof.monotonic).toBe(true);
});
-/**
- * The custom property Lightbox's motion reads its tempo from, asked of
- * `themeTempo` itself. A rename there renames it here too.
- */
-function tempoProperty(): string {
- let read = '';
- const view = {
- getComputedStyle: () => ({
- getPropertyValue: (name: string) => {
- read = name;
- return '';
- },
- }),
- };
- themeTempo({ownerDocument: {defaultView: view}} as unknown as Element);
- if (!read.startsWith('--')) {
- throw new Error(`themeTempo read no custom property: "${read}"`);
- }
- return read;
-}
-
/**
* The tempo the busy zoom proof plays the viewer at. Blocked, WebKit's
* software compositor on a loaded runner presents a frame only every 190 to
@@ -1119,18 +1146,6 @@ const ZOOM_BLOCK_MS = 2500;
*/
const ZOOM_SETTLED_STEPS = 24;
-/**
- * Plays the viewer's motion at `ZOOM_TEMPO`, through the property its motion
- * reads. A theme's tempo stops at 1.5, so this tempo is for the busy proof
- * only. Every element in the viewer carries it, so no nested theme's own
- * tempo wins.
- */
-async function slowZoom(page: Page): Promise<void> {
- await page.addStyleTag({
- content: `dialog, dialog * { ${tempoProperty()}: ${ZOOM_TEMPO} !important; }`,
- });
-}
-
/** Each animated property's curve length, and whether it still runs. */
function curvesByProperty(runs: ReadonlyArray<ActiveAnimation>) {
const meta = new Set(['offset', 'easing', 'composite', 'computedOffset']);
@@ -1189,7 +1204,7 @@ for (const pace of ['main-thread', 'frozen'] as const) {
const before = await state();
await markElement(photo, {mode: 'outline'});
await startBusyControl(page);
- await slowZoom(page);
+ await slowViewer(page, ZOOM_TEMPO);
await breakZoom(page, pace);
const cast = await startScreencast(page);
await driver.play(
diff --git a/packages/core/src/Lightbox/__tests__/viewerTempo.ts b/packages/core/src/Lightbox/__tests__/viewerTempo.ts
new file mode 100644
index 0000000000..54c8ca1780
--- /dev/null
+++ b/packages/core/src/Lightbox/__tests__/viewerTempo.ts
@@ -0,0 +1,56 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file viewerTempo.ts
+ * @input themeTempo.ts, for the custom property Lightbox's motion reads its
+ * tempo from
+ * @output `slowViewer`: plays the open viewer's motion at a slow tempo, 3
+ * unless a proof asks for another, until the function it returns runs
+ * @position Test helper for the Lightbox interaction specs' busy-main-thread
+ * proofs
+ */
+
+import type {Page} from '@astryxdesign/a11y-spec/playwright';
+import {themeTempo} from '../../motion/themeTempo';
+
+/**
+ * The custom property Lightbox's motion reads its tempo from, asked of
+ * `themeTempo` itself. A rename there renames it here too.
+ */
+function tempoProperty(): string {
+ let read = '';
+ const view = {
+ getComputedStyle: () => ({
+ getPropertyValue: (name: string) => {
+ read = name;
+ return '';
+ },
+ }),
+ };
+ themeTempo({ownerDocument: {defaultView: view}} as unknown as Element);
+ if (!read.startsWith('--')) {
+ throw new Error(`themeTempo read no custom property: "${read}"`);
+ }
+ return read;
+}
+
+/**
+ * Plays the open viewer's motion at `tempo`, through the property its motion
+ * reads. A theme's tempo stops at 1.5, so a slower tempo is for these proofs
+ * only. Every element in the viewer carries it, so no nested theme's own
+ * tempo wins. Resolves with a function that puts the viewer's own tempo back.
+ */
+export async function slowViewer(
+ page: Page,
+ tempo = 3,
+): Promise<() => Promise<void>> {
+ const style = await page.addStyleTag({
+ content: `dialog, dialog * { ${tempoProperty()}: ${tempo} !important; }`,
+ });
+ return async () => {
+ await style.evaluate(element => {
+ element.parentNode?.removeChild(element);
+ });
+ await style.dispose();
+ };
+}
diff --git a/packages/core/src/Lightbox/useZoomCore.ts b/packages/core/src/Lightbox/useZoomCore.ts
index f13fa2d500..6c8d5a5e41 100644
--- a/packages/core/src/Lightbox/useZoomCore.ts
+++ b/packages/core/src/Lightbox/useZoomCore.ts
@@ -4,11 +4,13 @@
/**
* @file useZoomCore.ts
- * @input A stage element ref (clipping and centring the photo), the current
- * item's key, and the zoom and fit callbacks
+ * @input A stage element ref, which clips and centres the photo, and the
+ * element the gestures attach to: the stage, or a gallery's track. Also
+ * whether zoom is on, the current item's key and the zoom and fit callbacks
* @output Exports `useZoomCore`: Lightbox's zoom stage for every pointer. It
* writes the photo's transform through the compositor animator and settles
- * every zoom, the keyboard's zoom and pan included, on `springs.settle`
+ * every zoom, the keyboard's zoom and pan included, on `springs.settle`. Its
+ * API tells an outer pager when the photo is at an edge (`isAtEdge`)
* @position Lightbox's shared zoom stage, internal. useZoomStage.ts drives
* its pointer paths; the geometry is in zoomStage.ts.
*
@@ -33,6 +35,7 @@ import {
maxScaleFor,
pannedBy,
releasedZoomTarget,
+ restRange,
restingTransform,
transformForResize,
type StagePoint,
@@ -43,9 +46,21 @@ import {
/** Set on the stage while a finger or the mouse drags a zoomed photo. */
export const ZOOM_DRAGGING_ATTRIBUTE = 'data-zoom-dragging';
+/** A drag's initial direction on screen. */
+export type PanDirection = 'left' | 'right';
+
export interface UseZoomCoreOptions {
- /** The stage: the photo's clipping parent, which centres it. */
+ /** The stage: the box the photo is fitted and centred in, clipping it. */
stageRef: RefObject<HTMLElement | null>;
+ /**
+ * Where the gestures attach and what the resize observer watches: the
+ * stage by default. In a pager, the track (the pager's own pan sits on
+ * the stage, each element has one `touch-action`, and every page shares
+ * the track's size).
+ */
+ surfaceRef?: RefObject<HTMLElement | null>;
+ /** Zoom is on (an image item with `hasZoom`). */
+ isEnabled: boolean;
/** Changes when another item shows; the photo returns to the fitted size. */
itemKey: unknown;
/** The photo became zoomed or returned to the fitted size. */
@@ -85,6 +100,12 @@ export interface ZoomStage {
* keeps the system's double-click speed.
*/
doubleClickAt(clientX: number, clientY: number): void;
+ /**
+ * Whether a zoomed photo can no longer move with a drag toward
+ * `direction`, since its edge on that side is at the stage's. A pager takes
+ * such a drag, as an outer paging scroll view does.
+ */
+ isAtEdge(direction: PanDirection): boolean;
}
/** The core as the gestures (useZoomStage.ts) drive it. */
@@ -109,6 +130,10 @@ export interface ZoomCore {
/** Where the photo is going, when an animation the core did not start ends there. */
setTarget(transform: ZoomTransform): void;
setZoomed(next: boolean): void;
+ /** Whether the photo is moving (shown away from where it is going). */
+ isMoving(): boolean;
+ /** Whether a zoomed photo's edge toward `direction` is at the stage's. */
+ isAtEdgeOf(geometry: ZoomGeometry, direction: PanDirection): boolean;
/**
* Settles on `springs.settle`: a release past a limit, a double tap, a
* double-click and the keyboard's zoom and pan. Lightbox's main interaction
@@ -251,6 +276,27 @@ export function useZoomCore(options: UseZoomCoreOptions): ZoomCore {
targetRef.current = transform;
}, []);
+ const isMoving = useCallback((): boolean => {
+ const shown = current();
+ const target = targetRef.current;
+ return (
+ Math.abs(shown.x - target.x) > 0.01 ||
+ Math.abs(shown.y - target.y) > 0.01 ||
+ Math.abs(shown.scale - target.scale) > 0.0001
+ );
+ }, [current]);
+
+ const isAtEdgeOf = useCallback(
+ (geometry: ZoomGeometry, direction: PanDirection): boolean => {
+ const {x, scale} = targetRef.current;
+ const range = restRange(geometry, scale);
+ return direction === 'left'
+ ? x <= range.x.min + 0.5
+ : x >= range.x.max - 0.5;
+ },
+ [],
+ );
+
const setZoomed = useCallback((next: boolean) => {
if (zoomedRef.current !== next) {
zoomedRef.current = next;
@@ -333,7 +379,9 @@ export function useZoomCore(options: UseZoomCoreOptions): ZoomCore {
}, [animator, options.itemKey, setAtFit]);
// A rotation or resize keeps the same photo point centred at the same
- // on-screen size (the shared resize observer).
+ // on-screen size (the shared resize observer). It watches the surface: in
+ // a gallery the stage moves to each current page, while the track, whose
+ // size every page shares, stays.
const onResize = useCallback(() => {
const before = geometryRef.current;
if (before == null || !zoomedRef.current) {
@@ -348,17 +396,23 @@ export function useZoomCore(options: UseZoomCoreOptions): ZoomCore {
write(next);
setZoomed(isZoomed(after, next));
}, [animator, measure, setZoomed, write]);
- // The stage mounts with the viewer's first media, which can come after the
+ // The surface mounts with the viewer's first media, which can come after the
// viewer, as in a gallery mounted closed while its photos load.
- // `useAttachment` follows the element after every commit.
+ // `useAttachment` follows the element, and zoom turning on or off, after
+ // every commit.
+ const surfaceRef = options.surfaceRef ?? options.stageRef;
+ const isEnabled = options.isEnabled;
const onResizeRef = useRef(onResize);
useIsomorphicLayoutEffect(() => {
onResizeRef.current = onResize;
});
useAttachment(
- options.stageRef,
- stage => observeResize(stage, () => onResizeRef.current()),
- null,
+ surfaceRef,
+ surface =>
+ isEnabled
+ ? observeResize(surface, () => onResizeRef.current())
+ : () => {},
+ isEnabled,
);
// The keyboard works on where the photo is going, like UIKit's model
@@ -404,8 +458,24 @@ export function useZoomCore(options: UseZoomCoreOptions): ZoomCore {
const point = toStage({x: clientX, y: clientY});
settleTo(geometry, doubleClickTarget(geometry, current(), point));
},
+ isAtEdge: (direction: PanDirection) => {
+ const geometry = geometryRef.current ?? measure();
+ if (geometry == null || !zoomedRef.current) {
+ return true;
+ }
+ return isAtEdgeOf(geometry, direction);
+ },
}),
- [contentRef, current, measure, settleTo, toStage, zoomIn, zoomOut],
+ [
+ contentRef,
+ current,
+ isAtEdgeOf,
+ measure,
+ settleTo,
+ toStage,
+ zoomIn,
+ zoomOut,
+ ],
);
// One object for the component's lifetime: every member is stable.
@@ -423,6 +493,8 @@ export function useZoomCore(options: UseZoomCoreOptions): ZoomCore {
write,
setTarget,
setZoomed,
+ isMoving,
+ isAtEdgeOf,
settleTo,
}),
[
@@ -434,6 +506,8 @@ export function useZoomCore(options: UseZoomCoreOptions): ZoomCore {
write,
setTarget,
setZoomed,
+ isMoving,
+ isAtEdgeOf,
settleTo,
],
);
diff --git a/packages/core/src/Lightbox/useZoomStage.ts b/packages/core/src/Lightbox/useZoomStage.ts
index 062400f851..b77f28c171 100644
--- a/packages/core/src/Lightbox/useZoomStage.ts
+++ b/packages/core/src/Lightbox/useZoomStage.ts
@@ -4,25 +4,30 @@
/**
* @file useZoomStage.ts
- * @input The zoom core (useZoomCore.ts), the stage element ref, whether the
- * gestures and the touch presentation are on, and tap and drag callbacks
+ * @input The zoom core (useZoomCore.ts), the stage element ref and the
+ * element the recognizers attach to: the stage, or a gallery's track. Also
+ * whether the gestures and the touch presentation are on, and tap and drag
+ * callbacks
* @output Exports `useZoomStage`: Lightbox's gestures, those of a zooming
* UIScrollView for every pointer, on top of the core, whose API it returns
* @position Lightbox's gesture module, internal, with one import site
* (Lightbox.tsx). It builds on the gesture recognizers and the core's
* animator; the geometry is in zoomStage.ts.
*
- * SYNC: When modified, update useZoomCore.ts, zoomStage.ts, Lightbox.tsx and
- * __tests__/LightboxZoom.interaction.browser.spec.ts.
+ * SYNC: When modified, update useZoomCore.ts, zoomStage.ts, Lightbox.tsx,
+ * __tests__/LightboxZoom.interaction.browser.spec.ts and
+ * __tests__/LightboxPaging.interaction.browser.spec.ts.
*/
import {useRef, useState, type RefObject} from 'react';
+import type {GestureRecognizer} from '../gestures/GestureRecognizer';
import {LongPressGestureRecognizer} from '../gestures/LongPressGestureRecognizer';
import {PanGestureRecognizer} from '../gestures/PanGestureRecognizer';
import {PinchGestureRecognizer} from '../gestures/PinchGestureRecognizer';
import {TapGestureRecognizer} from '../gestures/TapGestureRecognizer';
import type {Point} from '../gestures/types';
import {useGestureRecognizer} from '../gestures/useGestureRecognizer';
+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
import {UIKIT_PAN} from '../motion/uikit/gestures';
import {coast as coastCurves} from '../motion/coast';
import {decayRestDistance} from '../motion/decay';
@@ -49,12 +54,18 @@ import {
export {ZOOM_DRAGGING_ATTRIBUTE, type ZoomStage};
export interface UseZoomStageOptions {
- /** The stage: the photo's clipping parent, which centres it. */
+ /** The stage: the box the photo is fitted and centred in, clipping it. */
stageRef: RefObject<HTMLElement | null>;
+ /** Where the recognizers attach: the stage by default, a pager's track. */
+ surfaceRef?: RefObject<HTMLElement | null>;
/** The gestures are on (zoom is on), for every pointer. */
isEnabled: boolean;
- /** A finger's single tap landed outside the photo. */
- onTapOutside?: () => void;
+ /**
+ * A finger's single tap landed off the photo, at this client point. It
+ * landed on the stage, or on the surface around it, such as a gallery
+ * page's empty strip.
+ */
+ onTapOutside?: (location: Point) => void;
/** A pan began (a release over the backdrop must not close). */
onDragStart?: () => void;
/**
@@ -63,6 +74,16 @@ export interface UseZoomStageOptions {
* stops at the edges and at the release.
*/
isTouchPresentation?: boolean;
+ /**
+ * Whether a pinch, or a two-finger pan, may begin, from the recognizer's
+ * tracked touches. False leaves the fingers to the page's zoom.
+ */
+ shouldBeginPinch?: (recognizer: GestureRecognizer) => boolean;
+ /**
+ * An outer pager takes a one-finger drag that heads past the zoomed photo's
+ * edge. Without one, the pan begins there and gives past the edge.
+ */
+ hasOuterPager?: boolean;
}
interface PinchSession {
@@ -81,7 +102,6 @@ interface PanSession {
readonly hasGive: boolean;
}
-/** Every pointer: a mouse, a pen and a finger. */
const EVERY_POINTER = ['touch', 'pen', 'mouse'] as const;
/** Fingers only: a pen does not pinch. A ctrl-wheel pinches too. */
const PINCH_POINTERS = ['touch'] as const;
@@ -90,11 +110,6 @@ const DOUBLE_TAP_POINTERS = ['touch'] as const;
/** A mouse's or a pen's click beside the photo is the browser's `click`. */
const TAP_POINTERS = ['touch'] as const;
-/** Sets the zoom pan's begin threshold for the press that just landed. */
-function setBeginThreshold(pan: PanGestureRecognizer, px: number): void {
- pan.hysteresis = px;
-}
-
/**
* Lightbox's zoom gestures. They take every pointer: a mouse, a pen and a
* finger alike. The pinch is the fingers', and a ctrl-wheel pinches too. The
@@ -106,12 +121,17 @@ function setBeginThreshold(pan: PanGestureRecognizer, px: number): void {
* release and double tap runs on the compositor as baked keyframes. A press
* on a moving photo takes it from its presentation value.
*
- * The recognizers on the stage, as UIScrollView arranges its own:
+ * The recognizers sit on the stage or a gallery's track, as UIScrollView
+ * arranges its own.
* - pinch, with the pan, so two fingers zoom and move at once. A finger left
* down after the pinch keeps panning.
* - pan: one or two fingers, a mouse's or a pen's drag, or a trackpad's
* scroll. It moves a zoomed photo. In the touch presentation, its release
- * carries a scroll view's velocity.
+ * carries a scroll view's velocity. With two fingers down it begins when
+ * the pinch may. With one, it begins on a zoomed photo. Where an outer
+ * pager takes the drag, it begins only short of the photo's edge on the
+ * side the drag heads to. UIKit's paging scroll view does the same.
+ * Elsewhere it gives past that edge.
* - double tap, a finger's: it fills the viewer, at least 2×, and keeps the
* point in place. When zoomed it goes back to the fitted size. A mouse's or
* a pen's double-click is the browser's `dblclick` (the core's
@@ -121,7 +141,8 @@ function setBeginThreshold(pan: PanGestureRecognizer, px: number): void {
* click ends it at once.
* - a zero-duration press beside them all, UIKit's touch-down idiom. A press
* on a moving photo stops it where it shows, and a lift with no drag lets
- * it settle.
+ * it settle. It claims only a press on a moving photo, so a still one
+ * leaves the press to an outer pager's own catch.
*
* The stage's `touch-action` is the caller's (none while zoom is on), since a
* disabled recognizer would still claim it.
@@ -129,8 +150,8 @@ function setBeginThreshold(pan: PanGestureRecognizer, px: number): void {
* It follows UIKit's measured behavior (motion/uikit/zoomMedia.ts). Inside the
* limits the zoom follows the pinch 1:1. The content point under the centroid
* stays under it, past the limits too. No scale momentum follows the lift.
- * Past a limit, the return is one eased animation anchored at the last
- * centroid. In the touch presentation, a zoomed pan coasts and bounces like a
+ * Past a limit, the return springs from the pinch's velocity, anchored at
+ * the last centroid. In the touch presentation, a zoomed pan coasts and bounces like a
* scroll view. A two-finger tap does nothing.
*/
export function useZoomStage(
@@ -140,7 +161,6 @@ export function useZoomStage(
const {
animator,
geometryRef,
- targetRef,
measure,
toStage,
current,
@@ -148,6 +168,8 @@ export function useZoomStage(
setTarget,
setZoomed,
settleTo,
+ isMoving,
+ isAtEdgeOf,
} = core;
const pinchRef = useRef<PinchSession | null>(null);
const panRef = useRef<PanSession | null>(null);
@@ -181,6 +203,38 @@ export function useZoomStage(
);
};
+ // The pan begins with two fingers down when a pinch may, or on a zoomed
+ // photo. Where an outer pager takes the drag, it begins only short of the
+ // photo's edge on the side the drag heads to. UIScrollView's pan in a
+ // paging scroll view does the same, and the pager takes the rest.
+ const panShouldBeginRef = useRef<(pan: PanGestureRecognizer) => boolean>(
+ () => true,
+ );
+ const isMovingRef = useRef(isMoving);
+ const pinchShouldBeginRef = useRef<
+ (recognizer: GestureRecognizer) => boolean
+ >(() => true);
+ const {shouldBeginPinch, hasOuterPager = false} = options;
+ useIsomorphicLayoutEffect(() => {
+ pinchShouldBeginRef.current = shouldBeginPinch ?? (() => true);
+ panShouldBeginRef.current = pan => {
+ if (pan.numberOfTouches > 1) {
+ return pinchShouldBeginRef.current(pan);
+ }
+ const geometry = measure();
+ if (geometry == null || !isZoomed(geometry, current())) {
+ return false;
+ }
+ const {x, y} = pan.totalTranslation();
+ return !(
+ hasOuterPager &&
+ Math.abs(x) >= Math.abs(y) &&
+ isAtEdgeOf(geometry, x < 0 ? 'left' : 'right')
+ );
+ };
+ isMovingRef.current = isMoving;
+ });
+
// Whether a finger began each gesture, read from its first touch as it
// begins. Under reduced motion a finger's release cross-fades. A mouse's, a
// trackpad's or a pen's release completes at once where the primary pointer
@@ -190,6 +244,7 @@ export function useZoomStage(
const pinch = new PinchGestureRecognizer({
name: 'Lightbox.zoomPinch',
allowedPointerTypes: PINCH_POINTERS,
+ shouldBegin: recognizer => pinchShouldBeginRef.current(recognizer),
});
// A zoomed photo is a scroll view: its coast reads the pan's scroll-view
// release (`scrollVelocity()`), so it coasts as far as UIKit's.
@@ -198,15 +253,15 @@ export function useZoomStage(
maximumNumberOfTouches: 2,
allowedPointerTypes: EVERY_POINTER,
allowedScrollTypes: ['continuous'],
- // A mouse, a pen or a trackpad pans only a zoomed photo. On a fitted
- // photo it starts no pan, so its press and release stay a click.
- shouldBegin: recognizer => {
- if (recognizer.trackedTouches[0]?.pointerType === 'touch') {
- return true;
- }
- const geometry = geometryRef.current;
- return geometry != null && isZoomed(geometry, current());
- },
+ shouldBegin: recognizer => panShouldBeginRef.current(recognizer),
+ // A mouse's or a pen's drag on a zoomed photo pans from its first move.
+ // A finger keeps UIKit's begin threshold, which tells a tap from a pan.
+ hysteresis: touch =>
+ touch.pointerType !== 'touch' &&
+ geometryRef.current != null &&
+ isZoomed(geometryRef.current, current())
+ ? 0
+ : UIKIT_PAN.hysteresis.value,
});
// A finger's double tap. A mouse's or a pen's double-click is the
// browser's `dblclick`, which keeps the system's double-click speed.
@@ -226,6 +281,9 @@ export function useZoomStage(
cancelsTouchesInView: false,
delaysTouchesEnded: false,
allowedPointerTypes: EVERY_POINTER,
+ // Only a moving photo is caught, so a still one leaves the touch to
+ // everyone else (an outer pager's own catch).
+ shouldBegin: () => isMovingRef.current(),
});
pinch.recognizeSimultaneouslyWith(pan);
tap.requireToFail(doubleTap);
@@ -236,9 +294,10 @@ export function useZoomStage(
});
const recognizerOptions = {isEnabled: options.isEnabled, manageStyle: false};
+ const surfaceRef = options.surfaceRef ?? options.stageRef;
useGestureRecognizer(
- options.stageRef,
+ surfaceRef,
() => recognizers.pinch,
pinch => {
if (pinch.state === 'began') {
@@ -330,7 +389,7 @@ export function useZoomStage(
);
useGestureRecognizer(
- options.stageRef,
+ surfaceRef,
() => recognizers.pan,
pan => {
const stage = options.stageRef.current;
@@ -382,7 +441,6 @@ export function useZoomStage(
});
return;
}
- // Ended or cancelled.
stage?.removeAttribute(ZOOM_DRAGGING_ATTRIBUTE);
const session = panRef.current;
panRef.current = null;
@@ -403,35 +461,19 @@ export function useZoomStage(
);
useGestureRecognizer(
- options.stageRef,
+ surfaceRef,
() => recognizers.touchDown,
touchDown => {
if (touchDown.state === 'began') {
- const isFinger = touchDown.trackedTouches[0]?.pointerType === 'touch';
- fingerRef.current.catch = isFinger;
- // A mouse's or a pen's drag on a zoomed photo pans from its first
- // move. A finger keeps UIKit's begin threshold, which tells a tap from
- // a pan.
- const geometry = geometryRef.current;
- setBeginThreshold(
- recognizers.pan,
- !isFinger && geometry != null && isZoomed(geometry, current())
- ? 0
- : UIKIT_PAN.hysteresis.value,
- );
+ fingerRef.current.catch =
+ touchDown.trackedTouches[0]?.pointerType === 'touch';
+ // It only begins on a moving photo: stopped where it shows, at the
+ // presentation value from the curve.
draggedSinceCatchRef.current = false;
+ caughtRef.current = true;
const shown = current();
- const target = targetRef.current;
- const moving =
- Math.abs(shown.x - target.x) > 0.01 ||
- Math.abs(shown.y - target.y) > 0.01 ||
- Math.abs(shown.scale - target.scale) > 0.0001;
- caughtRef.current = moving;
- if (moving) {
- // Stopped where it shows: the presentation value, from the curve.
- animator.stop();
- setTarget(shown);
- }
+ animator.stop();
+ setTarget(shown);
return;
}
if (touchDown.state === 'changed') {
@@ -463,7 +505,7 @@ export function useZoomStage(
);
useGestureRecognizer(
- options.stageRef,
+ surfaceRef,
() => recognizers.doubleTap,
doubleTap => {
if (doubleTap.state !== 'ended') {
@@ -483,7 +525,7 @@ export function useZoomStage(
);
useGestureRecognizer(
- options.stageRef,
+ surfaceRef,
() => recognizers.tap,
tap => {
if (tap.state !== 'ended') {
@@ -497,13 +539,13 @@ export function useZoomStage(
const {x, y, scale} = current();
const left = geometry.fit.x + x;
const top = geometry.fit.y + y;
- const inside =
+ const onPhoto =
point.x >= left &&
point.x <= left + geometry.fit.width * scale &&
point.y >= top &&
point.y <= top + geometry.fit.height * scale;
- if (!inside) {
- options.onTapOutside?.();
+ if (!onPhoto) {
+ options.onTapOutside?.(tap.location());
}
},
recognizerOptions,
diff --git a/packages/core/src/hooks/usePager.test.ts b/packages/core/src/hooks/usePager.test.ts
index 05e153294c..05b75efa3f 100644
--- a/packages/core/src/hooks/usePager.test.ts
+++ b/packages/core/src/hooks/usePager.test.ts
@@ -17,7 +17,11 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {GestureHost} from '../gestures/GestureHost';
import {PanGestureRecognizer} from '../gestures/PanGestureRecognizer';
import {ManualClock} from '../gestures/__tests__/harness';
-import {createMotionEngine, type Animator} from '../motion/animator';
+import {
+ createMotionEngine,
+ END_HOLD_MS,
+ type Animator,
+} from '../motion/animator';
import {solveAnimatedPageScroll, solvePaging} from '../motion/paging';
import type * as motionResolution from '../motion/resolveMotion';
import {resolveMotion} from '../motion/resolveMotion';
@@ -507,6 +511,44 @@ describe('createPager', () => {
expect(f.calls).toEqual(['index:2:drag', 'settle:2:1']);
});
+ // The settle plays at the tempo of the theme the track is in: from rest it
+ // keeps its shape and takes tempo times as long. At tempo 1 it is UIKit's
+ // measured settle.
+ it.each([1, 3])(
+ "a release's settle plays at the theme's tempo %s",
+ async tempo => {
+ const style = document.createElement('style');
+ style.textContent = `[data-tempo] { --_astryx-motion-tempo: ${tempo}; }`;
+ document.head.append(style);
+ try {
+ const f = setup({defaultIndex: 1});
+ f.track.setAttribute('data-tempo', '');
+ // A silent hold of 100 ms before the lift: the settle starts at rest.
+ await drag(f, {from: 300, dx: -250, step: 4, dt: 8, hold: 100});
+ expect(f.pager.index).toBe(2);
+ const position = -f.x();
+ const measured = solvePaging({
+ from: position,
+ velocity: 0,
+ to: 2 * WIDTH,
+ });
+ await advance(16, f.clock);
+ await advance(100, f.clock);
+ // 116 ms in, it shows where the measured settle is at 116 ÷ tempo ms.
+ expect(-f.x()).toBeCloseTo(measured.at(0.116 / tempo), 0);
+ // The animation holds its end for END_HOLD_MS after the curve.
+ const played = recorded.filter(animation => !animation.cancelled);
+ expect(
+ Number(played.at(-1)?.options.duration) - END_HOLD_MS,
+ ).toBeCloseTo(measured.duration * 1000 * tempo, 6);
+ await settle(f);
+ expect(f.x()).toBe(-2 * WIDTH);
+ } finally {
+ style.remove();
+ }
+ },
+ );
+
// A sample at the finger's last place is not motion (spec:AST-100's one
// filter). A finger that keeps reporting while it stands still keeps its
// speed until the stillness interval runs out.
@@ -2786,6 +2828,7 @@ describe('usePager (React)', () => {
defaultIndex?: number;
viewportKey?: string;
isPanEnabled?: boolean;
+ isControlledChangeAnimated?: boolean;
onIndexChange?: (index: number) => void;
onSettle?: (index: number, previous: number) => void;
onPager?: (pager: Pager) => void;
@@ -2799,6 +2842,7 @@ describe('usePager (React)', () => {
index: props.index,
defaultIndex: props.defaultIndex,
isPanEnabled: props.isPanEnabled,
+ isControlledChangeAnimated: props.isControlledChangeAnimated,
onIndexChange: props.onIndexChange,
onSettle: props.onSettle,
});
@@ -3038,6 +3082,84 @@ describe('usePager (React)', () => {
view.unmount();
});
+ // Off, a new controlled index moves the pager at once. A drag the owner
+ // refuses still springs back over frames, as any released drag does.
+ it('with isControlledChangeAnimated off, a drag the owner refuses springs back animated', async () => {
+ const runFrames = handFrames();
+ vi.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(
+ WIDTH,
+ );
+ const box: {pager: Pager | null} = {pager: null};
+ const onIndexChange = vi.fn();
+ const view = render(
+ createElement(Paged, {
+ index: 0,
+ isControlledChangeAnimated: false,
+ onIndexChange,
+ onPager: p => {
+ box.pager = p;
+ },
+ }),
+ );
+ const pager = box.pager;
+ if (pager == null) {
+ throw new Error('no pager');
+ }
+ const goTo = vi.spyOn(pager, 'goTo');
+ const track = view.getByTestId('viewport').firstElementChild as Element;
+ // Past half a page: the release pages, and the owner keeps page 0.
+ heldDrag(track);
+ now += 8;
+ vi.advanceTimersByTime(8);
+ touch('touchend', track, 60, 100, now);
+ // The release reports its page once its settle runs, a few frames on.
+ for (let i = 0; i < 6; i++) {
+ await act(async () => {
+ for (const animation of recorded) {
+ if (animation.startTime == null && !animation.cancelled) {
+ animation.commit(now);
+ }
+ }
+ runFrames(1);
+ await Promise.resolve();
+ await Promise.resolve();
+ now += 16;
+ await vi.advanceTimersByTimeAsync(16);
+ });
+ }
+ expect(onIndexChange).toHaveBeenCalledWith(1, 'drag');
+ expect(goTo).toHaveBeenCalledWith(0, {
+ reason: 'controlled',
+ animated: true,
+ });
+ view.unmount();
+ });
+
+ it('with isControlledChangeAnimated off, a new controlled index moves the pager at once', () => {
+ const box: {pager: Pager | null} = {pager: null};
+ const props = {
+ isControlledChangeAnimated: false,
+ onPager: (p: Pager) => {
+ box.pager = p;
+ },
+ };
+ const view = render(createElement(Paged, {...props, index: 2}));
+ const pager = box.pager;
+ if (pager == null) {
+ throw new Error('no pager');
+ }
+ const goTo = vi.spyOn(pager, 'goTo');
+ act(() => {
+ view.rerender(createElement(Paged, {...props, index: 4}));
+ });
+ expect(goTo).toHaveBeenCalledWith(4, {
+ reason: 'controlled',
+ animated: false,
+ });
+ expect(pager.index).toBe(4);
+ view.unmount();
+ });
+
it('with a controlled index, a page the owner takes stays', () => {
const frames: FrameRequestCallback[] = [];
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
diff --git a/packages/core/src/hooks/usePager.ts b/packages/core/src/hooks/usePager.ts
index dd40fbf846..c1474f3a8c 100644
--- a/packages/core/src/hooks/usePager.ts
+++ b/packages/core/src/hooks/usePager.ts
@@ -44,6 +44,7 @@ import {
solvePaging,
} from '../motion/paging';
import {resolveMotion} from '../motion/resolveMotion';
+import {themeTempo} from '../motion/themeTempo';
import {resolveSnapPoint} from '../motion/resolveSnapPoint';
import {rubberBandClamp, rubberBandUnclamp} from '../motion/rubberBand';
import {paging, registerPagingTable} from '../motion/uikit/paging';
@@ -454,8 +455,8 @@ function isScrollContact(recognizer: PanGestureRecognizer): boolean {
* move, no layout read and no React render. Past the first or last page,
* the track follows UIKit's rubber band, with d = the page width.
* - At the lift, `pageForRelease` picks the page with UIKit's measured rule.
- * The track then settles on UIKit's paging integrator (`solvePaging`),
- * baked into keyframes.
+ * The track then settles on UIKit's paging integrator (`solvePaging`), at
+ * the tempo of the theme the track is in, baked into keyframes.
* - A finger that lands on a settling pager catches it `paging.catchStopMs`
* after the touch, as in UIKit. A finger stops a `goTo` move at once. A
* drag catches it at once, from the value on screen. While the pan is off,
@@ -936,8 +937,15 @@ export function createPager(
touchRelease: boolean,
): void {
const to = offsetOf(target);
- // UIKit's integrator, as a playable curve (touch motion stays internal).
- const curve = solvePaging({from: position, velocity, to});
+ // UIKit's integrator, as a playable curve (touch motion stays internal),
+ // at the theme's tempo. No motion role names it, so it reads the tempo
+ // itself.
+ const curve = solvePaging({
+ from: position,
+ velocity,
+ to,
+ tempo: themeTempo(trackElement),
+ });
if (curve.steps === 0) {
animator?.set({x: positionToX(to)});
rest();
@@ -1433,6 +1441,12 @@ export interface UsePagerOptions extends PagerOptions {
index?: number;
/** Live toggle for the pan; turning it off mid-drag cancels the drag. */
isPanEnabled?: boolean;
+ /**
+ * Whether a change of the controlled `index` animates. Off, the pager moves
+ * there at once. A page the pager reported and the owner refused returns
+ * animated either way, as a released drag springs back. Default true.
+ */
+ isControlledChangeAnimated?: boolean;
}
/**
@@ -1453,6 +1467,7 @@ export function usePager({
trackRef,
index,
isPanEnabled = true,
+ isControlledChangeAnimated = true,
...options
}: UsePagerOptions): Pager {
const latestRef = useRef(options);
@@ -1513,12 +1528,20 @@ export function usePager({
// reported and the owner did not take, such as a refused swipe. A
// controlled input returns to its value the same way. The move is the
// owner's own, so it is not reported back. It moves only while the two
- // differ.
- useEffect(() => {
+ // differ, and before the browser paints the new `index`. The same `index`
+ // after a report is a refused page, which springs back whatever
+ // `isControlledChangeAnimated` says.
+ const syncedIndexRef = useRef(index);
+ useIsomorphicLayoutEffect(() => {
if (index != null && index !== pager.index) {
- pager.goTo(index, {reason: 'controlled'});
+ pager.goTo(index, {
+ reason: 'controlled',
+ animated:
+ isControlledChangeAnimated || index === syncedIndexRef.current,
+ });
}
- }, [pager, index, reported]);
+ syncedIndexRef.current = index;
+ }, [pager, index, reported, isControlledChangeAnimated]);
return pager;
}
diff --git a/packages/core/src/motion/MEASUREMENTS.md b/packages/core/src/motion/MEASUREMENTS.md
index 1040ffd008..f4e28921a7 100644
--- a/packages/core/src/motion/MEASUREMENTS.md
+++ b/packages/core/src/motion/MEASUREMENTS.md
@@ -349,12 +349,13 @@ Values Lightbox's zoom stage reads (`uikit/zoomMedia.ts`). Done (UIKit lab and
Photos, iOS 26.2 simulator, Oct 23 2026; tagged `measured:`): the overshoot
past the limits, the absence of scale momentum and of a two-finger-tap action,
the content point under the centroid staying put, Photos' aspect-fill double
-tap and its maximum zoom on 3000 × 2000 and 2000 × 3000 photos. M-ZM2 confirms
-that maximum on two other sizes. A zoomed pan flicked into an edge coasts and
-bounces like any scroll view (`scroll.*`). UIKit settles a zoom on an eased
-curve whose length grows with the zoom ratio (100 ms plus 300 ms per unit of
-its log, at most 400 ms). Lightbox's zoom settles on `springs.settle` instead,
-since its main interaction is a gesture (`spec:AST-094` FR45).
+tap and its maximum zoom on 3000 × 2000 and 2000 × 3000 photos, and the 40 pt
+gap between Photos' pages. M-ZM2 confirms that maximum on two other sizes. A
+zoomed pan flicked into an edge coasts and bounces like any scroll view
+(`scroll.*`). UIKit settles a zoom on an eased curve whose length grows with
+the zoom ratio (100 ms plus 300 ms per unit of its log, at most 400 ms).
+Lightbox's zoom settles on `springs.settle` instead, since its main
+interaction is a gesture (`spec:AST-094` FR45).
| ID | What | App and gesture | Extract | Method |
| ----- | ------------ | -------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------ |
diff --git a/packages/core/src/motion/paging.test.ts b/packages/core/src/motion/paging.test.ts
index 6a8a1cba90..7f58d9647c 100644
--- a/packages/core/src/motion/paging.test.ts
+++ b/packages/core/src/motion/paging.test.ts
@@ -353,6 +353,38 @@ describe("solvePaging: UIKit's paging settle, frame by frame", () => {
expect(curve.at(0.1)).toBe(804);
});
+ it.each([0.75, 1.5, 3])(
+ 'at tempo %s, a settle from rest keeps its shape and takes tempo times as long',
+ tempo => {
+ const measured = solvePaging({from: 633.33, velocity: 0, to: 804});
+ const paced = solvePaging({from: 633.33, velocity: 0, to: 804, tempo});
+ expect(paced.steps).toBe(measured.steps);
+ expect(paced.duration).toBeCloseTo(measured.duration * tempo, 9);
+ for (let t = 0; t <= measured.duration; t += 0.01) {
+ expect(paced.at(t * tempo)).toBeCloseTo(measured.at(t), 6);
+ }
+ expect(paced.at(paced.duration)).toBe(804);
+ },
+ );
+
+ it("at any tempo, a release starts at UIKit's step velocity", () => {
+ for (const tempo of [0.75, 1.5, 3]) {
+ const curve = solvePaging({from: 500, velocity: 1000, to: 804, tempo});
+ expect(curve.velocity(0)).toBeCloseTo(960, 6);
+ expect(curve.at(curve.duration)).toBe(804);
+ }
+ });
+
+ it('at tempo 1, the settle is the measured one', () => {
+ const measured = solvePaging({from: 450, velocity: 600, to: 804});
+ const atOne = solvePaging({from: 450, velocity: 600, to: 804, tempo: 1});
+ expect(atOne.steps).toBe(measured.steps);
+ expect(atOne.duration).toBe(measured.duration);
+ for (let t = 0; t <= measured.duration; t += 0.004) {
+ expect(atOne.at(t)).toBe(measured.at(t));
+ }
+ });
+
it('runs the documented integrator', () => {
const {springPull, friction} = paging.integrator;
const curve = solvePaging({from: 0, velocity: 0, to: 100});
diff --git a/packages/core/src/motion/paging.ts b/packages/core/src/motion/paging.ts
index 2cd978c7c4..3664a72b02 100644
--- a/packages/core/src/motion/paging.ts
+++ b/packages/core/src/motion/paging.ts
@@ -50,24 +50,34 @@ export interface PagingCurve extends MotionCurve {
* The release velocity enters in px per millisecond per step, as UIKit hands it
* to the integrator. At 960 steps a second, the content starts at 96 % of the
* finger's speed, as in UIKit.
+ *
+ * At a theme's `tempo`, each step lasts tempo times as long and carries tempo
+ * times the release's distance. So a settle from rest keeps its shape and
+ * takes tempo times as long, and a release still starts at 96 % of the
+ * finger's speed. At tempo 1 the settle is the measured one.
*/
export function solvePaging({
from,
velocity,
to,
+ tempo = 1,
}: {
from: number;
velocity: number;
to: number;
+ /** The tempo of the theme the motion plays in (themeTempo.ts). */
+ tempo?: number;
}): PagingCurve {
- const {springPull, friction, stepsPerSecond, restDistance, restSpeed} =
- paging.integrator;
+ const {springPull, friction, restDistance, restSpeed} = paging.integrator;
+ const pace = Number.isFinite(tempo) && tempo > 0 ? tempo : 1;
+ const stepsPerSecond = paging.integrator.stepsPerSecond / pace;
+ const startVelocity = (velocity / 1000) * pace;
const xs: number[] = [from];
- const vs: number[] = [velocity / 1000];
+ const vs: number[] = [startVelocity];
let x = from;
- let v = velocity / 1000;
- // ~10 s of steps: far beyond any settle (≈ 0.35 s from rest).
- const maxSteps = stepsPerSecond * 10;
+ let v = startVelocity;
+ // ~10 s of steps at tempo 1: far beyond any settle (≈ 0.35 s from rest).
+ const maxSteps = paging.integrator.stepsPerSecond * 10;
let steps = 0;
while (steps < maxSteps) {
if (Math.abs(to - x) < restDistance && Math.abs(v) < restSpeed) {
diff --git a/packages/core/src/motion/themeTempo.ts b/packages/core/src/motion/themeTempo.ts
index 936ac78297..37d05eb2e3 100644
--- a/packages/core/src/motion/themeTempo.ts
+++ b/packages/core/src/motion/themeTempo.ts
@@ -4,7 +4,8 @@
* @file themeTempo.ts
* @input An element on the page
* @output `themeTempo(element)`: the tempo of the theme the element is in
- * @position Motion foundation; resolveMotion.ts scales a motion role by it
+ * @position Motion foundation; resolveMotion.ts scales a motion role by it,
+ * and the pager scales its settle by it, which no role names
*
* A theme that sets `tempo` writes it, clamped, to the private custom
* property `--_astryx-motion-tempo` beside its duration tokens. An
diff --git a/packages/core/src/motion/uikit/zoomMedia.ts b/packages/core/src/motion/uikit/zoomMedia.ts
index fdefa6bf08..1adc275fbf 100644
--- a/packages/core/src/motion/uikit/zoomMedia.ts
+++ b/packages/core/src/motion/uikit/zoomMedia.ts
@@ -4,7 +4,8 @@
* @file zoomMedia.ts
* @input Nothing; data only
* @output Exports `zoomMedia`: UIScrollView zooming in a photo viewer. That
- * is the give past the zoom limits, and Photos' double tap and maximum zoom
+ * is the give past the zoom limits, and Photos' double tap, maximum zoom
+ * and gap between pages
* @position A domain of the UIKit constants table (motion/uikit). Lightbox's
* zoom stage reads it
*
@@ -69,5 +70,13 @@ export const zoomMedia = {
* 2000 × 3000 photos, Oct 23 2026
*/
maxPixelZoomMultiple: 6,
+ /**
+ * Space between photos while they page, pt: the pager's stride is the
+ * screen's width plus this (442 on the 402 pt screen). It shows only
+ * while a page moves.
+ * @source measured: Photos, iOS 26.2 simulator, iPhone 17 Pro, the
+ * pager's contentOffset per page, Oct 23 2026
+ */
+ pageGap: 40,
},
} as const;