An open source design system that's fully customizable and agent ready
TypeScript
feat(Lightbox): drag a photo down to close, like Photos (#8215)
Christopher Chedeau4043d65e5084
diff --git a/.changeset/lightbox-drag-to-dismiss.md b/.changeset/lightbox-drag-to-dismiss.mdnew file mode 100644index 0000000000..835d0a4ec5--- /dev/null+++ b/.changeset/lightbox-drag-to-dismiss.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[feat] On a phone or tablet, drag a Lightbox photo down to close the viewer, as in the iOS Photos viewer. The photo follows your finger and shrinks a little as you pull, while the backdrop fades and the controls fade faster. The backdrop fades without its blur, which comes back once it is at rest. Let go moving down, however short the pull, and the photo carries on down as the viewer closes. Flick it back up, or bring it back to where you started, and it springs back into place. A zoomed photo still pans when you drag it; the drag to close starts from the fitted size. Videos are unchanged.++The viewer's controls now sit in their own layers, which fade together during the drag.++@vjeuxdiff --git a/apps/storybook/stories/Lightbox.stories.tsx b/apps/storybook/stories/Lightbox.stories.tsxindex 0080f9daab..ef85628989 100644--- a/apps/storybook/stories/Lightbox.stories.tsx+++ b/apps/storybook/stories/Lightbox.stories.tsx@@ -87,6 +87,30 @@ export const Gallery: Story = {},};+/**+ * The parent decides whether the viewer closes: here it asks first. When it+ * keeps the viewer open, a photo dragged down comes back.+ */+export const ConfirmClose: Story = {+ render: () => {+ const [isOpen, setIsOpen] = useState(false);+ return (+ <>+ <button onClick={() => setIsOpen(true)}>Open, confirm to close</button>+ <Lightbox+ isOpen={isOpen}+ onOpenChange={next => {+ if (next || window.confirm('Close the photo?')) {+ setIsOpen(next);+ }+ }}+ media={{src: SAMPLE_IMAGE, alt: 'Forest path'}}+ />+ </>+ );+ },+};+export const WithZoom: Story = {render: () => {const [isOpen, setIsOpen] = useState(false);diff --git a/docs/specs/components/Lightbox/Lightbox.spec.md b/docs/specs/components/Lightbox/Lightbox.spec.mdindex cdf87d6a07..456e01def7 100644--- a/docs/specs/components/Lightbox/Lightbox.spec.md+++ b/docs/specs/components/Lightbox/Lightbox.spec.md@@ -79,8 +79,11 @@ Consumer migration instructions belong in consumer docs and release notes.The shipped Lightbox does not yet meet every requirement below. Each gap namesthe requirement it misses and the person it affects.-- **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.+- **Touch presentation (FR9, FR10, FR12).** On a touch screen there is no+ pinch to close, tap to hide the controls, or thumbnail transition.+- **Drag to close (FR8).** Implementation gap: the close is reported when the+ photo has left the screen, about 0.3–0.5 s after the lift, until the shared+ exit hold lets the viewer stay up after a reported close.- **Paging motion roles (FR5).** The page settle plays the pager's own UIKitvalues, which the motion role table does not list as roles.- **Video controls (FR7).** A video's native controls are taken as a 48 px@@ -146,10 +149,10 @@ FR21). Consumer props and usage remain documented in `Lightbox.doc.mjs`.| FR2 | Viewer overlay carries the current `lightbox` target. Media, Caption, and Counter carry no Lightbox public target. | Current source and public docs | settled || FR3 | Close, Previous, and Next button surfaces use Button's `button` target through IconButton rather than Lightbox-owned button targets. | Current source and target docs | settled || FR4 | The open viewer is a focus region through Core's shared focus-region module (`component:Dialog/DEC-2`): Tab from its last control moves focus to its first and Shift+Tab from its first moves focus to its last, so focus never leaves the viewer for the browser's own interface. | `component:Dialog/DEC-2` | settled; implementation gap |-| FR5 | Under a coarse primary pointer, after hydration, Lightbox presents FR6–FR10 with no opt-in. Lightbox's main interaction is a gesture, so every move in them (the zoom settle, a double tap's zoom, the page settle, the dismiss and the pinch close) is a spring on a named motion role read through the motion role table, never a literal, and a release starts at the gesture's velocity; the controls fade is companion motion on the pace of the main spring (`spec:AST-094` FR45). Under reduced motion they follow AR6. | `spec:AST-094` FR4, FR13 | settled; implementation gap |+| FR5 | Under a coarse primary pointer, after hydration, Lightbox presents FR6–FR10 with no opt-in. Lightbox's main interaction is a gesture, so every move in them (the zoom settle, a double tap's zoom, the page settle, a cancelled drag's return and the pinch close) is a spring on a named motion role read through the motion role table, never a literal, and a release starts at the gesture's velocity; the controls fade is companion motion on the pace of the main spring (`spec:AST-094` FR45). A drag down that closes the viewer is a gesture-driven exit, so it plays the measured springs the Motion section lists (`spec:AST-094` FR4). Under reduced motion they follow AR6. | `spec:AST-094` FR4, FR13 | settled; implementation gap || FR6 | With `hasZoom`, on an image, a pinch zooms about the fingers and pans while it zooms; past the minimum or maximum the photo resists and eases back without overshoot. A double tap zooms to the larger of filling the viewer and 2×, about the tapped point; a second double tap returns to the fitted size. A zoomed photo pans with momentum and rubber-band edges. A pinch on the controls or the caption still zooms the page. | `spec:AST-094` FR3, FR10 | settled; implementation gap || FR7 | In a gallery, a horizontal drag moves the row of items, which sit apart by the measured gap. The release lands on at most one neighbouring item by `spec:AST-094` FR3's paging rule (DEC-25). Paging applies over a video item's frame as over a photo; a drag that starts on the video's own controls, such as its scrubber or volume, stays the video's. A zoomed photo pans to its edge before a new drag pages. A pinch never pages. Previous, Next, and the arrow keys keep paging. A controlled `index` the caller refuses springs back. `onIndexChange` reports a swipe. | `spec:AST-094` FR3, FR14, FR36–FR39, DEC-25 | settled; implementation gap |-| FR8 | On a fitted image, a downward drag moves the photo with the finger, shrinks it, and fades the backdrop. The release decides once: a projected travel past the commit point closes the viewer and reports `onOpenChange(false)` at the lift; a release moving back springs back. Video is unchanged. | `spec:AST-094` FR36–FR40 | settled; implementation gap |+| FR8 | On a fitted image, a downward drag moves the photo with the finger, shrinks it, and fades the backdrop. The release decides once: a projected travel past the commit point closes the viewer and reports `onOpenChange(false)` at the lift; a release moving back springs back. Video is unchanged. | `spec:AST-094` FR4, FR36–FR40, FR45 | settled; implementation gap || FR9 | With `hasZoom`, a pinch in from the fitted size is a release decision: below the measured fraction of the fitted size the release closes the viewer; opening the fingers again by the measured amount before the lift is moving back and cancels. A pinch that starts zoomed in never closes the viewer. | `spec:AST-094` FR36, FR37 | settled; implementation gap || FR10 | With `hasZoom`, under a coarse pointer only, a tap on the photo fades the controls and caption and darkens the backdrop. While they are hidden, the next tap on the photo, a tap beside the photo, or a cancelled drag brings them back, and that tap beside the photo does not close the viewer (ORD3). AR5 governs keyboard and assistive-technology access while they are hidden. | `architecture:public-component-api` INV16 | settled; implementation gap || FR11 | A mouse, a pen, and a trackpad also use FR7's drag paging, FR8's drag to close, a ctrl-wheel or trackpad pinch over the photo for FR6's zoom and FR9's close, and a trackpad's scroll to pan a zoomed photo; a mouse wheel's notches leave it in place (`spec:AST-094` FR43); over the photo these replace the browser's page zoom and scroll. A double-click zooms 2× about the clicked point. A click on the photo keeps the controls, and the viewer opens and closes at once. | `spec:AST-094` FR43; `spec:AST-017` FR59 | settled; implementation gap |@@ -161,6 +164,18 @@ FR21). Consumer props and usage remain documented in `Lightbox.doc.mjs`.| FR17 | For any whole-number `index`, controlled or default, the viewer opens on the nearest valid item: below 0 the first, past the last the last. | Current source and tests | settled || FR18 | In a gallery, a video on a neighbouring page stays mounted and paused while another item shows. Paging back to it shows it where it stopped, as the platform photo viewer does: paused, or playing on from there with `hasAutoPlay`. | Current source and tests | settled |+### Motion++A drag down that closes the viewer is a gesture-driven exit, so it plays+Photos' measured dismissal springs (FR5, `spec:AST-094` FR4). Every other+spring a gesture drives, a cancelled drag's return included, plays+`springs.settle`.++| Spring | Value | Platform source |+| ----------------------------------------- | --------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |+| `zoomMedia.dismiss.dismissPositionSpring` | Mass 1, stiffness 918.09, damping 60.60 | Photos, iOS 26.2 simulator, iPhone 17 Pro: a committed drag to dismiss, the zoom view's position animation (`CASpringAnimation`) |+| `zoomMedia.dismiss.dismissSizeSpring` | Mass 1, stiffness 947.14, damping 61.55 | Photos, iOS 26.2 simulator, iPhone 17 Pro: the same dismissal's bounds and opacity animations (`CASpringAnimation`) |+### Allowed variation- **AV1 — Media mode.** Media may be an image or video; zoom, pan, drag down to@@ -341,6 +356,7 @@ a decision that they must remain unthemeable.| FR4, AR3 | Browser keyboard test: Tab and Shift+Tab at both ends, Escape, arrows in LTR and RTL, `+`, `-`, `0`, close focus | Single image, gallery, zoomed image, removed opener | Focus leaving the viewer, a key without its action, or focus not returning to a connected opener fails. | `audit:Lightbox/accessibility` || AR3 | `Lightbox.test.tsx` "Lightbox unmounting while open" suite | Viewer rendered only while open and removed by the page, with the opener still on the page; a page control that removes it keeps its focus; StrictMode | Focus left on the page body after an open viewer unmounts fails. | `audit:Lightbox/accessibility` || FR5–FR10 | Interaction tests on synthetic touch streams with explicit timestamps; Reduce Motion; a busy main thread | Below and past each commit point; a release moving back; a drag on a video's frame and on its scrubber; a tap beside the photo with the controls hidden | A literal timing, a second decision during a settle, a gesture that pages while pinching, a drag on a video's frame that does not page, a drag on its controls that pages, or a tap beside the photo that closes while the controls are hidden fails. | `audit:Lightbox/touch` |+| Motion | `zoomStage.test.ts` case listing the dismissal's springs in this record | The dismissal's position spring, and its size and opacity spring | A spring the dismissal plays that the Motion section does not list with its value fails. | `audit:Lightbox/touch` || FR11 | Fine-pointer browser tests | Double-click, click on the photo, drag, ctrl-wheel, trackpad scroll, mouse wheel notch | A double-click that does not zoom 2× about the point, a click that hides the controls, a fine-pointer close that animates, or a mouse wheel's notch that pans a zoomed photo fails. | `audit:Lightbox/touch` || FR6, AR1 | Touch test double-tapping a photo shaped like the screen and a landscape photo | 9:16 photo on a phone viewport, 3:2 photo | A double tap that zooms less than 2×, or not about the tapped point, fails. | `audit:Lightbox/touch` || FR16 | Touch tests closing by Close, Escape, platform close, and a tap beside the photo with the controls shown; Reduce Motion | With and without `experimental`; controls shown and hidden | A touch close without the exit, a literal timing, input reaching the viewer during the exit, or a tap beside the photo that closes while the controls are hidden fails. | `audit:Lightbox/touch` |diff --git a/packages/core/src/Lightbox/Lightbox.doc.mjs b/packages/core/src/Lightbox/Lightbox.doc.mjsindex d65e12d9b3..b8324276bf 100644--- a/packages/core/src/Lightbox/Lightbox.doc.mjs+++ b/packages/core/src/Lightbox/Lightbox.doc.mjs@@ -68,7 +68,8 @@ export const docs = {{name: 'onOpenChange',type: '(isOpen: boolean) => void',- description: 'Callback when the lightbox open state changes.',+ description:+ 'Callback when the lightbox open state changes: the Close button, Escape, a tap beside the media, or, on a phone or tablet, dragging a photo down from its fitted size.',required: true,},{@@ -188,7 +189,8 @@ export const docsZh = {{name: 'onOpenChange',type: '(isOpen: boolean) => void',- description: '灯箱打开状态变化时的回调。',+ description:+ '灯箱打开状态变化时的回调:关闭按钮、Esc 键、点按媒体旁空白处,或在手机或平板上从适合大小向下拖动照片。',required: true,},{@@ -292,7 +294,8 @@ export const docsDense = {},propDescriptions: {isOpen: 'Whether the lightbox is open.',- onOpenChange: 'Callback when open state changes.',+ onOpenChange:+ 'Callback when open state changes (including a photo dragged down).',media: 'Single media object or array for gallery mode.',index: 'Current index in gallery mode.',onIndexChange:diff --git a/packages/core/src/Lightbox/Lightbox.test.tsx b/packages/core/src/Lightbox/Lightbox.test.tsxindex a73146f8b9..937f28911e 100644--- a/packages/core/src/Lightbox/Lightbox.test.tsx+++ b/packages/core/src/Lightbox/Lightbox.test.tsx@@ -5,6 +5,7 @@ import {act, render, screen, fireEvent, waitFor} from '@testing-library/react';import {Profiler, StrictMode, useState} from 'react';import {Lightbox} from './Lightbox';import {getFocusableElements} from '../hooks/useFocusTrap';+import {getGestureHost} from '../gestures/GestureHost';import {__resetLiveRegionsForTest} from '../hooks/useAnnounce';import {InternationalizationProvider} from '../i18n';@@ -61,9 +62,7 @@ function stubStageLayout(): () => void {// The zoom stage: a single item's photo box, or a gallery page's.const isStage = (element: Element) =>element.hasAttribute('data-lightbox-page-media') ||- (element.getAttribute('role') === 'button' &&- element.getAttribute('aria-label') === 'Zoom' &&- element.querySelector('[data-lightbox-page]') == null);+ element.querySelector(':scope > img') != null;define(HTMLElement.prototype, 'offsetWidth', element =>isPhoto(element) ? 400 : 0,);@@ -1735,6 +1734,64 @@ describe('Lightbox double-click under the touch layer', () => {});});+describe('Lightbox recognizers attach for every pointer (spec:AST-094 FR43)', () => {+ /** Names of the Lightbox recognizers attached while `body` runs. */+ function lightboxRecognizersAttached(body: () => void): string[] {+ const attach = vi.spyOn(getGestureHost(document), 'attach');+ try {+ body();+ return attach.mock.calls+ .map(([, recognizer]) => recognizer.name)+ .filter(name => /lightbox/i.test(name));+ } finally {+ attach.mockRestore();+ }+ }++ it('attaches no drag to dismiss where the primary pointer is fine', () => {+ expect(+ lightboxRecognizersAttached(() => {+ render(+ <Lightbox+ isOpen={true}+ onOpenChange={() => {}}+ media={{src: '/photo.jpg', alt: 'Photo'}}+ />,+ );+ }),+ ).toEqual([]);+ });++ it('attaches the drag to dismiss under the touch layer', () => {+ const originalMatchMedia = window.matchMedia;+ window.matchMedia = (query: string) => ({+ matches: query === '(pointer: coarse)',+ media: query,+ onchange: null,+ addEventListener: () => {},+ removeEventListener: () => {},+ addListener: () => {},+ removeListener: () => {},+ dispatchEvent: () => false,+ });+ try {+ expect(+ lightboxRecognizersAttached(() => {+ render(+ <Lightbox+ isOpen={true}+ onOpenChange={() => {}}+ media={{src: '/photo.jpg', alt: 'Photo'}}+ />,+ );+ }),+ ).toContain('Lightbox.dismissPan');+ } finally {+ window.matchMedia = originalMatchMedia;+ }+ });+});+describe('Lightbox touch zoom (synthetic touches)', () => {let restoreLayout: () => void = () => {};const originalMatchMedia = window.matchMedia;@@ -1989,6 +2046,106 @@ describe('Lightbox touch zoom (synthetic touches)', () => {expect(x()).toBeLessThan(before - 20);touch('touchend', stage, [], [finger], 900 + 9 * 16);});++ // Times on the arena's clock: velocities read the gap since the last sample.+ let clock = 0;++ /** A one-finger drag down by `dy` in 10 px steps. */+ function dragDown(+ stage: Element,+ dy: number,+ ): {x: number; y: number; id: number} {+ clock = performance.now();+ let finger = {id: 1, x: 200, y: 300};+ touch('touchstart', stage, [finger], [finger], clock);+ for (let i = 1; i <= dy / 10; i++) {+ finger = {...finger, y: 300 + 10 * i};+ touch('touchmove', stage, [finger], [finger], clock + i * 16);+ }+ clock += (dy / 10) * 16;+ return finger;+ }++ it('carries a photo dragged down, shrinking it, and the release dismisses', async () => {+ const onOpenChange = vi.fn();+ render(+ <Lightbox+ isOpen={true}+ onOpenChange={onOpenChange}+ media={{src: '/photo.jpg', alt: 'Photo'}}+ />,+ );+ const img = screen.getByAltText('Photo');+ const stage = img.parentElement!;+ const finger = dragDown(stage, 100);+ // The travel past the pan's 10 px threshold is 90 px: the photo's centre+ // moved 90 px down, and it shrank to 1 − 4.91e-6 × 90².+ const scale = 1 - 4.91e-6 * 90 * 90;+ expect(parseFloat(photoTransform(img).scale)).toBeCloseTo(scale, 4);+ const [tx, ty] = photoTransform(img).translate.split(' ').map(parseFloat);+ expect(tx).toBeCloseTo(((1 - scale) * 400) / 2, 2);+ expect(ty).toBeCloseTo(90 + ((1 - scale) * 200) / 2, 2);+ expect(onOpenChange).not.toHaveBeenCalled();+ touch('touchend', stage, [], [finger], clock + 16);+ await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false));+ });++ it('springs back when the finger lifts moving up', async () => {+ const onOpenChange = vi.fn();+ render(+ <Lightbox+ isOpen={true}+ onOpenChange={onOpenChange}+ media={{src: '/photo.jpg', alt: 'Photo'}}+ hasZoom+ />,+ );+ const img = screen.getByAltText('Photo');+ const stage = img.parentElement!;+ let finger = dragDown(stage, 100);+ for (let i = 1; i <= 6; i++) {+ finger = {...finger, y: finger.y - 10};+ touch('touchmove', stage, [finger], [finger], clock + i * 16);+ }+ touch('touchend', stage, [], [finger], clock + 7 * 16);+ // The return's end state is in place at once (it springs there on the+ // compositor); at rest the photo keeps no inline transform.+ expect(photoTransform(img)).toEqual({translate: '', scale: ''});+ await new Promise(resolve => setTimeout(resolve, 50));+ expect(onOpenChange).not.toHaveBeenCalled();+ });++ it('ignores the first tap on the strip after a drag to close springs back, as before', async () => {+ const onOpenChange = vi.fn();+ render(+ <Lightbox+ isOpen={true}+ onOpenChange={onOpenChange}+ media={{src: '/photo.jpg', alt: 'Photo', caption: 'A caption'}}+ hasZoom+ />,+ );+ const img = screen.getByAltText('Photo');+ const stage = img.parentElement!;+ let finger = dragDown(stage, 100);+ for (let i = 1; i <= 6; i++) {+ finger = {...finger, y: finger.y - 10};+ touch('touchmove', stage, [finger], [finger], clock + i * 16);+ }+ touch('touchend', stage, [], [finger], clock + 7 * 16);+ await new Promise(resolve => setTimeout(resolve, 50));+ expect(onOpenChange).not.toHaveBeenCalled();+ const group = screen.getByText('A caption').parentElement!;+ const tapStrip = () => {+ fingerDown(group, 200, 590);+ fireEvent.click(group, {clientX: 200, clientY: 590, detail: 1});+ };+ // The first tap on the strip below the stage only clears the drag's flag.+ tapStrip();+ expect(onOpenChange).not.toHaveBeenCalled();+ tapStrip();+ expect(onOpenChange).toHaveBeenCalledWith(false);+ });});describe('Lightbox zoom reset timing', () => {@@ -2044,6 +2201,40 @@ describe('Lightbox zoom reset timing', () => {});});+describe('Lightbox restore after a dismissal', () => {+ const media = [+ {src: '/a.jpg', alt: 'Image A'},+ {src: '/b.jpg', alt: 'Image B'},+ ];+ // The backdrop's blur is off while the backdrop moves, as during a+ // cancelled drag's return, and the restore brings it back.+ const BLUR_OFF = '--_lightbox-backdrop-filter';++ it('brings the backdrop back to rest as the viewer opens', () => {+ const {rerender} = render(+ <Lightbox isOpen={false} onOpenChange={() => {}} media={media} hasZoom />,+ );+ const dialog = document.querySelector('dialog');+ expect(dialog).not.toBeNull();+ dialog?.style.setProperty(BLUR_OFF, 'none');+ rerender(+ <Lightbox isOpen={true} onOpenChange={() => {}} media={media} hasZoom />,+ );+ expect(dialog?.style.getPropertyValue(BLUR_OFF)).toBe('');+ });++ it('leaves a moving backdrop alone on a page change while the viewer is open', () => {+ render(+ <Lightbox isOpen={true} onOpenChange={() => {}} media={media} hasZoom />,+ );+ const dialog = screen.getByRole('dialog');+ dialog.style.setProperty(BLUR_OFF, 'none');+ fireEvent.click(screen.getByRole('button', {name: /next/i}));+ expect(dialog).toHaveTextContent('2 / 2');+ expect(dialog.style.getPropertyValue(BLUR_OFF)).toBe('none');+ });+});+describe('Lightbox with an unusable controlled index', () => {it('renders without looping when index is NaN', () => {expect(() =>diff --git a/packages/core/src/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsxindex 0cefcc0600..a219aa915f 100644--- a/packages/core/src/Lightbox/Lightbox.tsx+++ b/packages/core/src/Lightbox/Lightbox.tsx@@ -6,7 +6,8 @@* @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, and a gallery pages with usePager+ * zoom uses useZoomCore and useZoomStage, a gallery pages with usePager,+ * and the drag to dismiss fades the backdrop and controls on the animator* @output Exports Lightbox component, LightboxProps, LightboxMedia* @position Core implementation; consumed by index.ts*@@ -27,6 +28,7 @@ import {useCallback,useEffect,useMemo,+ useReducer,useRef,useState,type MouseEvent as ReactMouseEvent,@@ -71,6 +73,8 @@ import {usePager} from '../hooks/usePager';import {TapGestureRecognizer} from '../gestures/TapGestureRecognizer';import type {GestureTouch} from '../gestures/types';import {useGestureRecognizer} from '../gestures/useGestureRecognizer';+import {resolveMotion} from '../motion/resolveMotion';+import {springs} from '../motion/uikit/springs';import {zoomMedia} from '../motion/uikit/zoomMedia';import {useZoomStage} from './useZoomStage';import {useTouchPresentation} from '../utils/touchPresentation';@@ -81,6 +85,8 @@ import {import english from '../i18n/generated-english/Lightbox/Lightbox.generated';import {isRenderable} from '../utils/isRenderable';import {prepareFocusReturnOnRemoval} from '../utils/focusReturn';+import {animatorFor, type Animator} from '../motion/animator';+import {dismissBackdropAlpha, dismissChromeAlpha} from './zoomStage';registerEnglishFallback(english);/**@@ -179,9 +185,13 @@ const styles = stylex.create({backgroundColor: 'transparent',overflow: 'hidden',outline: 'none',+ // The backdrop is the theme's overlay colour over a 2 px blur. A drag to+ // dismiss and its release remove the blur through+ // `--_lightbox-backdrop-filter`. A full-viewport blur repainted every+ // frame of the fade drops frames.'::backdrop': {backgroundColor: colorVars['--color-overlay'],- backdropFilter: 'blur(2px)',+ backdropFilter: 'var(--_lightbox-backdrop-filter, blur(2px))',},},container: {@@ -199,7 +209,9 @@ const styles = stylex.create({alignItems: 'center',maxWidth: '100%',maxHeight: '100%',- overflow: 'hidden',+ // ZOOM_DISMISSING_ATTRIBUTE on the stage inside: a photo dragged to+ // dismiss draws outside the box that hugs it.+ overflow: {default: 'hidden', ':has([data-zoom-dismissing])': 'visible'},},// A zoomable photo's stage fills the viewer for every pointer, as a photo// viewer's zooming scroll view does. A zoomed photo uses the whole screen,@@ -227,7 +239,16 @@ const styles = stylex.create({display: 'flex',alignItems: 'center',justifyContent: 'center',- overflow: 'hidden',+ // ZOOM_DISMISSING_ATTRIBUTE, on this stage or a gallery page's: a photo+ // dragged to dismiss draws outside it, above its caption and below the+ // controls. The drag fades the caption, which makes it a stacking context+ // painted after the stage.+ overflow: {+ default: 'hidden',+ ':is([data-zoom-dismissing])': 'visible',+ ':has([data-zoom-dismissing])': 'visible',+ },+ zIndex: {default: null, ':is([data-zoom-dismissing])': 1},cursor: 'default',userSelect: 'none',minHeight: 0,@@ -256,6 +277,11 @@ const styles = stylex.create({flexShrink: 1,flexBasis: 0,},+ // In the touch presentation, a photo without zoom leaves pinch-zoom to the+ // page but takes one-finger drags. A drag down dismisses it.+ imageWrapperDismissTarget: {+ touchAction: 'pinch-zoom',+ },// 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: {@@ -301,7 +327,9 @@ const styles = stylex.create({display: 'flex',alignItems: 'center',justifyContent: 'center',- overflow: 'hidden',+ // As the single item's stage, while a photo is dragged to dismiss.+ overflow: {default: 'hidden', ':is([data-zoom-dismissing])': 'visible'},+ zIndex: {default: null, ':is([data-zoom-dismissing])': 1},minHeight: 0,minWidth: 0,maxWidth: '100%',@@ -371,6 +399,8 @@ const styles = stylex.create({navNext: {insetInlineEnd: spacingVars['--spacing-3'],},+ // The counter takes its own clicks in the click-through layer, so a click+ // on it leaves the viewer open.counter: {position: 'absolute',top: spacingVars['--spacing-3'],@@ -379,9 +409,24 @@ const styles = stylex.create({fontSize: typeScaleVars['--text-body-size'],lineHeight: typeScaleVars['--text-body-leading'],zIndex: 1,+ pointerEvents: 'auto',},controlButton: {color: colorVars['--color-on-dark'],+ pointerEvents: 'auto',+ },+ // The controls sit in layers over the viewer that pass clicks through. A+ // drag to dismiss fades the layers, which carry no transition of their own,+ // since a Button's opacity transition would trail the finger.+ // They sit above the stage, even a photo dragged to dismiss. While a fade+ // writes their opacity, each is a stacking context. A gallery's positioned+ // pages, later in tree order, would otherwise cover them and take the taps+ // meant for the controls.+ chromeLayer: {+ position: 'absolute',+ inset: 0,+ zIndex: 2,+ pointerEvents: 'none',},// With zoom a photo can lie under the controls. Lightbox's own translucent// backing keeps them readable over any photo: 3:1 for the buttons, 4.5:1@@ -599,6 +644,31 @@ export function Lightbox({}}, [index, hasAutoPlay]);+ // The backdrop, the controls and the pages a dismissal faded, to restore+ // exactly those. A page faded as a neighbour may be the current one when+ // the viewer opens again.+ const fadedRef = useRef<Animator[]>([]);+ // Set when a dismissal has asked the caller to close; the next render+ // (one more is asked for) reads the caller's answer.+ const dismissalAnsweredRef = useRef(false);+ const [, renderAfterDismissal] = useReducer((n: number) => n + 1, 0);++ // Drag to dismiss, as in Photos. The backdrop fades with the drag's travel,+ // and the controls and the neighbouring photos fade faster. A dismissal+ // fades them out on its spring and closes once the photo has left.+ // The backdrop's blur comes off while the backdrop moves and comes back+ // once it rests, through the dialog's '::backdrop' style. Each move counts:+ // a release's end restores it only if nothing has moved the backdrop since.+ const backdropMovesRef = useRef(0);+ const setBackdropMoving = useCallback((moving: boolean) => {+ const dialog = dialogRef.current;+ if (moving) {+ dialog?.style.setProperty('--_lightbox-backdrop-filter', 'none');+ } else {+ dialog?.style.removeProperty('--_lightbox-backdrop-filter');+ }+ }, []);+// 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;@@ -772,6 +842,34 @@ export function Lightbox({);const isZoomTarget = hasZoom && !isVideo;++ const dismissFades = useCallback((): {+ backdrop: Animator | null;+ chrome: Animator[];+ } => {+ const dialog = dialogRef.current;+ const container = containerRef.current;+ if (dialog == null || container == null) {+ return {backdrop: null, chrome: []};+ }+ const chrome: HTMLElement[] = [];+ for (const element of container.querySelectorAll<HTMLElement>(+ '[data-lightbox-chrome], [data-lightbox-page]:not([data-current]), [data-lightbox-caption]',+ )) {+ if (+ element.parentElement?.closest(+ '[data-lightbox-page]:not([data-current])',+ ) == null+ ) {+ chrome.push(element);+ }+ }+ return {+ backdrop: animatorFor(dialog, {pseudoElement: '::backdrop'}),+ chrome: chrome.map(element => animatorFor(element)),+ };+ }, []);+const onDragStart = () => {didDragRef.current = true;};@@ -855,6 +953,7 @@ export function Lightbox({stageRef: isGallery ? pageMediaRef : imageWrapperRef,surfaceRef: isGallery ? trackRef : imageWrapperRef,isEnabled: isOpen && isZoomTarget,+ itemKey: viewedItem,// 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}) => {@@ -879,6 +978,90 @@ export function Lightbox({// A pinch whose first finger lands on a gallery's caption is the page's.shouldBeginPinch: recognizer =>!startsOnCaption(recognizer.trackedTouches[0]),+ dismiss: {+ // Part of the touch presentation, which applies under a coarse primary+ // pointer. Where it is fine, a drag leaves the photo in place. A video+ // keeps its own controls' drags.+ isEnabled: isOpen && !isVideo && isTouch,+ onDrag: travel => {+ const {backdrop, chrome} = dismissFades();+ fadedRef.current = backdrop == null ? chrome : [backdrop, ...chrome];+ backdropMovesRef.current += 1;+ setBackdropMoving(true);+ backdrop?.set({opacity: dismissBackdropAlpha(travel)});+ const opacity = dismissChromeAlpha(travel);+ for (const animator of chrome) {+ animator.set({opacity});+ }+ },+ onRelease: (dismisses, touch) => {+ const {backdrop, chrome} = dismissFades();+ fadedRef.current = backdrop == null ? chrome : [backdrop, ...chrome];+ // They keep pace with the photo: the dismissal's measured spring, or+ // on a cancel the shared settle spring, read where the stage is.+ const spring = dismisses+ ? zoomMedia.dismiss.dismissSizeSpring+ : resolveMotion(+ (isGallery ? pageMediaRef : imageWrapperRef).current,+ springs.settle,+ );+ const opacity = dismisses ? 0 : 1;+ const move = (backdropMovesRef.current += 1);+ setBackdropMoving(true);+ const backdropMotion = backdrop?.animate(+ {opacity},+ {spring},+ {touchRelease: touch},+ );+ for (const animator of chrome) {+ animator.animate({opacity}, {spring}, {touchRelease: touch});+ }+ // Back at rest: the blur returns, unless the backdrop moved again.+ void backdropMotion?.finished.then(() => {+ if (!dismisses && backdropMovesRef.current === move) {+ setBackdropMoving(false);+ }+ });+ },+ onDismissed: () => {+ handleClose();+ // A caller may keep the viewer open, since the close is its call. The+ // render after its answer brings the photo, the backdrop and the+ // controls back, so no open dialog stays invisible.+ dismissalAnsweredRef.current = true;+ renderAfterDismissal();+ },+ },+ });++ // Restore the photo, the backdrop and the controls only when the viewer+ // opens or a dismissal is answered. Each write promotes a layer, and+ // releasing it later repaints during a gesture.+ const restoreAfterDismissal = useCallback(() => {+ stage.reset();+ backdropMovesRef.current += 1;+ setBackdropMoving(false);+ const faded = fadedRef.current;+ fadedRef.current = [];+ for (const animator of faded) {+ animator.set({opacity: 1});+ }+ }, [stage, setBackdropMoving]);+ // Effect: syncs the photo's and the controls' animations with an opening+ // viewer, so it opens at rest with the backdrop's blur back.+ useIsomorphicLayoutEffect(() => {+ if (isOpen) {+ restoreAfterDismissal();+ }+ }, [isOpen, restoreAfterDismissal]);+ useIsomorphicLayoutEffect(() => {+ if (!dismissalAnsweredRef.current) {+ return;+ }+ dismissalAnsweredRef.current = false;+ if (isOpen) {+ restoreAfterDismissal();+ }});// 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.@@ -1210,27 +1393,32 @@ export function Lightbox({didDragRef.current = false;}}}>- {control(styles.closeButton, {- icon: 'close',- label: t('@astryx.lightbox.close'),- onClick: handleClose,- })}-- {/* Gallery nav: prev — stays mounted and is disabled at the start of- the range so pressing/arrowing to the boundary doesn't unmount the- focused control and drop focus to <body>. */}- {isGallery &&- control([styles.navButton, styles.navPrev], {- icon: 'chevronLeft',- label: t('@astryx.lightbox.previous'),- isDisabled: !canPrev,- onClick: goToPrev,- isMirrored: true,+ <div+ data-lightbox-chrome=""+ {...stylex.props(styles.chromeLayer)}>+ {control(styles.closeButton, {+ icon: 'close',+ label: t('@astryx.lightbox.close'),+ onClick: handleClose,})}+ {/* Gallery nav: prev — stays mounted and is disabled at the start of+ the range so pressing/arrowing to the boundary doesn't unmount the+ focused control and drop focus to <body>. */}+ {isGallery &&+ control([styles.navButton, styles.navPrev], {+ icon: 'chevronLeft',+ label: t('@astryx.lightbox.previous'),+ isDisabled: !canPrev,+ onClick: goToPrev,+ isMirrored: true,+ })}+ </div>+{/* Media + caption group (centered together) */}<divref={mediaGroupRef}+ data-lightbox-media=""{...stylex.props(styles.mediaGroup,isZoomTarget && !isGallery && styles.mediaGroupZoom,@@ -1251,6 +1439,11 @@ export function Lightbox({isGallery && styles.imageWrapperGallery,isZoomTarget && !isGallery && styles.imageWrapperZoomTarget,isZoomTarget && !isGallery && styles.imageWrapperFill,+ isTouch &&+ !isZoomTarget &&+ !isVideo &&+ !isGallery &&+ styles.imageWrapperDismissTarget,isZoomTarget && focusOutlineStyles.focusVisible,isZoomTarget && styles.imageWrapperFocusInset,isZoomTarget && !isZoomed && styles.imageWrapperZoomable,@@ -1282,6 +1475,10 @@ export function Lightbox({{...stylex.props(styles.track,isZoomTarget && styles.trackZoomTarget,+ isTouch &&+ !isZoomTarget &&+ !isVideo &&+ styles.imageWrapperDismissTarget,)}>{pageIndexes.map(i => (<div@@ -1322,33 +1519,40 @@ export function Lightbox({</div>{!isGallery && isRenderable(currentItem.caption) && (- <div ref={captionRef} {...stylex.props(styles.caption)}>+ <div+ ref={captionRef}+ data-lightbox-caption=""+ {...stylex.props(styles.caption)}>{currentItem.caption}</div>)}</div>- {/* Gallery nav: next — see "prev" above; stays mounted and disabled at+ <div+ data-lightbox-chrome=""+ {...stylex.props(styles.chromeLayer)}>+ {/* Gallery nav: next — see "prev" above; stays mounted and disabled atthe end of the range instead of unmounting. */}- {isGallery &&- control([styles.navButton, styles.navNext], {- icon: 'chevronRight',- label: t('@astryx.lightbox.next'),- isDisabled: !canNext,- onClick: goToNext,- isMirrored: true,- })}+ {isGallery &&+ control([styles.navButton, styles.navNext], {+ icon: 'chevronRight',+ label: t('@astryx.lightbox.next'),+ isDisabled: !canNext,+ onClick: goToNext,+ isMirrored: true,+ })}- {/* Gallery counter */}- {isGallery && mediaArray.length > 1 && (- <div- {...stylex.props(- styles.counter,- hasZoom && styles.counterBacking,- )}>- {index + 1} / {mediaArray.length}- </div>- )}+ {/* Gallery counter */}+ {isGallery && mediaArray.length > 1 && (+ <div+ {...stylex.props(+ styles.counter,+ hasZoom && styles.counterBacking,+ )}>+ {index + 1} / {mediaArray.length}+ </div>+ )}+ </div></div></LayerContentBoundary></ModalAnnounceProvider>diff --git a/packages/core/src/Lightbox/LightboxFinePointer.a11y.browser.spec.ts b/packages/core/src/Lightbox/LightboxFinePointer.a11y.browser.spec.tsindex e0d0e36f1c..52523740b8 100644--- a/packages/core/src/Lightbox/LightboxFinePointer.a11y.browser.spec.ts+++ b/packages/core/src/Lightbox/LightboxFinePointer.a11y.browser.spec.ts@@ -5,9 +5,10 @@* @input The built Lightbox "with zoom" story, a desktop browser (a fine* primary pointer) and real mouse input; in Chromium, pen input* @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+ * pointer is fine too. It covers the zoom's touches as on a phone, and a+ * photo without zoom that leaves touches to the page. It also covers the+ * double-click's 2× zoom, the keyboard's spring, pen and mouse drags, and a+ * gallery's Next, arrow keys, dark-area click and counter* @position Cross-browser proof for Lightbox under a fine primary pointer*/@@ -251,6 +252,33 @@ test('the zoom target takes its touches as on a phone where the primary pointer]);});+test('a photo without zoom leaves its touches to the page where the primary pointer is fine, as on main', async ({+ page,+}) => {+ // The drag to close belongs to the touch presentation, which a coarse+ // primary pointer brings. A touchscreen laptop's finger scrolls and zooms+ // the page around a photo without zoom, as on main.+ 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--default&viewMode=story`,+ );+ await page.getByRole('button', {name: 'Open lightbox'}).click();+ const dialog = page.getByRole('dialog');+ await expect(dialog).toBeVisible();+ const photo = dialog.getByRole('img').first();+ expect(await touchActionsAbove(photo)).toEqual([+ 'auto',+ 'auto',+ 'auto',+ 'auto',+ ]);+});+test('a gallery leaves its sideways touches to the page where the primary pointer is fine', async ({page,}) => {@@ -356,6 +384,23 @@ test('in a gallery, a mouse click beside a large photo, level with it, leaves thawait expect(dialog).toBeVisible();});+test('a mouse click on the gallery counter leaves the viewer open, as on main', async ({+ page,+}) => {+ // A window taller than the photo's fitted height leaves the dark area+ // above it, where the counter sits and a click beside the photo closes.+ await page.setViewportSize({width: 1280, height: 1000});+ const {dialog, current} = await openGallery(page);+ const counter = dialog.getByText('1 / 4', {exact: true});+ await expect(counter).toBeVisible();+ const box = await boxOf(counter);+ expect(box.width).toBeGreaterThan(0);+ expect(box.y + box.height).toBeLessThan((await boxOf(current)).y);+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);+ 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,}) => {diff --git a/packages/core/src/Lightbox/__tests__/LightboxDismiss.interaction.browser.spec.ts b/packages/core/src/Lightbox/__tests__/LightboxDismiss.interaction.browser.spec.tsnew file mode 100644index 0000000000..dc00fbd4f9--- /dev/null+++ b/packages/core/src/Lightbox/__tests__/LightboxDismiss.interaction.browser.spec.ts@@ -0,0 +1,906 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file LightboxDismiss.interaction.browser.spec.ts+ * @input The built Lightbox stories on the phone project, real touch input+ * and the interaction harness+ * @output Proofs for Lightbox's drag to dismiss against Photos' measured one.+ * They cover the follow, shrink and fades, a release that dismisses or+ * springs back, a zoomed photo's pan and a gallery. They also cover a+ * blocked main thread, Reduce Motion, reopening, a caller that keeps the+ * viewer open, Close above a gallery's pages and a storyboard.+ * @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 {+ blockMainThread,+ type BusyRun,+ type BusyWindow,+ compareCurve,+ CONTROL_RGB,+ curveOf,+ drag,+ frames,+ holdAnimations,+ openStory,+ pooledBusyProof,+ releaseAnimations,+ sampleCurve,+ startBusyControl,+ startScreencast,+ timeline,+ touchDriver,+ type TouchDriver,+ type TouchScript,+ touchStoryboard,+ trackBrightness,+ trackMarker,+ waitForAnimation,+ waitForRest,+ withStorybook,+ writeEvidence,+} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++// Photos' measured drag to dismiss (motion/uikit/zoomMedia.ts), restated so+// a change to the table has to be made here too.+const SCALE_K = 4.91e-6;+const BACKDROP_K = 1.35e-5;+const CHROME_PER_PT = 0.00533;+const CHROME_START = 17.8;+/** The pan's begin threshold: travel before it is the finger's alone. */+const THRESHOLD = 10;+/** The dismissal's opacity spring: critically damped, mass 1. */+const FADE_STIFFNESS = 947.14;++/**+ * How near its end, in brightness levels, a fade on the dismissal's opacity+ * spring still steps a whole level between two frames `frameMs` apart. It+ * takes the widest range, all 255 levels. Nearer the end, a fade that still+ * runs can show the same 8-bit level twice.+ */+function wholeStepsUntil(frameMs: number): number {+ const omega = Math.sqrt(FADE_STIFFNESS);+ const left = (s: number) => 255 * (1 + omega * s) * Math.exp(-omega * s);+ // Past its fastest point, at 1 / omega, the step between frames only falls.+ let t = 1 / omega;+ while (left(t) - left(t + frameMs / 1000) >= 1) {+ t += 0.0001;+ }+ return left(t);+}++/** A critically damped spring from `from` to `to`, at rest at the start. */+function criticallyDamped(stiffness: number, from: number, to: number) {+ const omega = Math.sqrt(stiffness);+ return (ms: number) => {+ const t = ms / 1000;+ return to + (from - to) * (1 + omega * t) * Math.exp(-omega * t);+ };+}++function photoSvg(width: number, height: number): string {+ let squares = '';+ for (let y = 0; y < height; y += 50) {+ for (let x = 0; x < width; 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="${width}" height="${height}" viewBox="0 0 ${width} ${height}" shape-rendering="crispEdges"><rect width="${width}" height="${height}" fill="#fff"/><g fill="#000">${squares}</g><circle cx="${width / 2}" cy="${height / 2}" r="${height / 8}" fill="#d22"/></svg>`;+}++interface Viewer {+ driver: TouchDriver;+ dialog: Locator;+ photo: Locator;+ close: Locator;+ /** The photo's box centre on the page. */+ centre: {x: number; y: number};+ /** The photo's zoom-stage transform. */+ photoState: () => Promise<{x: number; y: number; scale: number}>;+ backdropAlpha: () => Promise<number>;+ /** The opacity of the controls' layer (the Close button's). */+ closeAlpha: () => Promise<number>;+}++const STORIES = {+ plain: {id: 'core-lightbox--default', trigger: 'Open lightbox'},+ zoom: {id: 'core-lightbox--with-zoom', trigger: 'Open with zoom'},+ gallery: {+ id: 'core-lightbox--gallery-with-zoom',+ trigger: 'Open gallery with zoom',+ },+ // Its parent asks before closing; Playwright dismisses the confirm, so the+ // parent keeps the viewer open.+ confirm: {+ id: 'core-lightbox--confirm-close',+ trigger: 'Open, confirm to close',+ },+} as const;++async function openViewer(+ page: Page,+ story: keyof typeof STORIES = 'plain',+): Promise<Viewer> {+ await page.route('https://picsum.photos/**', async route =>+ route.fulfill({contentType: 'image/svg+xml', body: photoSvg(3000, 2000)}),+ );+ await openStory(page, storybook(), STORIES[story].id);+ const driver = await touchDriver(page);+ const trigger = page.getByRole('button', {name: STORIES[story].trigger});+ const box = await trigger.boundingBox();+ if (box == null) {+ throw new Error('no trigger');+ }+ await driver.tap({x: box.x + box.width / 2, y: box.y + box.height / 2});+ const dialog = page.getByRole('dialog');+ await expect(dialog).toBeVisible();+ const photo =+ story === 'gallery'+ ? dialog.locator('[data-current] img')+ : dialog.locator('img').first();+ await expect+ .poll(async () =>+ photo.evaluate(el => (el as HTMLImageElement).naturalWidth),+ )+ .toBe(3000);+ await frames(page, 2);+ const rect = await photo.boundingBox();+ if (rect == null) {+ throw new Error('no photo');+ }+ const close = dialog.getByRole('button', {name: 'Close'});+ return {+ driver,+ dialog,+ photo,+ close,+ centre: {x: rect.x + rect.width / 2, y: rect.y + rect.height / 2},+ photoState: async () =>+ photo.evaluate(el => {+ const style = getComputedStyle(el);+ const [x = '0', y = '0'] =+ style.translate === 'none' ? [] : style.translate.split(' ');+ return {+ x: parseFloat(x),+ y: parseFloat(y),+ scale: style.scale === 'none' ? 1 : parseFloat(style.scale),+ };+ }),+ backdropAlpha: async () =>+ dialog.evaluate(el =>+ parseFloat(getComputedStyle(el, '::backdrop').opacity),+ ),+ closeAlpha: async () =>+ dialog+ .locator('[data-lightbox-chrome]')+ .first()+ .evaluate(el => parseFloat(getComputedStyle(el).opacity)),+ };+}++/** A slow drag down by `dy`, held still before the lift. */+function pullDown(from: {x: number; y: number}, dy: number): TouchScript {+ return drag(+ from,+ {x: from.x, y: from.y + dy},+ {durationMs: 500, restMs: 150},+ );+}++test('a drag down carries the photo and shrinks it by the travel, as the backdrop and controls fade', async ({+ page,+}, testInfo) => {+ const v = await openViewer(page);+ const rows: {+ travel: number;+ scale: number;+ backdrop: number;+ chrome: number;+ dy: number;+ }[] = [];+ await v.driver.play(pullDown(v.centre, 155), {+ onEvent: async step => {+ if (step.type !== 'touchMove') {+ return;+ }+ await frames(page, 1);+ const travel = step.changed[0].y - v.centre.y - THRESHOLD;+ if (travel <= 0) {+ return;+ }+ const s = await v.photoState();+ rows.push({+ travel,+ scale: s.scale,+ dy: s.y,+ backdrop: await v.backdropAlpha(),+ chrome: await v.closeAlpha(),+ });+ },+ });+ await writeEvidence(+ 'curves/lightbox-drag-to-dismiss',+ {[`${testInfo.project.name}.json`]: JSON.stringify(rows, null, 1)},+ testInfo,+ );+ expect(rows.length).toBeGreaterThan(10);+ const photoHeight = await v.photo.evaluate(+ el => (el as HTMLElement).offsetHeight,+ );+ for (const row of rows) {+ // The travel the photo shows: its centre's offset (it shrinks about it).+ const t = row.dy - ((1 - row.scale) * photoHeight) / 2;+ // It follows the finger 1:1 (a read may trail it by one move).+ expect(Math.abs(t - row.travel)).toBeLessThan(6);+ expect(row.scale).toBeCloseTo(1 - SCALE_K * t * t, 3);+ // The fades are read after the photo: a read may see them up to two+ // moves behind it (12 px of travel; WebKit dispatches slower).+ const backdrop = (travel: number) =>+ Math.min(1, 1 - BACKDROP_K * Math.max(0, travel) ** 2);+ const chrome = (travel: number) =>+ Math.min(1, Math.max(0, 1 - CHROME_PER_PT * (travel - CHROME_START)));+ expect(row.backdrop).toBeLessThanOrEqual(backdrop(t - 12) + 0.005);+ expect(row.backdrop).toBeGreaterThanOrEqual(backdrop(t) - 0.005);+ expect(row.chrome).toBeLessThanOrEqual(chrome(t - 12) + 0.005);+ expect(row.chrome).toBeGreaterThanOrEqual(chrome(t) - 0.005);+ }+});++test("a release moving down sends the photo on the dismissal's spring and closes the viewer", async ({+ page,+}, testInfo) => {+ const v = await openViewer(page);+ await v.driver.play(pullDown(v.centre, 110));+ const [exit] = await waitForAnimation(v.photo);+ const held = await holdAnimations(page, v.photo, {+ judges: {target: v.photo, property: 'translate'},+ });+ const duration = Math.max(...held.map(a => a.curveEndMs));+ const samples = curveOf(+ await sampleCurve(v.photo, timeline(duration)),+ 'translateY',+ );+ await releaseAnimations(page);+ const from = samples[0].value;+ const to = samples[samples.length - 1].value;+ // x(t) = to + (A + B·t)·e^(−ωt), A = from − to; B carries the release+ // velocity (B = v₀ + ωA), fitted by least squares.+ const omega = Math.sqrt(918.09);+ let num = 0;+ let den = 0;+ for (const {t, value} of samples) {+ const ts = t / 1000;+ const basis = ts * Math.exp(-omega * ts);+ num += basis * (value - to - (from - to) * Math.exp(-omega * ts));+ den += basis * basis;+ }+ const b = den > 0 ? num / den : 0;+ const spring = (ms: number) => {+ const ts = ms / 1000;+ return to + (from - to + b * ts) * Math.exp(-omega * ts);+ };+ const result = compareCurve(samples, spring, 1);+ await writeEvidence(+ 'curves/lightbox-dismiss-exit',+ {+ [`${testInfo.project.name}.json`]: JSON.stringify(+ {exit, held, samples, result},+ null,+ 1,+ ),+ },+ testInfo,+ );+ expect(result.maxError, JSON.stringify(result.worst)).toBeLessThanOrEqual(1);+ expect(to).toBeGreaterThan(from + 200);+ await expect(v.dialog).toBeHidden();+});++test('a pull flicked back up springs back on springs.settle', async ({+ page,+}, testInfo) => {+ const v = await openViewer(page);+ const down = {x: v.centre.x, y: v.centre.y + 150};+ const script: TouchScript = drag(v.centre, down, {durationMs: 400})+ .slice(0, -1)+ .concat(+ drag(down, {x: down.x, y: down.y - 60}, {durationMs: 60})+ .slice(1)+ .map(f => ({+ ...f,+ t: f.t + 420,+ })),+ );+ await v.driver.play(script);+ const [ret] = await waitForAnimation(v.photo);+ const held = await holdAnimations(page, v.photo, {+ judges: {target: v.photo, property: 'scale'},+ });+ const duration = Math.max(...held.map(a => a.curveEndMs));+ const samples = curveOf(+ await sampleCurve(v.photo, timeline(duration)),+ 'scaleX',+ );+ await releaseAnimations(page);+ // `springs.settle`: response 0.5 s, critically damped, so a stiffness of+ // (2π / 0.5 s)² at mass 1. The size returns from rest.+ const result = compareCurve(+ samples,+ criticallyDamped(((2 * Math.PI) / 0.5) ** 2, samples[0].value, 1),+ 0.002,+ );+ await writeEvidence(+ 'curves/lightbox-dismiss-cancel',+ {+ [`${testInfo.project.name}.json`]: JSON.stringify(+ {ret, held, samples, result},+ null,+ 1,+ ),+ },+ testInfo,+ );+ expect(samples[0].value).toBeLessThan(0.99);+ expect(result.maxError, JSON.stringify(result.worst)).toBeLessThanOrEqual(+ 0.002,+ );+ await waitForRest(v.photo);+ expect(await v.photoState()).toEqual({x: 0, y: 0, scale: 1});+ await expect(v.dialog).toBeVisible();+ await expect.poll(v.backdropAlpha).toBeCloseTo(1, 2);+ await expect.poll(v.closeAlpha).toBeCloseTo(1, 2);+});++test('a pull brought back to where it started springs back', async ({page}) => {+ const v = await openViewer(page);+ const down = {x: v.centre.x, y: v.centre.y + 120};+ const script = drag(v.centre, down, {durationMs: 300})+ .slice(0, -1)+ .concat(+ drag(+ down,+ {x: down.x, y: v.centre.y + THRESHOLD + 4},+ {durationMs: 300, restMs: 150},+ )+ .slice(1)+ .map(f => ({...f, t: f.t + 320})),+ );+ await v.driver.play(script);+ await frames(page, 30);+ await waitForRest(v.photo);+ expect(await v.photoState()).toEqual({x: 0, y: 0, scale: 1});+ await expect(v.dialog).toBeVisible();+});++test("a zoomed photo's vertical drag pans it and never dismisses", async ({+ page,+}) => {+ const v = await openViewer(page, 'zoom');+ await v.driver.play([+ {t: 0, fingers: [{id: 0, ...v.centre}]},+ {t: 50, fingers: []},+ {t: 170, fingers: [{id: 0, ...v.centre}]},+ {t: 220, fingers: []},+ ]);+ await waitForAnimation(v.photo);+ await waitForRest(v.photo);+ const zoomed = await v.photoState();+ expect(zoomed.scale).toBeGreaterThan(1.5);+ await v.driver.play(pullDown(v.centre, 80));+ await waitForRest(v.photo);+ const after = await v.photoState();+ expect(after.scale).toBeCloseTo(zoomed.scale, 3);+ await expect(v.dialog).toBeVisible();+ expect(await v.backdropAlpha()).toBeCloseTo(1, 2);+});++test('a gallery photo dismisses with a drag down', async ({page}) => {+ const v = await openViewer(page, 'gallery');+ await v.driver.play(pullDown(v.centre, 120));+ await expect(v.dialog).toBeHidden();+});++test('the dismissal keeps changing the screen every frame while the main thread is blocked', async ({+ page,+}, testInfo) => {+ // The dismissal runs for about a fifth of a second. A blocked WebKit+ // presents a frame only every 100 to 300 ms, so one run can hold too few+ // frames to judge. The proof plays it several times and judges the runs+ // pooled: each run on its own frames, the frame floor over all of them.+ const runs: BusyRun[] = [];+ const windows: BusyWindow[] = [];+ const closed: boolean[] = [];+ let closest = Number.POSITIVE_INFINITY;+ for (let run = 0; run < DISMISS_RUNS; run += 1) {+ const v = await openViewer(page);+ const box = await v.photo.boundingBox();+ if (box == null) {+ throw new Error('no photo');+ }+ // A flat point of the backdrop above the photo. The dismissal fades the+ // backdrop there every frame it runs, and nothing else paints there.+ const probe = {x: box.x + box.width / 2, y: box.y - 40};+ // A compositor-only control animation in the same window: what the+ // compositor presented while the main thread spun, on this machine.+ await startBusyControl(page);+ const cast = await startScreencast(page);+ await v.driver.play(pullDown(v.centre, 60));+ // Blocked inside the page once the dismissal runs on the compositor.+ const block = await blockMainThread(page, 400, {+ during: v.photo,+ minProgressMs: 16,+ });+ // A few frames after the block, so the screencast holds its end.+ await frames(page, 6);+ const castFrames = await cast.stop();+ const tracked = await trackBrightness(page, castFrames, {+ ...probe,+ size: 8,+ });+ const final = tracked.at(-1)?.box?.x ?? 0;+ const settled =+ tracked.find(+ f =>+ f.t >= block.from && f.box != null && Math.abs(f.box.x - final) <= 1,+ )?.t ?? block.to;+ const window = {+ from: block.from + 20,+ to: Math.min(block.to, settled) - 1,+ };+ const shown = tracked.filter(f => f.t >= window.from && f.t <= window.to);+ for (let i = 1; i < shown.length; i += 1) {+ closest = Math.min(closest, shown[i].t - shown[i - 1].t);+ }+ runs.push({+ tracked,+ control: await trackMarker(page, castFrames, {rgb: CONTROL_RGB}),+ window,+ });+ windows.push(window);+ closed.push(+ await v.dialog.waitFor({state: 'hidden', timeout: 2000}).then(+ () => true,+ () => false,+ ),+ );+ }+ // A change of the backdrop's brightness counts, in 8-bit levels. So+ // judging stops where the fade's step between the closest two frames shown+ // falls below one level. A shown level is rounded, so half a level is added.+ const proof = pooledBusyProof(runs, {+ axis: 'x',+ settledWithin: wholeStepsUntil(closest) + 0.5,+ // A run whose control moved on fewer than two frames is too little to+ // judge. At least two of the four runs must be judged.+ minRunFrames: 2,+ minJudgedRuns: 2,+ });+ await writeEvidence(+ 'busy-main-thread/lightbox-dismiss',+ {+ [`${testInfo.project.name}.json`]: JSON.stringify(+ {windows, proof},+ null,+ 1,+ ),+ },+ testInfo,+ );+ // 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 screen+ // keeps changing with the control, and a main-thread fade would not.+ expect(proof.verdict.failures).toEqual([]);+ // Each judged run shows the backdrop at a new level on at least one of its+ // own frames, not an excused one. So runs of one frame cannot add up to the+ // floor.+ proof.judged.forEach((judged, i) => {+ const read = proof.runs[i]?.control;+ if (judged) {+ expect(+ (read?.movedWith ?? 0) - (read?.belowStep ?? 0),+ `run ${i + 1} shows a new backdrop level`,+ ).toBeGreaterThanOrEqual(1);+ }+ });+ // The cutoff above comes from two frames a run showed, not a default.+ expect(closest, 'a run shows two frames in its window').toBeLessThan(+ Number.POSITIVE_INFINITY,+ );+ for (const window of windows) {+ expect(window.to - window.from).toBeGreaterThan(100);+ }+ expect(closed).toEqual(windows.map(() => true));+});++/** How many dismissals the busy proof plays and judges pooled. */+const DISMISS_RUNS = 4;++test('under Reduce Motion the dismissal fades the photo out in place', async ({+ page,+}) => {+ await page.emulateMedia({reducedMotion: 'reduce'});+ const v = await openViewer(page);+ await v.driver.play(pullDown(v.centre, 110));+ await waitForAnimation(v.photo);+ const held = await holdAnimations(page, v.photo, {+ judges: {target: v.photo, property: 'opacity'},+ });+ const samples = await sampleCurve(v.photo, [0, 50]);+ await releaseAnimations(page);+ // Under reduced motion, a fade of 200 ms or less.+ expect(Math.max(...held.map(a => a.curveEndMs))).toBeLessThanOrEqual(205);+ // The travel lands at the end; meanwhile the photo fades where it was.+ expect(samples[0].transform.translateY).toBeCloseTo(+ samples[1].transform.translateY,+ 1,+ );+ expect(samples[1].opacity).toBeLessThan(samples[0].opacity);+ expect(held.length).toBeGreaterThan(0);+ await expect(v.dialog).toBeHidden();+});++test(+ 'storyboard: drag to dismiss',+ {tag: '@storyboard'},+ async ({page}, testInfo) => {+ const v = await openViewer(page);+ const board = await touchStoryboard(+ page,+ v.driver,+ drag(+ v.centre,+ {x: v.centre.x + 20, y: v.centre.y + 160},+ {+ durationMs: 300,+ hz: 20,+ restMs: 100,+ },+ ),+ {+ name: 'lightbox-drag-to-dismiss',+ measure: async () => {+ const s = await v.photoState();+ return {+ scale: +s.scale.toFixed(3),+ backdrop: +(await v.backdropAlpha()).toFixed(2),+ };+ },+ columns: 4,+ cellScale: 0.35,+ },+ );+ await board.write(testInfo);+ },+);++test("reopening at the dismissed photo's neighbour shows that photo", async ({+ page,+}) => {+ await page.route('https://picsum.photos/**', async route =>+ route.fulfill({contentType: 'image/svg+xml', body: photoSvg(3000, 2000)}),+ );+ await openStory(page, storybook(), 'core-lightbox--gallery');+ const driver = await touchDriver(page);+ const thumbnails = page.locator('#storybook-root img[style*="cover"]');+ const tapThumbnail = async (i: number) => {+ const b = await thumbnails.nth(i).boundingBox();+ if (b == null) {+ throw new Error('no thumbnail');+ }+ await driver.tap({x: b.x + b.width / 2, y: b.y + b.height / 2});+ };+ const dialog = page.getByRole('dialog');+ const current = dialog.locator('[data-current]');+ await tapThumbnail(1);+ await expect(dialog).toBeVisible();+ // A plain image opener zooms the photo out of it: wait for it to land.+ await waitForRest(current.locator('img'));+ await frames(page, 4);+ const rect = await current.locator('img').boundingBox();+ if (rect == null) {+ throw new Error('no photo');+ }+ await driver.play(+ pullDown({x: rect.x + rect.width / 2, y: rect.y + rect.height / 2}, 110),+ );+ await expect(dialog).toBeHidden();+ // The release faded the second photo's neighbours, the third among them.+ await tapThumbnail(2);+ await expect(dialog).toBeVisible();+ await frames(page, 4);+ expect(+ await current.evaluate(el => parseFloat(getComputedStyle(el).opacity)),+ ).toBe(1);+});++test('a caller that keeps the viewer open gets the photo, the backdrop and the controls back', async ({+ page,+}) => {+ const v = await openViewer(page, 'confirm');+ await v.driver.play(pullDown(v.centre, 110));+ // The photo comes back once the caller keeps the viewer open.+ await expect+ .poll(+ async () => {+ const s = await v.photoState();+ return Math.abs(s.y) < 0.5 && Math.abs(s.scale - 1) < 0.001;+ },+ {timeout: 3000},+ )+ .toBe(true);+ await expect(v.dialog).toBeVisible();+ const state = await v.photoState();+ expect(state.y).toBeCloseTo(0, 0);+ expect(state.scale).toBeCloseTo(1, 3);+ expect(await v.backdropAlpha()).toBeCloseTo(1, 2);+ expect(await v.closeAlpha()).toBeCloseTo(1, 2);+ // And a new drag follows the finger again.+ let followed = 0;+ await v.driver.play(pullDown(v.centre, 80), {+ onEvent: async step => {+ if (step.type === 'touchMove') {+ followed = Math.max(followed, (await v.photoState()).y);+ }+ },+ });+ expect(followed).toBeGreaterThan(20);+});++test('a photo dragged to dismiss draws above its caption', async ({page}) => {+ // Without zoom the caption sits right under the photo. So the drag carries+ // the photo over it while the caption still shows, faded.+ const v = await openViewer(page);+ const caption = v.dialog.locator('[data-lightbox-caption]');+ await expect(caption).toBeVisible();+ let compared = false;+ await v.driver.play(pullDown(v.centre, 100), {+ onEvent: async step => {+ if (+ compared ||+ step.type !== 'touchMove' ||+ step.changed[0].y - v.centre.y < 90+ ) {+ return;+ }+ compared = true;+ await frames(page, 1);+ const [photoBox, captionBox] = await Promise.all([+ v.photo.boundingBox(),+ caption.boundingBox(),+ ]);+ if (photoBox == null || captionBox == null) {+ throw new Error('no photo or caption');+ }+ // Where the photo covers the caption, 2 px inside both edges.+ const top = Math.ceil(Math.max(photoBox.y, captionBox.y)) + 2;+ const bottom =+ Math.floor(+ Math.min(+ photoBox.y + photoBox.height,+ captionBox.y + captionBox.height,+ ),+ ) - 2;+ const left = Math.ceil(Math.max(photoBox.x, captionBox.x)) + 2;+ const right =+ Math.floor(+ Math.min(+ photoBox.x + photoBox.width,+ captionBox.x + captionBox.width,+ ),+ ) - 2;+ // The cover spans the caption's text, and the caption still shows.+ expect(bottom - top).toBeGreaterThan(24);+ expect(+ await caption.evaluate(el => Number(getComputedStyle(el).opacity)),+ ).toBeGreaterThan(0.3);+ const clip = {x: left, y: top, width: right - left, height: bottom - top};+ const shown = await page.screenshot({clip});+ await caption.evaluate(el => {+ (el as HTMLElement).style.visibility = 'hidden';+ });+ const hidden = await page.screenshot({clip});+ await caption.evaluate(el => {+ (el as HTMLElement).style.visibility = '';+ });+ // Hiding the caption changes no pixel under the photo.+ expect(shown.equals(hidden)).toBe(true);+ },+ });+ expect(compared).toBe(true);+});++for (const story of ['zoom', 'gallery'] as const) {+ test(`a photo dragged to dismiss draws past the box it was fitted in (${story})`, async ({+ page,+ }) => {+ // Held sideways, a landscape photo fills its box's height, so the drag+ // carries it past the box's bottom edge at once.+ await page.setViewportSize({width: 874, height: 402});+ const v = await openViewer(page, story);+ const seen: {drawn?: {past: number; clippedBy: string | null}} = {};+ await v.driver.play(pullDown(v.centre, 140), {+ onEvent: async step => {+ if (+ seen.drawn != null ||+ step.type !== 'touchMove' ||+ step.changed[0].y - v.centre.y < 130+ ) {+ return;+ }+ await frames(page, 1);+ seen.drawn = await v.photo.evaluate(el => {+ const photo = el.getBoundingClientRect();+ const stage = el+ .closest('[data-zoom-dismissing]')+ ?.getBoundingClientRect();+ // The first box between the photo and the dialog that clips it.+ let clippedBy: string | null = null;+ for (+ let box = el.parentElement;+ box != null && box.tagName !== 'DIALOG';+ box = box.parentElement+ ) {+ if (+ getComputedStyle(box).overflowY !== 'visible' &&+ photo.bottom > box.getBoundingClientRect().bottom + 0.5+ ) {+ clippedBy = box.outerHTML.slice(0, 80);+ break;+ }+ }+ return {+ past: photo.bottom - (stage?.bottom ?? Number.NaN),+ clippedBy,+ };+ });+ },+ });+ // The photo reaches past its box, and no box cuts it off.+ expect(seen.drawn?.past).toBeGreaterThan(20);+ expect(seen.drawn?.clippedBy).toBeNull();+ });+}++test('a caption comes back under the photo once a drag to close springs back', async ({+ page,+}) => {+ // A 3:1 panorama leaves the stage free space below the fitted photo, so+ // the caption moves up under it.+ await page.route('https://picsum.photos/**', async route =>+ route.fulfill({+ contentType: 'image/svg+xml',+ body: photoSvg(3000, 1000),+ }),+ );+ await openStory(page, storybook(), 'core-lightbox--zoom-with-caption');+ const driver = await touchDriver(page);+ const trigger = await page+ .getByRole('button', {name: 'Open zoom with caption'})+ .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');+ const img = dialog.getByRole('img', {name: 'Forest path'});+ await expect+ .poll(async () => img.evaluate(el => (el as HTMLImageElement).naturalWidth))+ .toBe(3000);+ const caption = dialog.getByText('A winding path through the forest');+ const gap = async () => {+ const photo = await img.boundingBox();+ const below = await caption.boundingBox();+ if (photo == null || below == null) {+ throw new Error('no photo or caption');+ }+ return Math.round(below.y - (photo.y + photo.height));+ };+ await expect.poll(gap).toBe(0);+ const box = await img.boundingBox();+ if (box == null) {+ throw new Error('no photo');+ }+ // Down 60 px and back to the start, then lifted: the drag is cancelled.+ const start = {x: box.x + box.width / 2, y: box.y + box.height / 2};+ const down = {x: start.x, y: start.y + 60};+ await driver.play(+ drag(start, down, {durationMs: 300})+ .slice(0, -1)+ .concat(+ drag(down, start, {durationMs: 300, restMs: 150})+ .slice(1)+ .map(f => ({...f, t: f.t + 320})),+ ),+ );+ await expect(dialog).toBeVisible();+ await expect.poll(gap).toBe(0);+});++test("while the controls fade with a drag, a tap on Close still reaches it, above a gallery's pages", async ({+ page,+}) => {+ const v = await openViewer(page, 'gallery');+ const close = await v.close.boundingBox();+ if (close == null) {+ throw new Error('no Close button');+ }+ const at = {x: close.x + close.width / 2, y: close.y + close.height / 2};+ let hit = '';+ await v.driver.play(pullDown(v.centre, 100), {+ onEvent: async step => {+ if (+ step.type === 'touchMove' &&+ hit === '' &&+ (await v.closeAlpha()) < 0.95+ ) {+ hit = await page.evaluate(+ ([x, y]) => {+ const el = document.elementFromPoint(x, y);+ return (+ el?.closest('button')?.getAttribute('aria-label') ??+ el?.tagName ??+ 'nothing'+ );+ },+ [at.x, at.y],+ );+ }+ },+ });+ expect(hit).toBe('Close');+});++test('the backdrop dims and blurs the page, under a finger and with a mouse', async ({+ page,+ browser,+}) => {+ const filterOf = async (dialog: Locator) =>+ dialog.evaluate(el => {+ const style = getComputedStyle(+ el,+ '::backdrop',+ ) as CSSStyleDeclaration & {+ webkitBackdropFilter?: string;+ };+ return style.backdropFilter || style.webkitBackdropFilter || 'none';+ });+ const v = await openViewer(page);+ expect(+ await page.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(true);+ expect(await filterOf(v.dialog)).toBe('blur(2px)');+ // A fine pointer too.+ const context = await browser.newContext({+ viewport: {width: 1280, height: 800},+ hasTouch: false,+ isMobile: false,+ });+ try {+ const desktop = await context.newPage();+ expect(+ await desktop.evaluate(() => matchMedia('(pointer: coarse)').matches),+ ).toBe(false);+ await openStory(desktop, storybook(), STORIES.plain.id);+ await desktop.getByRole('button', {name: STORIES.plain.trigger}).click();+ const dialog = desktop.getByRole('dialog');+ await expect(dialog).toBeVisible();+ expect(await filterOf(dialog)).toBe('blur(2px)');+ } finally {+ await context.close();+ }+});diff --git a/packages/core/src/Lightbox/__tests__/LightboxDismissCancel.interaction.browser.spec.ts b/packages/core/src/Lightbox/__tests__/LightboxDismissCancel.interaction.browser.spec.tsnew file mode 100644index 0000000000..9fdd8b15d6--- /dev/null+++ b/packages/core/src/Lightbox/__tests__/LightboxDismissCancel.interaction.browser.spec.ts@@ -0,0 +1,520 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file LightboxDismissCancel.interaction.browser.spec.ts+ * @input The built "Default" Lightbox story on the phone project, real+ * touch input and the interaction harness+ * @output Proofs for the drags that do not dismiss, against Photos' measured+ * cancel rule. The viewer stays open, the photo springs back on+ * `springs.settle` and the backdrop and controls return. They also cover+ * Reduce Motion, a blocked main thread and a storyboard.+ * @position Interaction tests for Lightbox (browser), beside+ * LightboxDismiss.interaction.browser.spec.ts+ */++import {+ expect,+ test,+ type Locator,+ type Page,+} from '@astryxdesign/a11y-spec/playwright';+import {+ blockMainThread,+ busyWindowProof,+ compareCurve,+ CONTROL_RGB,+ curveOf,+ drag,+ frames,+ holdAnimations,+ markElement,+ openStory,+ releaseAnimations,+ sampleCurve,+ startBusyControl,+ startScreencast,+ timeline,+ touchDriver,+ type TouchDriver,+ type TouchScript,+ touchStoryboard,+ trackMarker,+ waitForAnimation,+ waitForRest,+ withStorybook,+ writeEvidence,+} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++/** The pan's begin threshold: travel before it is the finger's alone. */+const THRESHOLD = 10;+/**+ * `springs.settle` (response 0.5 s, critically damped) as a stiffness at mass+ * 1: (2π / 0.5 s)².+ */+const SETTLE_K = ((2 * Math.PI) / 0.5) ** 2;++/**+ * A critically damped spring towards 0 from `from` with velocity `v0`+ * (units/s), at `ms` milliseconds.+ */+function criticallyDamped(stiffness: number, from: number, v0 = 0) {+ const omega = Math.sqrt(stiffness);+ return (ms: number) => {+ const t = ms / 1000;+ return (from + (v0 + omega * from) * t) * Math.exp(-omega * t);+ };+}++function photoSvg(width: number, height: number): string {+ let squares = '';+ for (let y = 0; y < height; y += 50) {+ for (let x = 0; x < width; 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="${width}" height="${height}" viewBox="0 0 ${width} ${height}" shape-rendering="crispEdges"><rect width="${width}" height="${height}" fill="#fff"/><g fill="#000">${squares}</g><circle cx="${width / 2}" cy="${height / 2}" r="${height / 8}" fill="#d22"/></svg>`;+}++interface Viewer {+ driver: TouchDriver;+ dialog: Locator;+ photo: Locator;+ centre: {x: number; y: number};+ photoState: () => Promise<{x: number; y: number; scale: number}>;+ backdropAlpha: () => Promise<number>;+ closeAlpha: () => Promise<number>;+}++async function openViewer(page: Page): Promise<Viewer> {+ await page.route('https://picsum.photos/**', async route =>+ route.fulfill({contentType: 'image/svg+xml', body: photoSvg(3000, 2000)}),+ );+ await openStory(page, storybook(), 'core-lightbox--default');+ const driver = await touchDriver(page);+ const trigger = page.getByRole('button', {name: 'Open lightbox'});+ const box = await trigger.boundingBox();+ if (box == null) {+ throw new Error('no trigger');+ }+ await driver.tap({x: box.x + box.width / 2, y: box.y + box.height / 2});+ const dialog = page.getByRole('dialog');+ await expect(dialog).toBeVisible();+ const photo = dialog.locator('img').first();+ await expect+ .poll(async () =>+ photo.evaluate(el => (el as HTMLImageElement).naturalWidth),+ )+ .toBe(3000);+ await waitForRest(photo);+ const rect = await photo.boundingBox();+ if (rect == null) {+ throw new Error('no photo');+ }+ return {+ driver,+ dialog,+ photo,+ centre: {x: rect.x + rect.width / 2, y: rect.y + rect.height / 2},+ photoState: async () =>+ photo.evaluate(el => {+ const style = getComputedStyle(el);+ const [x = '0', y = '0'] =+ style.translate === 'none' ? [] : style.translate.split(' ');+ return {+ x: parseFloat(x),+ y: parseFloat(y),+ scale: style.scale === 'none' ? 1 : parseFloat(style.scale),+ };+ }),+ backdropAlpha: async () =>+ dialog.evaluate(el =>+ parseFloat(getComputedStyle(el, '::backdrop').opacity),+ ),+ closeAlpha: async () =>+ dialog+ .locator('[data-lightbox-chrome]')+ .first()+ .evaluate(el => parseFloat(getComputedStyle(el).opacity)),+ };+}++/** Down by `dy`, then quickly back up by `up`: released moving up. */+function pullThenFlickUp(+ from: {x: number; y: number},+ dy: number,+ up: number,+): TouchScript {+ const down = {x: from.x, y: from.y + dy};+ return drag(from, down, {durationMs: 400})+ .slice(0, -1)+ .concat(+ drag(down, {x: down.x, y: down.y - up}, {durationMs: 60})+ .slice(1)+ .map(f => ({...f, t: f.t + 420})),+ );+}++/** Down by `dy`, then back to `travel` past the pan's threshold, held still. */+function pullThenReturn(+ from: {x: number; y: number},+ dy: number,+ travel: number,+): TouchScript {+ const down = {x: from.x, y: from.y + dy};+ return drag(from, down, {durationMs: 300})+ .slice(0, -1)+ .concat(+ drag(+ down,+ {x: down.x, y: from.y + THRESHOLD + travel},+ {durationMs: 300, restMs: 150},+ )+ .slice(1)+ .map(f => ({...f, t: f.t + 320})),+ );+}++/**+ * The held return's translateY and scale curves, and how long it runs. The+ * hold judges the motions the test reads.+ */+async function heldReturn(+ page: Page,+ photo: Locator,+ judged: ReadonlyArray<'translate' | 'scale'>,+) {+ const held = await holdAnimations(page, photo, {+ judges: judged.map(property => ({target: photo, property})),+ });+ const duration = Math.max(...held.map(a => a.curveEndMs));+ const samples = await sampleCurve(photo, timeline(duration));+ await releaseAnimations(page);+ return {+ held,+ duration,+ y: curveOf(samples, 'translateY'),+ scale: curveOf(samples, 'scaleX'),+ };+}++/** The viewer stays open, the photo at rest at the fitted size, all faded back. */+async function expectRestored(v: Viewer) {+ await waitForRest(v.photo);+ await expect(v.dialog).toBeVisible();+ expect(await v.photoState()).toEqual({x: 0, y: 0, scale: 1});+ await expect.poll(v.backdropAlpha).toBeCloseTo(1, 2);+ await expect.poll(v.closeAlpha).toBeCloseTo(1, 2);+}++test('released moving up, the photo springs back on springs.settle and the viewer stays open', async ({+ page,+}, testInfo) => {+ const v = await openViewer(page);+ await v.driver.play(pullThenFlickUp(v.centre, 150, 60));+ const [ret] = await waitForAnimation(v.photo);+ const back = await heldReturn(page, v.photo, ['translate', 'scale']);+ // The size returns from rest. The position carries the finger's upward+ // velocity, read from the first two samples as one unknown. The rest of the+ // curve must follow springs.settle.+ const size = compareCurve(+ back.scale,+ t => 1 + criticallyDamped(SETTLE_K, back.scale[0].value - 1)(t),+ 0.002,+ );+ const omega = Math.sqrt(SETTLE_K);+ const [s0, s1] = back.y;+ const t1 = (s1.t - s0.t) / 1000;+ const v0 =+ (s1.value * Math.exp(omega * t1) - s0.value) / t1 - omega * s0.value;+ const position = compareCurve(+ back.y,+ t => criticallyDamped(SETTLE_K, s0.value, v0)(t - s0.t),+ 0.75,+ );+ await writeEvidence(+ 'curves/lightbox-dismiss-cancel-up',+ {+ [`${testInfo.project.name}.json`]: JSON.stringify(+ {ret, back, v0, size, position},+ null,+ 1,+ ),+ },+ testInfo,+ );+ expect(back.y[0].value).toBeGreaterThan(40);+ expect(back.scale[0].value).toBeLessThan(0.99);+ expect(size.maxError, JSON.stringify(size.worst)).toBeLessThanOrEqual(0.002);+ expect(position.maxError, JSON.stringify(position.worst)).toBeLessThanOrEqual(+ 0.75,+ );+ await expectRestored(v);+});++test('brought back within 10 pt of the start and held still, it springs back from rest', async ({+ page,+}, testInfo) => {+ const v = await openViewer(page);+ await v.driver.play(pullThenReturn(v.centre, 120, 4));+ const [ret] = await waitForAnimation(v.photo);+ const back = await heldReturn(page, v.photo, ['translate']);+ const position = compareCurve(+ back.y,+ criticallyDamped(SETTLE_K, back.y[0].value),+ 0.25,+ );+ await writeEvidence(+ 'curves/lightbox-dismiss-cancel-return',+ {+ [`${testInfo.project.name}.json`]: JSON.stringify(+ {ret, back, position},+ null,+ 1,+ ),+ },+ testInfo,+ );+ expect(back.y[0].value).toBeGreaterThan(2);+ expect(position.maxError, JSON.stringify(position.worst)).toBeLessThanOrEqual(+ 0.25,+ );+ await expectRestored(v);+});++test('the backdrop keeps its blur at rest and fades without it while it moves', async ({+ page,+}) => {+ const v = await openViewer(page);+ const filter = async () =>+ v.dialog.evaluate(el => {+ const style = getComputedStyle(+ el,+ '::backdrop',+ ) as CSSStyleDeclaration & {webkitBackdropFilter?: string};+ return style.backdropFilter || style.webkitBackdropFilter || 'none';+ });+ expect(await filter()).toBe('blur(2px)');+ // On a 2-core limit a full-viewport blur repainted every frame of the fade+ // drops frames, so the drag fades the backdrop without it.+ let during: string | null = null;+ let moves = 0;+ await v.driver.play(pullThenReturn(v.centre, 120, 4), {+ onEvent: async step => {+ moves += step.type === 'touchMove' ? 1 : 0;+ if (step.type === 'touchMove' && moves === 10 && during == null) {+ during = await filter();+ }+ },+ });+ expect(during).toBe('none');+ await expectRestored(v);+ await expect.poll(filter).toBe('blur(2px)');+});++test('an 18 px flick down closes: its projected travel passes the commit point (FR36)', async ({+ page,+}) => {+ const v = await openViewer(page);+ // About 8 pt past the pan's threshold, quickly: short of the 10 pt commit+ // point, but the release velocity carries its projection past it.+ await v.driver.play(+ drag(+ v.centre,+ {x: v.centre.x, y: v.centre.y + 18},+ {durationMs: 40, restMs: 0},+ ),+ );+ await expect(v.dialog).toBeHidden();+});++test('without zoom, a dragged photo draws outside its own box', async ({+ page,+}) => {+ const v = await openViewer(page);+ let clipping: string[] | null = null;+ let moves = 0;+ await v.driver.play(+ drag(+ v.centre,+ {x: v.centre.x, y: v.centre.y + 120},+ {durationMs: 600, restMs: 150},+ ),+ {+ onEvent: async step => {+ moves += step.type === 'touchMove' ? 1 : 0;+ if (step.type === 'touchMove' && moves === 12 && clipping == null) {+ // Every box between the photo and the dialog (which clips at the+ // screen's edge) lets the moved photo show.+ clipping = await v.photo.evaluate(el => {+ const found: string[] = [];+ for (+ let box = el.parentElement;+ box != null && box.tagName !== 'DIALOG';+ box = box.parentElement+ ) {+ if (getComputedStyle(box).overflow !== 'visible') {+ found.push(box.className);+ }+ }+ return found;+ });+ }+ },+ },+ );+ expect(clipping).toEqual([]);+});++test('a slow short drag released below the threshold springs back', async ({+ page,+}, testInfo) => {+ const v = await openViewer(page);+ // 8 pt past the pan's threshold, slowly, held still: below the 10 pt a+ // release needs to dismiss.+ await v.driver.play(+ drag(+ v.centre,+ {x: v.centre.x, y: v.centre.y + THRESHOLD + 8},+ {durationMs: 600, restMs: 150},+ ),+ );+ const [ret] = await waitForAnimation(v.photo);+ const back = await heldReturn(page, v.photo, ['translate']);+ const position = compareCurve(+ back.y,+ criticallyDamped(SETTLE_K, back.y[0].value),+ 0.25,+ );+ await writeEvidence(+ 'curves/lightbox-dismiss-cancel-short',+ {+ [`${testInfo.project.name}.json`]: JSON.stringify(+ {ret, back, position},+ null,+ 1,+ ),+ },+ testInfo,+ );+ expect(back.y[0].value).toBeGreaterThan(4);+ expect(position.maxError, JSON.stringify(position.worst)).toBeLessThanOrEqual(+ 0.25,+ );+ await expectRestored(v);+});++test('under Reduce Motion a cancelled drag returns by a fade of 200 ms or less, with no travel', async ({+ page,+}) => {+ // Under reduced motion, what a touch release starts fades in place. It never+ // moves or scales on its way back.+ await page.emulateMedia({reducedMotion: 'reduce'});+ const v = await openViewer(page);+ await v.driver.play(pullThenFlickUp(v.centre, 150, 60));+ await waitForAnimation(v.photo);+ const held = await holdAnimations(page, v.photo, {+ judges: {target: v.photo, property: 'opacity'},+ });+ const duration = Math.max(...held.map(a => a.curveEndMs));+ const samples = await sampleCurve(v.photo, timeline(duration));+ await releaseAnimations(page);+ expect(duration).toBeLessThanOrEqual(205);+ const ys = samples.map(s => s.transform.translateY);+ const from = ys[0];+ const to = ys.at(-1) ?? from;+ for (const y of ys) {+ expect(Math.min(Math.abs(y - from), Math.abs(y - to))).toBeLessThan(0.5);+ }+ await waitForRest(v.photo);+ await expect(v.dialog).toBeVisible();+ await expectRestored(v);+});++test('the cancel keeps moving every frame while the main thread is blocked', async ({+ page,+}, testInfo) => {+ const v = await openViewer(page);+ await markElement(v.photo, {mode: 'outline'});+ // A compositor-only control animation in the same window: what the+ // compositor presented while the main thread spun, on this machine.+ await startBusyControl(page);+ const cast = await startScreencast(page);+ // Pulled 300 px, so the return is long enough to judge on a loaded runner.+ await v.driver.play(pullThenFlickUp(v.centre, 300, 60));+ // Blocked inside the page once the return runs on the compositor, 16 ms in,+ // as the dismissal's proof is. A block started from the test lands later in+ // the return, by a varying amount, and leaves less of it to judge.+ const block = await blockMainThread(page, 600, {+ during: v.photo,+ minProgressMs: 16,+ });+ // A few frames after the block, so the screencast holds its end.+ await frames(page, 6);+ const castFrames = await cast.stop();+ const tracked = await trackMarker(page, castFrames);+ const control = await trackMarker(page, castFrames, {rgb: CONTROL_RGB});+ // The spring slows hard at its end. Near the end each 60 Hz frame moves it+ // about 0.18 of what remains (2π / 0.5 s, critically damped). So within+ // about 5.6 cast steps of its end a frame moves less than one step, and+ // the cast shows plateaus there. Judging stops six cast steps from the end.+ const proof = busyWindowProof(+ tracked,+ {from: block.from, to: block.to},+ {axis: 'y', settledWithinSteps: 6, control},+ );+ await writeEvidence(+ 'busy-main-thread/lightbox-dismiss-cancel',+ {+ [`${testInfo.project.name}.json`]: JSON.stringify(+ {block, proof, control},+ null,+ 1,+ ),+ },+ testInfo,+ );+ // 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.+ expect(proof.verdict.failures).toEqual([]);+ expect(proof.monotonic).toBe(true);+ await expectRestored(v);+});++test(+ 'storyboard: a cancelled drag',+ {tag: '@storyboard'},+ async ({page}, testInfo) => {+ const v = await openViewer(page);+ const down = {x: v.centre.x, y: v.centre.y + 150};+ const script: TouchScript = drag(v.centre, down, {+ durationMs: 300,+ hz: 20,+ })+ .slice(0, -1)+ .concat(+ drag(down, {x: down.x, y: down.y - 120}, {durationMs: 150, hz: 20})+ .slice(1)+ .map(f => ({...f, t: f.t + 320})),+ );+ const board = await touchStoryboard(page, v.driver, script, {+ name: 'lightbox-drag-cancel',+ measure: async () => {+ const s = await v.photoState();+ return {+ y: +s.y.toFixed(1),+ scale: +s.scale.toFixed(3),+ backdrop: +(await v.backdropAlpha()).toFixed(2),+ };+ },+ columns: 5,+ cellScale: 0.35,+ });+ await board.write(testInfo);+ },+);diff --git a/packages/core/src/Lightbox/__tests__/LightboxEveryPointer.interaction.browser.spec.ts b/packages/core/src/Lightbox/__tests__/LightboxEveryPointer.interaction.browser.spec.tsindex 552f709b31..6b7790bc7b 100644--- a/packages/core/src/Lightbox/__tests__/LightboxEveryPointer.interaction.browser.spec.ts+++ b/packages/core/src/Lightbox/__tests__/LightboxEveryPointer.interaction.browser.spec.ts@@ -3,14 +3,14 @@/*** @file LightboxEveryPointer.interaction.browser.spec.ts* @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+ * stories in a desktop context. It has a mouse and a trackpad's wheel, and+ * in Chromium a pen and timed mouse events* @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. A mouse drag sideways and a trackpad's horizontal scroll leave a- * gallery on its photo+ * stops it. A mouse's sideways drag and a trackpad's sideways scroll leave a+ * gallery on its photo. A drag down by a mouse, a pen or a trackpad, or a+ * wheel's notch, leaves a fitted photo in place* @position Interaction tests for Lightbox (browser), beside* LightboxZoomModes.interaction.browser.spec.ts*/@@ -165,6 +165,28 @@ async function timedPointer(page: Page, pointerType: 'mouse' | 'pen') {};}+test('a mouse drag down leaves a fitted photo and the viewer in place, as on main', async ({+ browser,+}) => {+ // The drag to close belongs to the touch presentation. Where the primary+ // pointer is fine, a mouse drag leaves the photo where it is.+ const {context, page, dialog, img, centre} = await openDesktop(+ browser,+ 'with-zoom',+ );+ try {+ const before = await boxOf(img);+ await mouseDrag(page, centre, {x: centre.x, y: centre.y + 150}, 10);+ expect(Math.abs((await boxOf(img)).y - before.y)).toBeLessThan(1);+ await page.mouse.up();+ await frames(page, 30);+ await expect(dialog).toBeVisible();+ expect(Math.abs((await boxOf(img)).y - before.y)).toBeLessThan(1);+ } finally {+ await context.close();+ }+});+test('a mouse drag sideways leaves a gallery on its photo, as on main', async ({browser,}) => {@@ -447,3 +469,99 @@ test('a zoomed photo stops at a mouse drag’s release, as on main', async ({await context.close();}});++test('a pen drag down leaves a fitted photo and the viewer in place', async ({+ browser,+ browserName,+}) => {+ test.skip(+ browserName !== 'chromium',+ 'Pen input is dispatched through the Chrome DevTools Protocol.',+ );+ const {context, page, dialog, img, centre} = await openDesktop(+ browser,+ 'with-zoom',+ );+ try {+ const before = await boxOf(img);+ const pen = await timedPointer(page, 'pen');+ await pen('mouseMoved', centre, 0);+ await pen('mousePressed', centre, 16);+ for (let i = 1; i <= 8; i++) {+ await pen('mouseMoved', {x: centre.x, y: centre.y + 20 * i}, 24);+ }+ expect(Math.abs((await boxOf(img)).y - before.y)).toBeLessThan(1);+ await pen('mouseReleased', {x: centre.x, y: centre.y + 160}, 8);+ await frames(page, 30);+ await expect(dialog).toBeVisible();+ } finally {+ await context.close();+ }+});++test("a trackpad's scroll down leaves a fitted photo and the viewer in place", async ({+ browser,+ browserName,+}) => {+ test.skip(browserName !== 'webkit', WHEEL_DRIVERS);+ const {wheel, context, page, dialog, img, centre} = await openDesktop(+ browser,+ 'with-zoom',+ );+ try {+ const before = await boxOf(img);+ await page.mouse.move(centre.x, centre.y);+ const lowest = page.evaluate(+ async () =>+ new Promise<number>(resolve => {+ const photo = document.querySelector('dialog img');+ let low = photo?.getBoundingClientRect().y ?? 0;+ const t0 = performance.now();+ const tick = () => {+ low = Math.max(low, photo?.getBoundingClientRect().y ?? low);+ if (performance.now() - t0 < 400) {+ requestAnimationFrame(tick);+ } else {+ resolve(low);+ }+ };+ requestAnimationFrame(tick);+ }),+ );+ // A trackpad's swipe down, under natural scrolling. No delta is a+ // multiple of 40 px, which would read as a mouse wheel's notch.+ for (let i = 0; i < 10; i++) {+ await wheel(0, -12);+ await frames(page, 1);+ }+ // The drag to close belongs to the touch presentation: the photo stays.+ expect(await lowest).toBeLessThan(before.y + 1);+ await frames(page, 30);+ await expect(dialog).toBeVisible();+ } finally {+ await context.close();+ }+});++test("a mouse wheel's notch leaves a fitted photo and the viewer in place", async ({+ browser,+ browserName,+}) => {+ test.skip(browserName !== 'chromium', WHEEL_DRIVERS);+ const {wheel, context, page, dialog, img, centre} = await openDesktop(+ browser,+ 'with-zoom',+ );+ try {+ const before = await boxOf(img);+ await page.mouse.move(centre.x, centre.y);+ await wheel(0, -100);+ // 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);+ expect(Math.abs((await boxOf(img)).y - before.y)).toBeLessThan(1);+ await expect(dialog).toBeVisible();+ } finally {+ await context.close();+ }+});diff --git a/packages/core/src/Lightbox/useZoomCore.ts b/packages/core/src/Lightbox/useZoomCore.tsindex 6c8d5a5e41..6cbaa44aa7 100644--- a/packages/core/src/Lightbox/useZoomCore.ts+++ b/packages/core/src/Lightbox/useZoomCore.ts@@ -130,6 +130,11 @@ 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;+ /**+ * Reports that the photo shows at its fitted size again, when an animation+ * the core did not start lands there (`onFitChange`).+ */+ setAtFit(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. */@@ -493,6 +498,7 @@ export function useZoomCore(options: UseZoomCoreOptions): ZoomCore {write,setTarget,setZoomed,+ setAtFit,isMoving,isAtEdgeOf,settleTo,@@ -506,6 +512,7 @@ export function useZoomCore(options: UseZoomCoreOptions): ZoomCore {write,setTarget,setZoomed,+ setAtFit,isMoving,isAtEdgeOf,settleTo,diff --git a/packages/core/src/Lightbox/useZoomStage.ts b/packages/core/src/Lightbox/useZoomStage.tsindex b77f28c171..c1669ae54b 100644--- a/packages/core/src/Lightbox/useZoomStage.ts+++ b/packages/core/src/Lightbox/useZoomStage.ts@@ -6,8 +6,8 @@* @file useZoomStage.ts* @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+ * whether the gestures and the touch presentation are on, the current+ * item's key, the drag to close, 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@@ -19,7 +19,7 @@* __tests__/LightboxPaging.interaction.browser.spec.ts.*/-import {useRef, useState, type RefObject} from 'react';+import {useMemo, useRef, useState, type RefObject} from 'react';import type {GestureRecognizer} from '../gestures/GestureRecognizer';import {LongPressGestureRecognizer} from '../gestures/LongPressGestureRecognizer';import {PanGestureRecognizer} from '../gestures/PanGestureRecognizer';@@ -31,7 +31,14 @@ import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import {UIKIT_PAN} from '../motion/uikit/gestures';import {coast as coastCurves} from '../motion/coast';import {decayRestDistance} from '../motion/decay';+import {resolveMotion} from '../motion/resolveMotion';+import {springs} from '../motion/uikit/springs';+import {zoomMedia} from '../motion/uikit/zoomMedia';import {+ IDENTITY,+ dismissCommits,+ dismissExitY,+ dismissTransform,doubleTapTarget,draggedTransform,isZoomed,@@ -53,6 +60,12 @@ import {export {ZOOM_DRAGGING_ATTRIBUTE, type ZoomStage};+/**+ * Set on the stage while a drag to dismiss moves the photo, until it settles.+ * A stage that only hugs the photo then lets the moved photo draw outside it.+ */+export const ZOOM_DISMISSING_ATTRIBUTE = 'data-zoom-dismissing';+export interface UseZoomStageOptions {/** The stage: the box the photo is fitted and centred in, clipping it. */stageRef: RefObject<HTMLElement | null>;@@ -60,6 +73,8 @@ export interface UseZoomStageOptions {surfaceRef?: RefObject<HTMLElement | null>;/** The gestures are on (zoom is on), for every pointer. */isEnabled: boolean;+ /** Changes when another item shows: a drag to dismiss in progress ends. */+ itemKey: unknown;/*** 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@@ -84,6 +99,37 @@ export interface UseZoomStageOptions {* edge. Without one, the pan begins there and gives past the edge.*/hasOuterPager?: boolean;+ /** Drag to dismiss, as Photos has it; none without. */+ dismiss?: ZoomStageDismiss;+}++/**+ * Photos' drag to dismiss. A one-finger drag that starts downward on a photo+ * at its fitted size carries it. Its centre follows the finger, and it+ * shrinks with the travel. The release dismisses or springs back. The owner+ * fades its backdrop and controls by the travel and closes once the photo+ * has left.+ */+export interface ZoomStageDismiss {+ /** Whether a drag can dismiss now (an image, in the touch presentation). */+ isEnabled: boolean;+ /** Each move of the drag: its downward travel, pt. */+ onDrag: (travel: number) => void;+ /**+ * The release: whether it dismisses, so the photo leaves, or springs back,+ * and whether a finger released it. Under reduced motion a finger's+ * release cross-fades. A mouse's, a trackpad's or a pen's cross-fades on a+ * coarse primary pointer.+ */+ onRelease: (dismisses: boolean, touch: boolean) => void;+ /** The dismissed photo has left the stage. */+ onDismissed: () => void;+}++/** The touch layer's additions to the core's API. */+export interface ZoomStageWithTouch extends ZoomStage {+ /** A dismissed photo back at its fitted size at once (the viewer opens again). */+ reset(): void;}interface PinchSession {@@ -143,6 +189,13 @@ const TAP_POINTERS = ['touch'] as const;* on a moving photo stops it where it shows, and a lift with no drag lets* 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.+ * - with `dismiss`, a pan that begins only downward on a photo at its fitted+ * size: Photos' drag to dismiss. One finger, a mouse's or a pen's drag, or+ * a trackpad's scroll drives it. The photo's centre follows the pointer, and+ * it shrinks by the travel. A release moving up, or back at the start,+ * springs back on `springs.settle`. Any other sends it on down on the+ * dismissal's measured spring and reports it once it has left. A dismissed+ * photo is not caught.** The stage's `touch-action` is the caller's (none while zoom is on), since a* disabled recognizer would still claim it.@@ -157,22 +210,28 @@ const TAP_POINTERS = ['touch'] as const;export function useZoomStage(core: ZoomCore,options: UseZoomStageOptions,-): ZoomStage {+): ZoomStageWithTouch {const {animator,geometryRef,+ targetRef,measure,toStage,current,write,setTarget,setZoomed,+ setAtFit,settleTo,isMoving,isAtEdgeOf,} = core;const pinchRef = useRef<PinchSession | null>(null);const panRef = useRef<PanSession | null>(null);+ /** A drag to dismiss in progress: the geometry it started from. */+ const dismissRef = useRef<ZoomGeometry | null>(null);+ /** A dismissed photo is leaving: nothing catches it. */+ const leavingRef = useRef(false);/** A touch stopped a moving photo; a pan or pinch has since taken over. */const caughtRef = useRef(false);const draggedSinceCatchRef = useRef(false);@@ -215,6 +274,10 @@ export function useZoomStage((recognizer: GestureRecognizer) => boolean>(() => true);const {shouldBeginPinch, hasOuterPager = false} = options;+ // A drag to dismiss starts downward on a photo at its fitted size.+ const dismissShouldBeginRef = useRef<(pan: PanGestureRecognizer) => boolean>(+ () => false,+ );useIsomorphicLayoutEffect(() => {pinchShouldBeginRef.current = shouldBeginPinch ?? (() => true);panShouldBeginRef.current = pan => {@@ -232,14 +295,26 @@ export function useZoomStage(isAtEdgeOf(geometry, x < 0 ? 'left' : 'right'));};- isMovingRef.current = isMoving;+ isMovingRef.current = () => !leavingRef.current && isMoving();+ dismissShouldBeginRef.current = pan => {+ if (options.dismiss?.isEnabled !== true || leavingRef.current) {+ return false;+ }+ // Where the photo is going: one zooming in is not dismissed.+ const geometry = measure();+ if (geometry == null || isZoomed(geometry, targetRef.current)) {+ return false;+ }+ const {x, y} = pan.totalTranslation();+ return y > 0 && y >= Math.abs(x);+ };});// 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// is fine.- const fingerRef = useRef({pinch: false, catch: false});+ const fingerRef = useRef({pinch: false, catch: false, dismiss: false});const [recognizers] = useState(() => {const pinch = new PinchGestureRecognizer({name: 'Lightbox.zoomPinch',@@ -285,12 +360,19 @@ export function useZoomStage(// everyone else (an outer pager's own catch).shouldBegin: () => isMovingRef.current(),});+ const dismissPan = new PanGestureRecognizer({+ name: 'Lightbox.dismissPan',+ maximumNumberOfTouches: 1,+ allowedPointerTypes: EVERY_POINTER,+ allowedScrollTypes: ['continuous'],+ shouldBegin: recognizer => dismissShouldBeginRef.current(recognizer),+ });pinch.recognizeSimultaneouslyWith(pan);tap.requireToFail(doubleTap);- for (const other of [pinch, pan, doubleTap, tap]) {+ for (const other of [pinch, pan, doubleTap, tap, dismissPan]) {touchDown.recognizeSimultaneouslyWith(other);}- return {pinch, pan, doubleTap, tap, touchDown};+ return {pinch, pan, doubleTap, tap, touchDown, dismissPan};});const recognizerOptions = {isEnabled: options.isEnabled, manageStyle: false};@@ -551,5 +633,130 @@ export function useZoomStage(recognizerOptions,);- return core.api;+ useGestureRecognizer(+ surfaceRef,+ () => recognizers.dismissPan,+ pan => {+ const dismiss = options.dismiss;+ if (pan.state === 'began') {+ fingerRef.current.dismiss =+ pan.trackedTouches[0]?.pointerType === 'touch';+ const geometry = measure();+ if (geometry == null || dismiss == null) {+ return;+ }+ animator.stop();+ options.onDragStart?.();+ dismissRef.current = geometry;+ options.stageRef.current?.setAttribute(ZOOM_DISMISSING_ATTRIBUTE, '');+ }+ const geometry = dismissRef.current;+ if (geometry == null) {+ return;+ }+ const translation = pan.translation();+ if (pan.state === 'began' || pan.state === 'changed') {+ write(dismissTransform(geometry, translation.x, translation.y));+ dismiss?.onDrag(Math.max(0, translation.y));+ return;+ }+ // Ended or cancelled.+ dismissRef.current = null;+ // The release rule and the motion read the shared filter's velocity at+ // the lift, at rest after a silent hold.+ const velocity = pan.velocity();+ const dismisses =+ pan.state === 'ended' && dismissCommits(translation.y, velocity.y);+ dismiss?.onRelease(dismisses, fingerRef.current.dismiss);+ const shown = current();+ if (dismisses) {+ leavingRef.current = true;+ // No thumbnail to return to, so straight on down on the dismissal's+ // position spring, from the release velocity, until it leaves the+ // screen. A stage that only hugs the photo sits above its bottom. The+ // screen's bottom is in stage px, from the pan's first measure.+ const view = options.stageRef.current?.ownerDocument.defaultView;+ const y = dismissExitY(+ geometry,+ shown,+ view != null+ ? toStage({x: 0, y: view.innerHeight}).y+ : geometry.height,+ );+ setTarget({...shown, y});+ const handle = animator.animate(+ {x: shown.x, y},+ {+ spring: zoomMedia.dismiss.dismissPositionSpring,+ velocity: {x: velocity.x, y: velocity.y},+ },+ {crossfadeAs: 'exit', touchRelease: fingerRef.current.dismiss},+ );+ void handle.finished.then(() => {+ if (leavingRef.current) {+ dismiss?.onDismissed();+ }+ });+ return;+ }+ setTarget(IDENTITY);+ // A cancelled drag's return is not an exit, so it plays the shared+ // settle spring, read where the stage is, from the release velocity.+ const settle = resolveMotion(options.stageRef.current, springs.settle);+ const position = animator.animate(+ {x: 0, y: 0},+ {spring: settle, velocity: {x: velocity.x, y: velocity.y}},+ {touchRelease: fingerRef.current.dismiss},+ );+ const size = animator.animate(+ {scale: 1},+ {spring: settle},+ {touchRelease: fingerRef.current.dismiss},+ );+ // Back in its box: the stage clips again, unless another drag began,+ // and the photo is at its fitted size again once both springs land.+ void Promise.all([position.finished, size.finished]).then(+ ([moved, sized]) => {+ if (dismissRef.current == null && !leavingRef.current) {+ options.stageRef.current?.removeAttribute(+ ZOOM_DISMISSING_ATTRIBUTE,+ );+ if (moved && sized) {+ setAtFit(true);+ }+ }+ },+ );+ },+ {isEnabled: options.dismiss?.isEnabled === true, manageStyle: false},+ );++ // Another item: a drag to dismiss in progress ends, and the stage clips its+ // photo again. The core puts the photo back at the fitted size.+ const {stageRef} = options;+ useIsomorphicLayoutEffect(() => {+ dismissRef.current = null;+ leavingRef.current = false;+ stageRef.current?.removeAttribute(ZOOM_DISMISSING_ATTRIBUTE);+ }, [options.itemKey, stageRef]);++ const api = core.api;+ return useMemo(+ () => ({+ ...api,+ reset: () => {+ if (!leavingRef.current) {+ return;+ }+ leavingRef.current = false;+ dismissRef.current = null;+ animator.stop();+ animator.set({x: 0, y: 0, scale: 1, opacity: 1});+ setTarget(IDENTITY);+ setAtFit(true);+ stageRef.current?.removeAttribute(ZOOM_DISMISSING_ATTRIBUTE);+ },+ }),+ [animator, api, setAtFit, setTarget, stageRef],+ );}diff --git a/packages/core/src/Lightbox/zoomStage.test.ts b/packages/core/src/Lightbox/zoomStage.test.tsindex 374b7e2f80..1913a271b9 100644--- a/packages/core/src/Lightbox/zoomStage.test.ts+++ b/packages/core/src/Lightbox/zoomStage.test.ts@@ -2,19 +2,29 @@/*** @file zoomStage.test.ts- * @input vitest, the zoom stage geometry and the UIKit zoom constants+ * @input vitest, the zoom stage geometry, the UIKit zoom constants and+ * Lightbox's record* @output Checks the zoom stage against UIKit's measured zooming and* Lightbox's own zoom. It covers the overshoot, the maximum zoom, both- * double taps, resting places, a drag's rubber band, a resize and the+ * double taps and resting places. It also covers a drag's rubber band, a+ * resize, Photos' drag to dismiss, its springs in the record and the* keyboard's zoom* @position Testing; zoomStage.ts without a browser*/+import {readFileSync} from 'node:fs';+import {resolve} from 'node:path';import {describe, expect, it} from 'vitest';import {rubberBand} from '../motion/rubberBand';+import {zoomMedia} from '../motion/uikit/zoomMedia';import {IDENTITY,ZOOM_STEP,+ dismissBackdropAlpha,+ dismissChromeAlpha,+ dismissCommits,+ dismissExitY,+ dismissTransform,doubleClickTarget,doubleTapScaleFor,doubleTapTarget,@@ -337,6 +347,122 @@ describe('the double-click: 2× about the clicked point', () => {});});+describe("Photos' drag to dismiss (iOS 26.2)", () => {+ // Photos, a 3000 × 2000 photo at its fitted size dragged down: travel →+ // photo scale, backdrop alpha, neighbours' and controls' alpha.+ const measured = [+ {travel: 25, scale: 0.997, backdrop: 1.0, chrome: 0.96},+ {travel: 65, scale: 0.978, backdrop: 0.95, chrome: 0.76},+ {travel: 105, scale: 0.942, backdrop: 0.86, chrome: 0.52},+ {travel: 145, scale: 0.899, backdrop: 0.71, chrome: 0.33},+ ];++ it('shrinks the photo about its centre, which follows the finger', () => {+ const geometry = landscape();+ for (const row of measured) {+ const t = dismissTransform(geometry, 12, row.travel);+ expect(t.scale).toBeCloseTo(row.scale, 2);+ // The fitted box's centre moved by exactly the finger's travel.+ const centre = shown(geometry, t, 201, 134);+ expect(centre.x).toBeCloseTo(geometry.fit.x + 201 + 12, 6);+ expect(centre.y).toBeCloseTo(geometry.fit.y + 134 + row.travel, 6);+ }+ // Above where the drag started, the photo follows without shrinking.+ expect(dismissTransform(geometry, 0, -30)).toEqual({+ x: 0,+ y: -30,+ scale: 1,+ });+ });++ it('fades the backdrop and, faster, the controls', () => {+ for (const row of measured) {+ expect(dismissBackdropAlpha(row.travel)).toBeCloseTo(row.backdrop, 1);+ expect(+ Math.abs(dismissChromeAlpha(row.travel) - row.chrome),+ ).toBeLessThan(0.02);+ }+ expect(dismissBackdropAlpha(-10)).toBe(1);+ expect(dismissChromeAlpha(0)).toBe(1);+ expect(dismissChromeAlpha(1000)).toBe(0);+ });++ it('dismisses on any release unless moving up or back at the start', () => {+ // Pulls of 20, 40 and 60 pt held still, then lifted, dismiss. So do a+ // 60 pt flick and a slow downward release.+ expect(dismissCommits(20, 0)).toBe(true);+ expect(dismissCommits(60, 1500)).toBe(true);+ expect(dismissCommits(100, 40)).toBe(true);+ // A pull flicked back up cancels, as does one brought back to ~5 pt.+ expect(dismissCommits(150, -800)).toBe(false);+ expect(dismissCommits(5, 0)).toBe(false);+ expect(zoomMedia.dismiss.cancelTravel).toBeGreaterThan(5);+ expect(zoomMedia.dismiss.cancelTravel).toBeLessThan(20);+ });++ it('dismisses a short flick down: its projected travel reaches the commit point (spec:AST-094 FR36)', () => {+ // An 18 px flick reaches the stage as about 8 pt past the pan's begin+ // threshold. That is short of the commit point, but its velocity carries+ // it on.+ expect(dismissCommits(8, 600)).toBe(true);+ // The same travel lifted still springs back: nothing projects it on.+ expect(dismissCommits(8, 0)).toBe(false);+ // Moving back up cancels, however far it came.+ expect(dismissCommits(8, -600)).toBe(false);+ });++ it('decides the release at the commit point itself, and cancels one moving back toward the start', () => {+ // Exactly at the commit point and held still, the release stays: only+ // past it does a still pull dismiss.+ expect(dismissCommits(zoomMedia.dismiss.cancelTravel, 0)).toBe(false);+ expect(dismissCommits(zoomMedia.dismiss.cancelTravel + 0.01, 0)).toBe(true);+ // Above where the drag began, a release moving down moves back toward+ // the start, so it springs back however fast it moves.+ expect(dismissCommits(-5, 2000)).toBe(false);+ });++ it('sends a dismissed photo below the screen when the stage only hugs it', () => {+ const geometry = landscape();+ const t = dismissTransform(geometry, 0, 100);+ // The screen's bottom 300 px below the stage's.+ const bottom = geometry.height + 300;+ const exit = dismissExitY(geometry, t, bottom);+ expect(geometry.fit.y + exit).toBeGreaterThan(bottom);+ });++ it('sends a dismissed photo below the stage with no thumbnail to return to', () => {+ const geometry = landscape();+ const t = dismissTransform(geometry, 0, 100);+ const exit = dismissExitY(geometry, t);+ expect(geometry.fit.y + exit).toBeGreaterThan(geometry.height);+ expect(exit).toBeGreaterThan(t.y);+ });++ it("lists each spring the dismissal plays in Lightbox's record, with its value", () => {+ // A gesture-driven exit may play a measured spring that its component's+ // motion table lists with its platform source.+ const record = readFileSync(+ resolve(+ __dirname,+ '../../../../docs/specs/components/Lightbox/Lightbox.spec.md',+ ),+ 'utf8',+ ).split('\n');+ const {dismissPositionSpring, dismissSizeSpring} = zoomMedia.dismiss;+ for (const [name, spring] of Object.entries({+ dismissPositionSpring,+ dismissSizeSpring,+ })) {+ const row = record.find(line =>+ line.startsWith(`| \`zoomMedia.dismiss.${name}\``),+ );+ expect(row, name).toBeDefined();+ expect(row).toContain(`stiffness ${spring.stiffness.toFixed(2)}`);+ expect(row).toContain(`damping ${spring.damping.toFixed(2)}`);+ }+ });+});+describe("the keyboard's zoom", () => {const g = landscape();const centre = {x: g.width / 2, y: g.height / 2};diff --git a/packages/core/src/Lightbox/zoomStage.ts b/packages/core/src/Lightbox/zoomStage.tsindex 5e394de443..6bd14c8366 100644--- a/packages/core/src/Lightbox/zoomStage.ts+++ b/packages/core/src/Lightbox/zoomStage.ts@@ -14,6 +14,7 @@* useZoomStage.ts.*/+import {resolveSnapPoint} from '../motion/resolveSnapPoint';import {rubberBandClamp, rubberBandUnclamp} from '../motion/rubberBand';import {zoomMedia} from '../motion/uikit/zoomMedia';@@ -386,3 +387,86 @@ export function transformForResize(scale,});}++// ---------------------------------------------------------------------------+// Drag to dismiss (Photos)++/**+ * The photo under a drag to dismiss, from its fitted size. Its centre follows+ * the pointer (dx, dy). It shrinks about that centre by+ * `zoomMedia.dismiss.scalePerTravelSquared` × the downward travel².+ */+export function dismissTransform(+ geometry: ZoomGeometry,+ dx: number,+ dy: number,+): ZoomTransform {+ const travel = Math.max(0, dy);+ const scale = Math.max(+ 0,+ 1 - zoomMedia.dismiss.scalePerTravelSquared * travel * travel,+ );+ return {+ x: dx + ((1 - scale) * geometry.fit.width) / 2,+ y: dy + ((1 - scale) * geometry.fit.height) / 2,+ scale,+ };+}++/** The backdrop's opacity at a drag's downward travel (pt). */+export function dismissBackdropAlpha(travel: number): number {+ const t = Math.max(0, travel);+ return Math.min(+ 1,+ Math.max(0, 1 - zoomMedia.dismiss.backdropAlphaPerTravelSquared * t * t),+ );+}++/** The controls' and neighbouring photos' opacity at a drag's travel (pt). */+export function dismissChromeAlpha(travel: number): number {+ const {chromeAlphaPerPoint, chromeFadeStart} = zoomMedia.dismiss;+ return Math.min(+ 1,+ Math.max(0, 1 - chromeAlphaPerPoint * (travel - chromeFadeStart)),+ );+}++/**+ * Whether a released drag to dismiss dismisses, decided once at the lift by+ * Core's release rule (`resolveSnapPoint`). The release lands at the fitted+ * place or, past the commit point, gone: their midpoint is+ * `zoomMedia.dismiss.cancelTravel`. It is judged at the travel plus where its+ * velocity would coast (`zoomMedia.dismiss.projectionRate`), and a release+ * moving back toward where the drag began cancels. A short flick down closes;+ * a short pull lifted still springs back.+ */+export function dismissCommits(travel: number, velocityY: number): boolean {+ const {cancelTravel, projectionRate} = zoomMedia.dismiss;+ const release = resolveSnapPoint({+ points: [0, 2 * cancelTravel],+ position: travel,+ velocity: velocityY,+ // No flick rule: the projection alone decides.+ flickThreshold: Number.POSITIVE_INFINITY,+ // The projection that coasts at this deceleration rate.+ projection: {seconds: projectionRate / (1 - projectionRate) / 1000},+ start: 0,+ });+ return release.index === 1;+}++/**+ * Where a dismissed photo goes with no thumbnail to return to: straight on+ * down until its top passes `bottom`, in stage px. That is the screen's+ * bottom edge, which a stage that only hugs the photo sits well above. By+ * default it is the stage's own bottom.+ */+export function dismissExitY(+ geometry: ZoomGeometry,+ shown: ZoomTransform,+ bottom: number = geometry.height,+): number {+ return (+ Math.max(shown.y, Math.max(bottom, geometry.height) - geometry.fit.y) + 1+ );+}diff --git a/packages/core/src/motion/MEASUREMENTS.md b/packages/core/src/motion/MEASUREMENTS.mdindex f4e28921a7..52e044c1fd 100644--- a/packages/core/src/motion/MEASUREMENTS.md+++ b/packages/core/src/motion/MEASUREMENTS.md@@ -349,14 +349,21 @@ Values Lightbox's zoom stage reads (`uikit/zoomMedia.ts`). Done (UIKit lab andPhotos, iOS 26.2 simulator, Oct 23 2026; tagged `measured:`): the overshootpast 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, 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 |-| ----- | ------------ | -------------------------------------------------------------------- | ------------------------------------------------------------------------- | ------ |-| M-ZM2 | Maximum zoom | Photos: pinch a 4032 × 3024 and a 1200 × 800 photo as far as it goes | the zoom it settles on against the photo's pixel size and the fitted size | B, C |+tap and its maximum zoom on 3000 × 2000 and 2000 × 3000 photos, the 40 pt gap+between Photos' pages, and its drag-to-dismiss: the shrink and fades by+travel, the release rule and the dismissal's springs. M-ZM2 confirms that+maximum on two other sizes. M-ZM3 measures the cancel distance and M-ZM5 the+release's projection. 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). Photos returns+a cancelled drag on critically damped springs (stiffness 877.63 for its+position, 955.23 for its size). Lightbox's return plays `springs.settle`,+since only an exit may play a measured spring (`spec:AST-094` FR4).++| ID | What | App and gesture | Extract | Method |+| ----- | ------------------------ | -------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ------ |+| M-ZM2 | Maximum zoom | Photos: pinch a 4032 × 3024 and a 1200 × 800 photo as far as it goes | the zoom it settles on against the photo's pixel size and the fitted size | B, C |+| M-ZM3 | Dismiss cancel distance | Photos: pull a photo down 6–19 pt, bring it back to N pt and lift without moving | the largest N that still cancels | B, C |+| M-ZM5 | Dismiss flick projection | Photos: flick a photo down from rest, lifting after 6–19 pt at a range of speeds | the shortest travel that still dismisses at each speed: the projection's rate | B, C |diff --git a/packages/core/src/motion/uikit/zoomMedia.ts b/packages/core/src/motion/uikit/zoomMedia.tsindex 1adc275fbf..8bc5c93ca8 100644--- a/packages/core/src/motion/uikit/zoomMedia.ts+++ b/packages/core/src/motion/uikit/zoomMedia.ts@@ -3,9 +3,9 @@/*** @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, maximum zoom- * and gap between pages+ * @output Exports `zoomMedia`: UIScrollView zooming in a photo viewer. It+ * holds the give past the zoom limits, and Photos' double tap, maximum+ * zoom, page gap and drag to dismiss* @position A domain of the UIKit constants table (motion/uikit). Lightbox's* zoom stage reads it*@@ -79,4 +79,75 @@ export const zoomMedia = {*/pageGap: 40,},+ dismiss: {+ /**+ * While a photo at its fitted size is dragged down, its centre follows+ * the finger. It shrinks about that centre by 1 − k·d², where d is the+ * drag's downward travel in pt. It gives 0.997 / 0.978 / 0.942 / 0.899 at+ * 25 / 65 / 105 / 145 pt, with k the least-squares fit, within 0.004.+ * @source measured: Photos, iOS 26.2 simulator, iPhone 17 Pro, a 3000 ×+ * 2000 photo at its fitted size dragged down 25–145 pt, the zoom+ * view's bounds per frame, Oct 24 2026+ */+ scalePerTravelSquared: 4.91e-6,+ /**+ * The viewer's backdrop fades by 1 − k·d²: 1.0 / 0.95 / 0.86 / 0.71 at+ * 25 / 65 / 105 / 145 pt (k the least-squares fit, within 0.009).+ * @source measured: Photos, iOS 26.2 simulator, iPhone 17 Pro, the same+ * drags, the backdrop view's alpha per frame, Oct 24 2026+ */+ backdropAlphaPerTravelSquared: 1.35e-5,+ /**+ * The neighbouring photos and the controls fade faster, linearly once+ * the drag passes `chromeFadeStart`: 1 − k·(d − start). It gives 0.96 /+ * 0.76 / 0.52 / 0.33 at 25 / 65 / 105 / 145 pt, fitted within 0.016.+ * @source measured: Photos, iOS 26.2 simulator, iPhone 17 Pro, the same+ * drags, the neighbouring pages' and the chrome's alpha per frame,+ * Oct 24 2026+ */+ chromeAlphaPerPoint: 0.00533,+ /**+ * Travel, pt, before the controls start to fade (see+ * `chromeAlphaPerPoint`).+ * @source measured: Photos, iOS 26.2 simulator, iPhone 17 Pro, the+ * intercept of the same fit, Oct 24 2026+ */+ chromeFadeStart: 17.8,+ /**+ * The commit point. A release whose projected travel (`projectionRate`)+ * stays within this distance of where the drag started cancels, as a+ * release moving up does. Any other release dismisses, however short the+ * pull. Pulls of 20, 40 and 60 pt held still, then lifted, dismiss. A pull+ * brought back to about 5 pt cancels.+ * @source GUESS — between the measured 5 pt (cancels) and 20 pt+ * (dismisses); Photos, iOS 26.2 simulator, Oct 24 2026+ * @measure M-ZM3+ */+ cancelTravel: 10,+ /**+ * The deceleration rate that projects a release's travel. The drag+ * dismisses when its travel plus where its velocity would coast passes+ * `cancelTravel`, so a short flick down closes.+ * @source GUESS — UIScrollView's normal deceleration rate, the WWDC18+ * projection's default; Photos' own projection is not measured+ * @measure M-ZM5+ */+ projectionRate: 0.998,+ /**+ * The dismissal's position spring (critically damped, response about+ * 0.21 s): the photo leaves along it.+ * @source measured: Photos, iOS 26.2 simulator, iPhone 17 Pro, a+ * committed drag-to-dismiss, the zoom view's position animation+ * (`CASpringAnimation` mass 1, stiffness 918.09, damping 60.60),+ * Oct 24 2026+ */+ dismissPositionSpring: {mass: 1, stiffness: 918.09, damping: 60.6},+ /**+ * The dismissal's spring for size and opacity (critically damped).+ * @source measured: Photos, iOS 26.2 simulator, iPhone 17 Pro, the same+ * dismissal, the bounds and opacity animations (stiffness 947.14,+ * damping 61.55), Oct 24 2026+ */+ dismissSizeSpring: {mass: 1, stiffness: 947.14, damping: 61.55},+ },} as const;