diff --git a/.changeset/lightbox-single-caption-backing.md b/.changeset/lightbox-single-caption-backing.md new file mode 100644 index 0000000000000..f4f321442d3ab --- /dev/null +++ b/.changeset/lightbox-single-caption-backing.md @@ -0,0 +1,7 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] A single photo's caption in a `Lightbox` now shows as a gallery's does. It sits in the band at the bottom of the viewer, on the caption's backing, which keeps 4.5:1 over any page behind it. The photo centres above it. A caption longer than two lines ends in "more", which opens it in full over the photo. A single photo with no caption shows no band. + +@vjeux diff --git a/apps/storybook/stories/Lightbox.stories.tsx b/apps/storybook/stories/Lightbox.stories.tsx index 22d8267f47ee2..0411451347b14 100644 --- a/apps/storybook/stories/Lightbox.stories.tsx +++ b/apps/storybook/stories/Lightbox.stories.tsx @@ -128,7 +128,7 @@ export const WithZoom: Story = { }, }; -/** Zoom on a photo with a caption, which sits under the fitted photo. */ +/** Zoom on a photo with a caption, in the caption band a gallery's pages use. */ export const ZoomWithCaption: Story = { render: () => { const [isOpen, setIsOpen] = useState(false); @@ -241,6 +241,33 @@ export const GalleryKeepsIndex: Story = { }, }; +/** + * A single photo whose caption runs long. As on a gallery's page, two lines + * cut it short and "more" shows it all. + */ +export const SingleWithLongCaption: Story = { + render: () => { + const [isOpen, setIsOpen] = useState(false); + return ( + <> + + + + ); + }, +}; + export const WithCaption: Story = { render: () => { const [isOpen, setIsOpen] = useState(false); diff --git a/docs/specs/components/Lightbox/Lightbox.spec.md b/docs/specs/components/Lightbox/Lightbox.spec.md index 9c3bc3a117aec..64e9028f1e985 100644 --- a/docs/specs/components/Lightbox/Lightbox.spec.md +++ b/docs/specs/components/Lightbox/Lightbox.spec.md @@ -89,9 +89,6 @@ the requirement it misses and the person it affects. - **Video controls (FR7).** A video's native controls are taken as a 48 px band at its bottom edge, since browsers expose no control geometry; a browser that places controls elsewhere pages from them. -- **Single photo's caption contrast (FR19).** A single photo's caption has no - backing. Its white text over the backdrop measures 4.00:1 over a white - page, under FR19's 4.5:1, so a low-vision reader can lose it there. - **Zoom announcement (AR4).** A zoom change announces "zoomed in" or "zoomed out" without the zoom level. - **Fine-pointer gestures (FR11).** FR11's drag paging (FR7) and drag to @@ -99,6 +96,7 @@ the requirement it misses and the person it affects. fitted photo does nothing. On a desktop, a click in the viewer outside the photo and a band holding a caption closes it. Implementation gap: beside a photo scaled down to fit, a click within the band as wide as the photo's natural width stays open. + With zoom, a double-click on a caption zooms the photo, and a mouse does not select the caption's text, for one photo or a gallery. - **Double-click listener (FR14).** A mouse's or a pen's double-click reaches the zoom through the stage's own `dblclick` listener, since only the browser knows the system's double-click speed. @@ -140,6 +138,7 @@ FR21). Consumer props and usage remain documented in `Lightbox.doc.mjs`. | ID | Candidate invariant | Basis | Draft review state | | ---- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | --------------------------- | | FR1 | The viewer contains one active Media item and a Close button; galleries additionally contain Previous and Next buttons plus a Counter, and Caption renders only when supplied. In a gallery with any caption, every page keeps a band two caption lines tall under its Media, with the caption's backing only where the page has a caption. A longer caption's second line ends in a "more" action that opens it in full over the bottom of the Media, on a scrim. The full caption is always the viewer's accessible description. The caption band uses Astryx parts: the caption text is `Text` with the body type, not a hand-styled element. The caption's more/less toggle is an inline link-styled action that flows with the caption text (component:Link's button form), with aria-expanded and aria-controls. | Current source, docs, and tests | settled | +| FR1b | A single captioned item, a photo or a video, and a gallery present the caption the same way: the same plate, width, text treatment, inline "more", spacing and photo position, and no plate when there is no caption. (Owner direction, Nov 6 2026 (Cindy): the single-photo caption behaved differently from the gallery's, and "they really should be consistent".) Exceptions: a single photo has no Previous or Next button, no Counter and no paging, since there is no other item; and a drag past a zoomed single photo's edge rubber-bands and returns (FR6), where a gallery's touch pager takes it (FR7). | Owner direction, Nov 6 2026 | settled | | 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 | @@ -157,7 +156,7 @@ FR21). Consumer props and usage remain documented in `Lightbox.doc.mjs`. | FR16 | Under a coarse primary pointer, a close that is not a drag down (FR8), a pinch in (FR9), or a return into a source (FR12) plays the touch exit: Close, Escape, a platform close, and a tap beside the photo while the controls are shown (ORD3). The photo shrinks a little and fades out in place with the backdrop and controls, as the native viewer's zoom transition does without a source, on a spring from rest, `springs.settle` unless the motion table names another role, with the backdrop and controls fading on its pace (`spec:AST-094` FR7, FR45). `onOpenChange(false)` reports at the request, and the viewer takes no input while the exit plays. Under a fine pointer the viewer closes at once (FR11). | `spec:AST-094` FR7 | settled; implementation gap | | FR17 | For any `index`, controlled or default, the viewer opens on the nearest valid item: below 0 the first, past the last the last. A fraction rounds to the nearest item, and NaN opens the first. | 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 | -| FR19 | The viewer is a media surface: it renders inside `MediaTheme` (dark), so its controls and caption take the theme's dark surface tokens and the active theme's component rules (`architecture:theme-application` INV8), with no Lightbox-owned colors beyond AR9's backing, the caption's backing and the on-dark color. | Specs decision, Nov 5 2026 | settled; implementation gap | +| FR19 | The viewer is a media surface: it renders inside `MediaTheme` (dark), so its controls and caption take the theme's dark surface tokens and the active theme's component rules (`architecture:theme-application` INV8), with no Lightbox-owned colors beyond AR9's backing, the caption's backing and the on-dark color. | Specs decision, Nov 5 2026 | settled | ### Motion @@ -191,7 +190,7 @@ return included, plays `springs.settle`. | Single image | Viewer overlay, Media, and Close button render. | Caption and zoom may be absent or present. | | Gallery boundary | Both navigation buttons and Counter remain rendered. | Previous or Next is disabled at its boundary. | | Video | Media renders native video controls without image zoom interaction. | Autoplay follows the existing consumer prop. | -| Captioned media | Caption follows the active Media inside the centered media group. | Caption content remains caller-provided. | +| Captioned media | Caption shows in the band under the active Media's page, for one item or a gallery. | Caption content remains caller-provided. | | Zoomed image | A double tap or double-click, `-`, or `0` returns to the fitted size. | The zoom level and pan position. | | Controls hidden | Controls stay focusable and in the accessibility tree; focus or a key brings them back. | Backdrop shade while hidden. | @@ -349,6 +348,7 @@ a decision that they must remain unthemeable. | Contract | Verification | Representative states | Mutation or failure expectation | Audit section | | ------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ | | FR1 | `Lightbox.test.tsx` render, gallery, caption, media, and zoom suites; the `LightboxViewport` caption band cases | Single image, gallery edges, caption, video | Removing a documented part fails existing role, content, media, or navigation assertions. | `audit:Lightbox/anatomy` | +| FR1b | `Lightbox.test.tsx` single photo cases; `LightboxSingleCaption` interaction specs, Chromium and WebKit, on a phone and a desktop | A single photo with a caption, with zoom, with a long caption and with none, against a gallery page | A single photo whose band, caption text or photo box differs from a gallery page's, a long single caption without "more", a band without a caption, or a Previous, Next or Counter on a single photo fails. | `audit:Lightbox/anatomy` | | FR2 | Source inspection and `themingTargets.test.ts` | Viewer overlay, Media, Caption, and Counter | Removing the root target or documenting an unshipped child target fails evidence or inventory. | `audit:Lightbox/theming` | | FR3 | Source inspection plus Button and IconButton public composition | Close and gallery navigation controls | Re-owning a control surface requires the delegated owner and this map to change. | `audit:Lightbox/theming` | | FR4, AR3 | Browser keyboard test: Tab and Shift+Tab at both ends, Escape, arrows in LTR and RTL, `+`, `-`, `0`, close focus | Single image, gallery, zoomed image, removed opener | Focus leaving the viewer, a key without its action, or focus not returning to a connected opener fails. | `audit:Lightbox/accessibility` | diff --git a/packages/core/locales/en.json b/packages/core/locales/en.json index 3a29a82f4ded5..7f60049ed6fd7 100644 --- a/packages/core/locales/en.json +++ b/packages/core/locales/en.json @@ -1697,11 +1697,11 @@ }, "@astryx.lightbox.captionMore": { "defaultMessage": "more", - "description": "Visible label of the button after a gallery caption that two lines cut short in a Lightbox. It opens the full caption over the photo. Pairs with `lightbox.captionLess`." + "description": "Visible label of the button after a Lightbox caption that two lines cut short, for a single photo or a gallery. It opens the full caption over the photo. Pairs with `lightbox.captionLess`." }, "@astryx.lightbox.captionLess": { "defaultMessage": "less", - "description": "Visible label of the same button while a Lightbox gallery's full caption is open over the photo. It closes the full caption. Pairs with `lightbox.captionMore`." + "description": "Visible label of the same button while a Lightbox caption is open in full over the photo. It closes the full caption. Pairs with `lightbox.captionMore`." }, "@astryx.metadataList.showMore": { "defaultMessage": "Show more", diff --git a/packages/core/src/Lightbox/Lightbox.doc.mjs b/packages/core/src/Lightbox/Lightbox.doc.mjs index bb3ebe1f27fd8..27a5512e36f8f 100644 --- a/packages/core/src/Lightbox/Lightbox.doc.mjs +++ b/packages/core/src/Lightbox/Lightbox.doc.mjs @@ -32,7 +32,7 @@ const anatomy = [ name: 'Caption', required: false, description: - 'Caller-provided caption displayed below the active media. In a gallery it shows at most two lines; a longer caption ends in an inline "more" link that opens it in full over the photo.', + 'Caller-provided caption displayed below the active media, in a band at the bottom of the viewer. It shows at most two lines, for a single photo as for a gallery; a longer caption ends in an inline "more" link that opens it in full over the photo.', }, { name: 'Counter', diff --git a/packages/core/src/Lightbox/Lightbox.test.tsx b/packages/core/src/Lightbox/Lightbox.test.tsx index c1561f296d34d..193904aaeb123 100644 --- a/packages/core/src/Lightbox/Lightbox.test.tsx +++ b/packages/core/src/Lightbox/Lightbox.test.tsx @@ -1757,6 +1757,73 @@ describe('Lightbox', () => { }); }); + describe('a single photo', () => { + it("renders as a gallery's page: its photo's box, then its caption in the band below", () => { + render( + {}} + media={{src: '/photo.jpg', alt: 'Photo', caption: 'A caption'}} + />, + ); + const pages = document.querySelectorAll('[data-lightbox-page]'); + expect(pages).toHaveLength(1); + const page = pages[0]; + expect(page).toHaveAttribute('data-current'); + const media = page.querySelector('[data-lightbox-page-media]')!; + expect(media).toContainElement(screen.getByAltText('Photo')); + const caption = page.querySelector( + '[data-lightbox-caption]', + )!; + expect(caption).toHaveTextContent('A caption'); + expect(media.nextElementSibling).toContainElement(caption); + // Nothing to page to: no Previous, Next or counter. + expect(screen.queryByRole('button', {name: 'Previous'})).toBeNull(); + expect(screen.queryByRole('button', {name: 'Next'})).toBeNull(); + expect(screen.queryByText('1 / 1')).toBeNull(); + }); + + it("gives a single captioned video a gallery page's box and band, and its caption describes the viewer", () => { + render( + {}} + media={{ + src: '/clip.mp4', + alt: 'A clip', + type: 'video', + caption: 'A caption', + }} + />, + ); + const page = document.querySelector('[data-lightbox-page]')!; + expect(page).toHaveAttribute('data-current'); + const media = page.querySelector('[data-lightbox-page-media]')!; + expect(media.querySelector('video')).toHaveAttribute('src', '/clip.mp4'); + const caption = page.querySelector( + '[data-lightbox-caption]', + )!; + expect(caption).toHaveTextContent('A caption'); + expect(media.nextElementSibling).toContainElement(caption); + expect(screen.getByRole('dialog')).toHaveAccessibleDescription( + 'A caption', + ); + }); + + it('with no caption has no band, as a gallery with none', () => { + render( + {}} + media={{src: '/photo.jpg', alt: 'Photo'}} + />, + ); + const page = document.querySelector('[data-lightbox-page]')!; + expect(page.children).toHaveLength(1); + expect(page.querySelector('[data-lightbox-caption]')).toBeNull(); + }); + }); + it('does not crash with an empty media array', () => { const {container} = render( {}} media={[]} />, @@ -1765,7 +1832,7 @@ describe('Lightbox', () => { }); describe('backdrop dismiss', () => { - it('closes on a click on the strip a raised caption leaves below the stage', () => { + it("closes on a mouse click above a single photo, as on a gallery's page", () => { const onOpenChange = vi.fn(); render( { hasZoom />, ); - // The media group: the stage, then the caption's place below it. A - // mouse's click there is below the raised caption. - const group = screen.getByText('A caption').parentElement!; - fireEvent.click(group, {detail: 1, clientY: 590}); + // The stage centres the 200 px photo in its 600 px box. + const current = document.querySelector('[data-current]')!; + mousePress(current.querySelector('[data-lightbox-page-media]')!, { + x: 200, + y: 20, + }); expect(onOpenChange).toHaveBeenCalledWith(false); }); - it('without zoom, leaves a click beside a narrower caption alone', () => { + it("without zoom, leaves a mouse click on a single photo's caption alone", () => { const onOpenChange = vi.fn(); render( { media={{src: '/photo.jpg', alt: 'Photo', caption: 'A caption'}} />, ); - // The media group hugs its media and caption, as before. - fireEvent.click(screen.getByText('A caption').parentElement!); + const current = document.querySelector('[data-current]')!; + layOutPage(current, { + photo: rectAt(100, 200, 200, 200), + natural: 200, + caption: rectAt(50, 560, 300, 40), + viewer: 400, + }); + mousePress(current.querySelector('[data-lightbox-caption]')!, { + x: 200, + y: 580, + }); expect(onOpenChange).not.toHaveBeenCalled(); }); @@ -2048,9 +2126,12 @@ describe('Lightbox gestures for a mouse and a pen (spec:AST-094 FR43)', () => { await act(async () => { await new Promise(resolve => setTimeout(resolve, 400)); }); - // Each caption click reads its own press, not the drag's. + // Each caption click reads its own press, not the drag's. The caption + // sits in its band, on the stage's surface, so its presses are timed as a + // browser times them: now. const caption = screen.getByText('A caption'); - for (const at of [t0 + 1000, t0 + 2000]) { + for (let i = 0; i < 2; i++) { + const at = performance.now(); pointer('pointerdown', caption, 'mouse', 200, 300, at); pointer('pointerup', caption, 'mouse', 200, 300, at + 40); fireEvent.click(caption, {clientX: 200, clientY: 300, detail: 1}); @@ -2138,12 +2219,12 @@ describe('Lightbox gestures for a mouse and a pen (spec:AST-094 FR43)', () => { pointer('pointerup', stage, 'mouse', 180, 300, t0 + 32); fireEvent.click(stage, {clientX: 180, clientY: 300, detail: 1}); expect(onOpenChange).not.toHaveBeenCalled(); - // A new press on the dark area above starts a new click, which closes. - const container = - screen.getByText('A caption').parentElement!.parentElement!; - pointer('pointerdown', container, 'mouse', 200, 10, t0 + 1000); - pointer('pointerup', container, 'mouse', 200, 10, t0 + 1040); - fireEvent.click(container, {clientX: 200, clientY: 10, detail: 1}); + // A new press on the dark area above, on the stage, starts a new click, + // which closes. It is timed as a browser times it: now. + const later = performance.now(); + pointer('pointerdown', stage, 'mouse', 200, 10, later); + pointer('pointerup', stage, 'mouse', 200, 10, later + 40); + fireEvent.click(stage, {clientX: 200, clientY: 10, detail: 1}); expect(onOpenChange).toHaveBeenCalledWith(false); }); }); @@ -2207,6 +2288,7 @@ describe('Lightbox recognizers attach for every pointer (spec:AST-094 FR43)', () } it('attaches no drag to dismiss where the primary pointer is fine', () => { + // Only the backdrop's tap beside the photo, as on a gallery's page. expect( lightboxRecognizersAttached(() => { render( @@ -2217,7 +2299,7 @@ describe('Lightbox recognizers attach for every pointer (spec:AST-094 FR43)', () />, ); }), - ).toEqual([]); + ).toEqual(['lightbox-backdrop-tap']); }); it('attaches the drag to dismiss under the touch layer', () => { @@ -2301,24 +2383,6 @@ describe('Lightbox touch zoom (synthetic touches)', () => { }); } - /** A finger's pointerdown, which a browser sends before its touchstart. */ - function fingerDown(target: Element, x: number, y: number): void { - const event = new Event('pointerdown', {bubbles: true, cancelable: true}); - const fields = {pointerType: 'touch', pointerId: 2, isPrimary: true}; - for (const [key, value] of Object.entries({ - ...fields, - button: 0, - buttons: 1, - clientX: x, - clientY: y, - })) { - Object.defineProperty(event, key, {value}); - } - act(() => { - target.dispatchEvent(event); - }); - } - it('reports a tap beside the photo to the newest onOpenChange', async () => { // The stage's gestures read the props of the latest render, so a parent's // new callback is the one a tap beside the photo reaches. @@ -2346,7 +2410,7 @@ describe('Lightbox touch zoom (synthetic touches)', () => { ['a fitted photo', false], ['a zoomed photo', true], ])( - 'closes on a finger’s tap on the strip after a finger drag on %s, once the drag’s flag is clear', + 'closes on a finger’s tap beside the photo after a finger drag on %s', async (_, isZoomedFirst) => { const onOpenChange = vi.fn(); render( @@ -2372,17 +2436,13 @@ describe('Lightbox touch zoom (synthetic touches)', () => { touch('touchmove', stage, [finger], [finger], 1000 + i * 16); } touch('touchend', stage, [], [finger], 1000 + 7 * 16); - const group = screen.getByText('A caption').parentElement!; - const tapStrip = () => { - fingerDown(group, 200, 590); - fireEvent.click(group, {clientX: 200, clientY: 590, detail: 1}); - }; - // A zoomed drag's flag takes the first tap. A fitted photo's drag starts - // no zoom pan, since paging owns it, so it leaves no flag. - tapStrip(); - expect(onOpenChange).toHaveBeenCalledTimes(isZoomedFirst ? 0 : 1); - tapStrip(); - expect(onOpenChange).toHaveBeenCalledWith(false); + // Above the photo, on the stage: its own tap closes the viewer, as on a + // gallery's page. The drag leaves nothing in its way. + const tap: Contact = {id: 7, x: 200, y: 50}; + touch('touchstart', stage, [tap], [tap], 2000); + touch('touchend', stage, [], [tap], 2040); + // A single tap waits out a double tap's interval. + await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false)); }, ); @@ -2425,7 +2485,7 @@ describe('Lightbox touch zoom (synthetic touches)', () => { touch('touchend', stage, [], [a], 20 * 16); }); - it("takes a caption off the photo from a pinch's first move", () => { + it('keeps a single photo’s caption in its band, outside the photo’s box, through a pinch', () => { render( { />, ); const stage = screen.getByRole('button', {name: 'Zoom'}); - const caption = screen.getByText('A caption'); - // Fitted, the caption is raised by the stage's free space below the - // photo: (600 - 200) / 2. - expect(caption.style.translate).toBe('0 -200px'); + const caption = stage.parentElement!.querySelector( + '[data-lightbox-caption]', + )!; + // The band is the page's row below the photo's box, as on a gallery's. + expect(stage).not.toContainElement(caption); + expect(caption.style.translate).toBe(''); let a: Contact = {id: 1, x: 150, y: 300}; let b: Contact = {id: 2, x: 250, y: 300}; touch('touchstart', stage, [a], [a], 0); @@ -2448,10 +2510,12 @@ describe('Lightbox touch zoom (synthetic touches)', () => { b = {...b, x: 250 + 6 * i}; touch('touchmove', stage, [a, b], [a, b], i * 16); } - // Both fingers are still down, and the photo spreads over the stage. + // Both fingers are still down, and the photo spreads over the stage. The + // caption stays in its band, unmoved. expect( parseFloat(photoTransform(screen.getByAltText('Photo')).scale), ).toBeGreaterThan(1); + expect(stage).not.toContainElement(caption); expect(caption.style.translate).toBe(''); touch('touchend', stage, [a], [b], 5 * 16); touch('touchend', stage, [], [a], 6 * 16); @@ -2573,7 +2637,7 @@ describe('Lightbox touch zoom (synthetic touches)', () => { expect(onOpenChange).not.toHaveBeenCalled(); }); - it('ignores the first tap on the strip after a drag to close springs back, as before', async () => { + it('closes on a finger’s tap beside the photo after a drag to close springs back', async () => { const onOpenChange = vi.fn(); render( { 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); + // Above the photo, on the stage: its own tap closes the viewer, as on a + // gallery's page. The drag leaves nothing in its way. The tap is timed as + // a browser times it: now. + const tap: Contact = {id: 7, x: 200, y: 50}; + const now = performance.now(); + touch('touchstart', stage, [tap], [tap], now); + touch('touchend', stage, [], [tap], now + 40); + // A single tap waits out a double tap's interval. + await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false)); }); }); diff --git a/packages/core/src/Lightbox/Lightbox.tsx b/packages/core/src/Lightbox/Lightbox.tsx index ab32c92b73a08..a629e25ae9c94 100644 --- a/packages/core/src/Lightbox/Lightbox.tsx +++ b/packages/core/src/Lightbox/Lightbox.tsx @@ -53,10 +53,7 @@ import {announceInModal} from '../hooks/useAnnounce'; import {useScrollLock} from '../hooks/useScrollLock'; import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect'; import {useAttachment} from '../hooks/useAttachment'; -import { - observeResize, - observeResizeAfterLayout, -} from '../utils/sharedResizeObserver'; +import {observeResizeAfterLayout} from '../utils/sharedResizeObserver'; import {useTouchHitArea} from '../utils/touchHitArea'; import {touchHitAreaStyles} from '../internal/touchHitArea.stylex'; import {usePressTracker} from '../gestures/usePressTracker'; @@ -228,31 +225,21 @@ const styles = stylex.create({ height: '100%', position: 'relative', }, + // The stage is the pager's viewport, a single photo's too. It fills the + // viewer on every presentation, so its pages have a size of their own. mediaGroup: { display: 'flex', flexDirection: 'column', alignItems: 'center', + alignSelf: 'stretch', + flexGrow: 1, + minHeight: 0, maxWidth: '100%', maxHeight: '100%', // 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, - // and a pinch can start anywhere around it. Only a zoom target does this: - // around any other item, a tap on the dark area still closes the viewer. - mediaGroupZoom: { - alignSelf: 'stretch', - flexGrow: 1, - minHeight: 0, - }, - imageWrapperFill: { - alignSelf: 'stretch', - flexGrow: 1, - flexShrink: 1, - flexBasis: 0, - }, // The zoom button's box clips, so its focus ring sits inside its edge. zoomButtonFocusInset: { outlineOffset: { @@ -264,31 +251,27 @@ const styles = stylex.create({ display: 'flex', alignItems: 'center', justifyContent: 'center', - // 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}, + alignSelf: 'stretch', + flexGrow: 1, + flexShrink: 1, + flexBasis: 0, + position: 'relative', + // ZOOM_DISMISSING_ATTRIBUTE on the current page's photo box: a photo + // dragged to dismiss draws outside the stage. + overflow: {default: 'hidden', ':has([data-zoom-dismissing])': 'visible'}, cursor: 'default', userSelect: 'none', minHeight: 0, }, - // The stage's own pinch, pan and double tap take every touch on it, - // whatever the primary pointer. Only the stage does: the controls and - // caption leave pinch-zoom to the page. It fills the viewer (mediaGroupZoom, - // imageWrapperFill). - imageWrapperZoomTarget: { - touchAction: 'none', + // 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', }, - // In a gallery the photo rows take the stage's touches, for every pointer - // (as imageWrapperZoomTarget). A descendant cannot allow what an ancestor's - // `touch-action` rules out. So the track allows only the page's pinch-zoom, - // and a pinch on a caption still zooms the page. The pager's pan manages the + // The photo rows take the stage's own pinch, pan and double tap, for every + // pointer. A descendant cannot allow what an ancestor's `touch-action` rules + // out. So the track allows only the page's pinch-zoom, and a pinch on the + // controls or a caption still zooms the page. The pager's pan manages the // stage's own `touch-action`. trackZoomTarget: { touchAction: 'pinch-zoom', @@ -302,25 +285,6 @@ const styles = stylex.create({ ':is(:disabled,[aria-disabled="true"])': 'default', }, }, - // 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: { - alignSelf: 'stretch', - flexGrow: 1, - minHeight: 0, - }, - imageWrapperGallery: { - alignSelf: 'stretch', - flexGrow: 1, - flexShrink: 1, - flexBasis: 0, - position: 'relative', - }, // Two rows that every page shares through subgrid: the photo's and the // caption band's. The band has one height on every page (`captionBand`). So // every photo centres on the same box, with or without a caption. The next @@ -357,7 +321,9 @@ const styles = stylex.create({ display: 'flex', alignItems: 'center', justifyContent: 'center', - // As the single item's stage, while a photo is dragged to dismiss. + // ZOOM_DISMISSING_ATTRIBUTE: a photo dragged to dismiss draws outside its + // box, above its caption band and below the controls. The drag fades the + // band, which makes it a stacking context painted after the box. overflow: {default: 'hidden', ':is([data-zoom-dismissing])': 'visible'}, zIndex: {default: null, ':is([data-zoom-dismissing])': 1}, }, @@ -568,7 +534,7 @@ const styles = stylex.create({ // 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 + // writes their opacity, each is a stacking context. The track's positioned // pages, later in tree order, would otherwise cover them and take the taps // meant for the controls. chromeLayer: { @@ -694,6 +660,7 @@ export function Lightbox({ const containerRef = useRef(null); const imageWrapperRef = useRef(null); const trackRef = useRef(null); + const noPagerTrackRef = useRef(null); // A gallery's zoom stage: the current page's photo box. const pageMediaRef = useRef(null); const triggerElementRef = useRef(null); @@ -723,6 +690,8 @@ export function Lightbox({ () => (Array.isArray(media) ? media : [media]), [media], ); + // Every item is a page of the track, a single photo too, so its photo and + // caption sit as a gallery page's do. Only paging needs more than one item. const isGallery = mediaArray.length > 1; // The item shown is current in every respect: its page, the counter, the // pager and the announcement. @@ -938,16 +907,13 @@ export function Lightbox({ const pointerTypeRef = useRef(''); // Where the last press on the media started, which a click does not carry. const pressPointRef = useRef<{x: number; y: number} | null>(null); - // Without zoom, a click on the dark area lands on the container or the - // dialog, and both close. A finger's tap on a gallery's stage, or on the - // zoom stage beside the photo, closes on the stage's own tap. So does its - // tap on the media group's strip below a single photo's stage. A mouse's or - // a pen's click closes only outside the media (`isClickOutsideMedia`). A - // zoomed drag sets `didDragRef`, so its click is ignored. The next press - // clears the flag, and a finger's only on the stage. + // The stage fills the viewer. A finger's tap on it beside the media closes + // on a tap of its own: the zoom stage's, or the backdrop tap without zoom. + // A mouse's or a pen's click closes only outside the media + // (`isClickOutsideMedia`). A zoomed drag sets `didDragRef`, so its click is + // ignored. The next press clears the flag, and a finger's only on the stage. const didDragRef = useRef(false); const mediaGroupRef = useRef(null); - const captionRef = useRef(null); // The current item's caption, which is the viewer's accessible description. const captionId = useId(); const fullCaptionId = useId(); @@ -1182,16 +1148,15 @@ export function Lightbox({ null, ); // Whether a mouse's or a pen's click on the media closes the viewer. It - // does when its press or its release lands outside the media: a single - // item's, or a gallery's current page's. The media runs from the fitted - // photo's top to the caption's bottom. It is as wide as the photo's - // natural width or the caption, up to the viewer's. While zoomed, the - // photo's shown box is media too. + // does when its press or its release lands outside the current page's + // media. That is the fitted photo's rows, as wide as the photo's natural + // width or the caption, up to the viewer's, and the caption's own box. + // While zoomed, the photo's shown box is media too. const isClickOutsideMedia = useCallback((e: ReactMouseEvent) => { const viewer = imageWrapperRef.current; - const page = viewer?.querySelector('[data-current]') ?? viewer; + const page = viewer?.querySelector('[data-current]'); const media = page?.querySelector('img') ?? page?.querySelector('video'); - // The photo's own box, which centres it: the stage, or a page's. + // The page's photo box, which centres the photo. const box = media?.parentElement; const group = mediaGroupRef.current; if ( @@ -1210,16 +1175,8 @@ export function Lightbox({ const space = (box.clientHeight - media.offsetHeight) / 2; const boxRect = box.getBoundingClientRect(); const top = boxRect.top + space; - let bottom = top + media.offsetHeight; - const caption = - page === viewer - ? captionRef.current - : page.querySelector('[data-lightbox-caption]'); - if (caption != null) { - // The caption's place under the fitted photo, also while zoomed. - const lift = caption.style.translate === '' ? space : 0; - bottom = Math.max(bottom, caption.getBoundingClientRect().bottom - lift); - } + const bottom = top + media.offsetHeight; + const caption = page.querySelector('[data-lightbox-caption]'); const natural = media instanceof HTMLImageElement ? media.naturalWidth : media.videoWidth; const width = Math.min( @@ -1228,14 +1185,12 @@ export function Lightbox({ ); const middle = boxRect.left + box.clientWidth / 2; const shown = media.getBoundingClientRect(); - // A gallery's caption band can sit apart from the photo. There the media - // is the photo's rows, the band and the caption's own box, which an open - // caption lifts over the photo. So the space between the photo and the - // band is outside it. - const captionBox = - page === viewer ? null : caption?.getBoundingClientRect(); - const bandBox = - page === viewer ? null : caption?.parentElement?.getBoundingClientRect(); + // The caption band can sit apart from the photo. There the media is the + // photo's rows, the band and the caption's own box, which an open caption + // lifts over the photo. So the space between the photo and the band is + // outside it. + const captionBox = caption?.getBoundingClientRect(); + const bandBox = caption?.parentElement?.getBoundingClientRect(); const isOutside = ({x, y}: {x: number; y: number}) => { const isOnShownPhoto = x >= shown.left && @@ -1278,9 +1233,7 @@ export function Lightbox({ return; } const isMediaClose = - pointerTypeRef.current === 'touch' - ? hasZoom && !isVideo && e.target === mediaGroupRef.current - : (isGallery || (hasZoom && !isVideo)) && isClickOutsideMedia(e); + pointerTypeRef.current !== 'touch' && isClickOutsideMedia(e); if ( e.target === e.currentTarget || e.target === containerRef.current || @@ -1289,7 +1242,7 @@ export function Lightbox({ handleClose(); } }, - [handleClose, hasZoom, isVideo, isGallery, isClickOutsideMedia], + [handleClose, isClickOutsideMedia], ); const isZoomTarget = hasZoom && !isVideo; @@ -1326,49 +1279,14 @@ export function Lightbox({ chrome: chrome.map(element => animatorFor(element)), }; }, []); - const onDragStart = () => { didDragRef.current = true; }; - // With zoom the stage fills the viewer, so a caption would sit at the - // viewer's bottom. It moves up by the stage's space below the fitted - // photo, so it sits under the photo as it does without zoom. The stage - // already leaves the caption its height. A photo shown larger than it fits - // fills the stage, from a gesture's first move until a settle back lands. - // Meanwhile the caption goes back to its own place below the stage. - const isShownAtFitRef = useRef(true); - const placeCaption = useCallback(() => { - const caption = captionRef.current; - if (caption == null) { - return; - } - const stageElement = imageWrapperRef.current; - const photo = stageElement?.querySelector('img'); - // The photo's laid-out height, not its zoomed box. - const below = - isZoomTarget && - isShownAtFitRef.current && - stageElement != null && - photo != null - ? (stageElement.clientHeight - photo.offsetHeight) / 2 - : 0; - caption.style.translate = below > 0 ? `0 ${-below}px` : ''; - }, [isZoomTarget]); - useAttachment( - imageWrapperRef, - element => observeResize(element, placeCaption), - placeCaption, - ); - // Places the caption for the new item's layout before it paints. - useIsomorphicLayoutEffect(() => { - placeCaption(); - }, [placeCaption, viewedItem]); - // The zoom stage takes the keyboard's zoom and pan and every pointer's // gestures. Past a limit, a pinch or a pan gives way and returns. const zoom = useZoomCore({ - stageRef: isGallery ? pageMediaRef : imageWrapperRef, - surfaceRef: isGallery ? trackRef : imageWrapperRef, + stageRef: pageMediaRef, + surfaceRef: trackRef, isEnabled: isOpen && isZoomTarget, itemKey: viewedItem, // Zoom changes are silent to assistive tech, since only the transform @@ -1379,10 +1297,6 @@ export function Lightbox({ next ? t('@astryx.lightbox.zoomedIn') : t('@astryx.lightbox.zoomedOut'), ); }, - onFitChange: isAtFit => { - isShownAtFitRef.current = isAtFit; - placeCaption(); - }, }); const {isTouch} = useTouchPresentation(); const startsOnCaption = (touch: GestureTouch | undefined) => { @@ -1393,12 +1307,12 @@ export function Lightbox({ ); }; const stage = useZoomStage(zoom, { - stageRef: isGallery ? pageMediaRef : imageWrapperRef, - surfaceRef: isGallery ? trackRef : imageWrapperRef, + stageRef: pageMediaRef, + surfaceRef: trackRef, 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. + // The stage shares its surface with the page around it. A tap there + // closes, as on the backdrop, unless it lands on the caption. onTapOutside: ({x, y}) => { const caption = trackRef.current ?.querySelector('[data-current] [data-lightbox-caption]') @@ -1418,7 +1332,7 @@ export function Lightbox({ isTouchPresentation: isTouch, // Only a gallery's touch pager takes a drag past a zoomed photo's edge. hasOuterPager: isGallery && isTouch, - // A pinch whose first finger lands on a gallery's caption is the page's. + // A pinch whose first finger lands on a caption is the page's. shouldBeginPinch: recognizer => !startsOnCaption(recognizer.trackedTouches[0]), dismiss: { @@ -1444,10 +1358,7 @@ export function Lightbox({ // 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, - ); + : resolveMotion(pageMediaRef.current, springs.settle); const opacity = dismisses ? 0 : 1; const move = (backdropMovesRef.current += 1); setBackdropMoving(true); @@ -1575,7 +1486,9 @@ export function Lightbox({ usePager({ viewportRef: imageWrapperRef, - trackRef, + // A single photo has no pager, since it has nothing to page to. Its track + // still holds its one page and takes the zoom's gestures. + trackRef: isGallery ? trackRef : noPagerTrackRef, count: mediaArray.length, gap: zoomMedia.viewer.pageGap, index, @@ -1643,7 +1556,7 @@ export function Lightbox({ x <= Math.max(...boxes.map(r => r.right))) ); }; - // Without zoom, a gallery's stage fills the viewer. So a finger's tap on it + // Without zoom, the stage fills the viewer. So a finger's tap on it // beside the media closes the viewer, as a click on the backdrop does. A // press that moves past the tap's movement limit is no tap. A mouse's or a // pen's click closes it only outside the media (`isClickOutsideMedia`). @@ -1664,7 +1577,7 @@ export function Lightbox({ handleClose(); } }, - {isEnabled: isOpen && isGallery && !isZoomTarget, manageStyle: false}, + {isEnabled: isOpen && !isZoomTarget, manageStyle: false}, ); // Gallery navigation. The buttons and the arrow keys ask for the new item. @@ -1818,7 +1731,6 @@ export function Lightbox({ ) : ( {isCurrent ); // The current item and its neighbours; the pager shows one at rest. - const pageIndexes = isGallery - ? [index - 1, index, index + 1].filter(i => i >= 0 && i < mediaArray.length) - : []; - const hasCaptionBand = - isGallery && mediaArray.some(item => isRenderable(item.caption)); + const pageIndexes = [index - 1, index, index + 1].filter( + i => i >= 0 && i < mediaArray.length, + ); + const hasCaptionBand = mediaArray.some(item => isRenderable(item.caption)); // Its place ends the caption's last line, unless the open caption scrolls. const hasCaptionTogglePlace = hasCaptionToggle && !isCaptionScrolling; - // The keyboard's zoom button is the photo's wrapper. In a gallery it is the - // current page's photo box, so the caption band stays outside it. - const isWrapperZoomButton = isZoomTarget && !isGallery; + // The keyboard's zoom button is the current page's photo box, so the + // caption band stays outside it. const zoomButtonProps = { role: 'button', tabIndex: 0, @@ -1924,32 +1834,15 @@ export function Lightbox({ })} - {/* Media + caption group (centered together) */} + {/* The stage: a track of pages, each a photo and its caption */}
+ {...stylex.props(styles.mediaGroup)}>
- {isGallery ? ( -
- {pageIndexes.map(i => ( +
+ {pageIndexes.map(i => ( +
+ {renderMedia(mediaArray[i], i === index)} +
+ {hasCaptionBand && (
- {renderMedia(mediaArray[i], i === index)} -
- {hasCaptionBand && ( -
- {isRenderable(mediaArray[i].caption) && ( - // The page's one caption: clamped in the - // band, or open over the photo's bottom. -
-
- +
+ +
-
+
+ + {i === index && ( + // Mounted with the caption, and hidden + // until the caption needs it. So a + // measurement only shows or hides it, + // and adds no element. + { + if (isCaptionOpen) { + setOpenCaptionIndex(null); + return; } - {...stylex.props(styles.captionFlow)}> -
-
- {i === index && ( - // Mounted with the caption, and hidden - // until the caption needs it. So a - // measurement only shows or hides it, - // and adds no element. - { - if (isCaptionOpen) { - setOpenCaptionIndex(null); - return; - } - // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the opened caption lays out without the toggle's place before its lines are counted - flushSync(() => { - setCaptionShownLines(0); - setOpenCaptionIndex(index); - }); - countOpenCaption(); - }} - xstyle={ - [ - styles.captionToggle, - touchHitAreaStyles.layer, - !hasCaptionToggle && - styles.captionToggleHidden, - ] as StyleXStyles - }> - {isCaptionOpen - ? t('@astryx.lightbox.captionLess') - : t('@astryx.lightbox.captionMore')} - - )} -
+ // eslint-disable-next-line @eslint-react/dom-no-flush-sync -- the opened caption lays out without the toggle's place before its lines are counted + flushSync(() => { + setCaptionShownLines(0); + setOpenCaptionIndex(index); + }); + countOpenCaption(); + }} + xstyle={ + [ + styles.captionToggle, + touchHitAreaStyles.layer, + !hasCaptionToggle && + styles.captionToggleHidden, + ] as StyleXStyles + }> + {isCaptionOpen + ? t('@astryx.lightbox.captionLess') + : t('@astryx.lightbox.captionMore')} + + )}
- )} -
- )} -
- ))} -
- ) : ( - renderMedia(currentItem, true) - )} +
+ )} +
+ )} +
+ ))} +
- - {!isGallery && isRenderable(currentItem.caption) && ( - - {currentItem.caption} - - )}
{ const style = getComputedStyle(el); return { width: parseFloat(style.outlineWidth), offset: parseFloat(style.outlineOffset), - clips: getComputedStyle(el.parentElement as Element).overflow, + clips: getComputedStyle( + el.closest('[data-lightbox-media] > :first-child') as Element, + ).overflow, }; }); expect(ring.clips).toBe('hidden'); @@ -138,10 +142,10 @@ test("the zoom target's focus ring sits inside the stage, which a clipping group expect(ring.offset).toBeLessThanOrEqual(-ring.width); }); -test('a caption sits under the fitted photo, as it does without zoom', async ({ +test("a caption sits in its band under the photo's box, zoomed or not, as in a gallery", async ({ page, }) => { - // A 3:1 panorama leaves the filling stage most of its height free. + // A 3:1 panorama leaves the photo's box most of its height free. await page.route('https://picsum.photos/**', async route => route.fulfill({ contentType: 'image/svg+xml', @@ -157,22 +161,29 @@ test('a caption sits under the fitted photo, as it does without zoom', async ({ await expect .poll(async () => img.evaluate(el => (el as HTMLImageElement).naturalWidth)) .toBe(3000); - const caption = dialog.getByText('A winding path through the forest'); - await expect - .poll(async () => { - const photo = await boxOf(img); - const below = await boxOf(caption); - return Math.round(below.y - (photo.y + photo.height)); - }) - .toBe(0); - // Zoomed, the photo fills the stage, and the caption goes back below it. + const caption = dialog.locator('[data-lightbox-caption]'); const stage = dialog.getByRole('button', {name: 'Zoom'}); + // The band starts where the photo's box ends, and the fitted photo centres + // in that box, clear of the band. + const band = async () => + caption.evaluate(el => { + const r = (el.parentElement as HTMLElement).getBoundingClientRect(); + return {top: r.top, height: r.height}; + }); const stageBox = await boxOf(stage); + const fitted = await band(); + expect(Math.abs(fitted.top - (stageBox.y + stageBox.height))).toBeLessThan( + 0.5, + ); + const photo = await boxOf(img); + expect(photo.y + photo.height).toBeLessThanOrEqual(fitted.top + 0.5); + // Zoomed, the photo fills its box, and the band and caption stay put. + const captionBox = await boxOf(caption); await page.mouse.dblclick(centre(stageBox).x, centre(stageBox).y); await expect(stage).toHaveAttribute('aria-pressed', 'true'); - await expect - .poll(async () => (await boxOf(caption)).y - (stageBox.y + stageBox.height)) - .toBeGreaterThanOrEqual(-0.5); + await settled(page); + expect(await band()).toEqual(fitted); + expect(await boxOf(caption)).toEqual(captionBox); }); /** Opens the gallery story (zoom on) at its first photo with the mouse. */ @@ -288,11 +299,16 @@ test('the zoom target takes its touches as on a phone where the primary pointer expect(await stage.evaluate(el => getComputedStyle(el).touchAction)).toBe( 'none', ); - // The last is the media surface, which has no box. + // As in a gallery, the photo's box claims them and the track, the zoom + // stage's surface, leaves only the page's pinch-zoom. The last is the media + // surface, which has no box. expect(await touchActionsAbove(img)).toEqual([ 'auto', 'none', 'auto', + 'pinch-zoom', + 'auto', + 'auto', 'auto', 'auto', ]); @@ -317,13 +333,17 @@ test('a photo without zoom leaves its touches to the page where the primary poin const dialog = page.getByRole('dialog'); await expect(dialog).toBeVisible(); const photo = dialog.getByRole('img').first(); - // The last is the media surface, which has no box. + // The photo's page, its track and the stage sit between them. The last is + // the media surface, which has no box. expect(await touchActionsAbove(photo)).toEqual([ 'auto', 'auto', 'auto', 'auto', 'auto', + 'auto', + 'auto', + 'auto', ]); }); @@ -865,6 +885,63 @@ test('a mouse click between a gallery photo and its caption band closes the view }); }); +test('with zoom, a mouse double-click on a single photo’s caption zooms the photo, and the caption stays its description', async ({ + page, +}) => { + await page.route('https://picsum.photos/**', async route => + route.fulfill({ + contentType: 'image/svg+xml', + body: photoSvg(PHOTO.width, PHOTO.height), + }), + ); + await page.goto( + `${storybook.origin}/iframe.html?id=core-lightbox--zoom-with-caption&viewMode=story`, + ); + await page.getByRole('button', {name: 'Open zoom with caption'}).click(); + const dialog = page.getByRole('dialog'); + await expect(dialog).toBeVisible(); + const img = dialog.getByRole('img', {name: 'Forest path'}); + await expect + .poll(async () => img.evaluate(el => (el as HTMLImageElement).naturalWidth)) + .toBe(PHOTO.width); + await settled(page); + const fitted = await boxOf(img); + // The middle of the caption's first word. + const word = await dialog.evaluate(viewer => { + const caption = viewer.querySelector( + '[data-lightbox-caption] .astryx-text', + ); + const walker = document.createTreeWalker( + caption ?? viewer, + NodeFilter.SHOW_TEXT, + ); + let node = walker.nextNode() as Text | null; + while (node != null && node.data.trim() === '') { + node = walker.nextNode() as Text | null; + } + if (node == null) { + throw new Error('no caption text'); + } + const start = node.data.search(/\S/); + const range = document.createRange(); + range.setStart(node, start); + range.setEnd(node, start + 1); + const r = range.getBoundingClientRect(); + return {x: r.x + r.width / 2, y: r.y + r.height / 2}; + }); + await page.mouse.dblclick(word.x, word.y); + await expect + .poll(async () => (await boxOf(img)).width) + .toBeGreaterThan(fitted.width * 1.5); + expect(await page.evaluate(() => String(window.getSelection()).trim())).toBe( + '', + ); + // Screen readers still read the caption: it is the viewer's description. + await expect(dialog).toHaveAccessibleDescription( + 'A winding path through the forest', + ); +}); + test('in a gallery with zoom, a mouse click beside a small photo closes past its caption’s width and stays open within it, as on main', async ({ page, }) => { diff --git a/packages/core/src/Lightbox/LightboxZoomResize.test.tsx b/packages/core/src/Lightbox/LightboxZoomResize.test.tsx index ad063fceb3923..e2b2776267f0f 100644 --- a/packages/core/src/Lightbox/LightboxZoomResize.test.tsx +++ b/packages/core/src/Lightbox/LightboxZoomResize.test.tsx @@ -4,9 +4,9 @@ * @file LightboxZoomResize.test.tsx * @input Lightbox with `hasZoom`, mounted closed with no media, given its * photos, then opened; the shared resize observer watched - * @output Pins that the zoom follows a resize of its stage however the viewer - * first rendered. A stage that mounts after the viewer is subscribed once - * it exists + * @output Pins that the zoom follows a resize of its stage's track however + * the viewer first rendered. A track that mounts after the viewer is + * subscribed once it exists * @position Unit test for useZoomCore.ts's resize subscription */ @@ -51,12 +51,15 @@ describe('Lightbox zoom and resizes', () => { rerender( {}} media={photos} hasZoom />, ); - // The zoom target is the stage: a rotation while zoomed keeps the same - // photo point centred only if its resizes reach the zoom. + // The zoom target is the stage, on its page of the track. A rotation + // while zoomed keeps the same photo point centred only if the track's + // resizes reach the zoom. const stage = screen.getByRole('button', {name: 'Zoom'}); + const track = stage.closest('[data-lightbox-page]')?.parentElement; const observed = vi .mocked(observeResize) .mock.calls.map(([element]) => element); - expect(observed).toContain(stage); + expect(track).toBeInstanceOf(HTMLElement); + expect(observed).toContain(track); }); }); diff --git a/packages/core/src/Lightbox/__tests__/LightboxDismiss.interaction.browser.spec.ts b/packages/core/src/Lightbox/__tests__/LightboxDismiss.interaction.browser.spec.ts index 12e1674042b07..45b1d2a3d088a 100644 --- a/packages/core/src/Lightbox/__tests__/LightboxDismiss.interaction.browser.spec.ts +++ b/packages/core/src/Lightbox/__tests__/LightboxDismiss.interaction.browser.spec.ts @@ -796,8 +796,10 @@ test('a caller that keeps the viewer open gets the photo, the backdrop and the c }); 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. + // The caption sits in its band under the photo's row. Held sideways, a + // landscape photo fills the row's height, so the drag carries it over the + // caption at once, while the caption still shows. + await page.setViewportSize({width: 874, height: 402}); const v = await openViewer(page); const caption = v.dialog.locator('[data-lightbox-caption]'); await expect(caption).toBeVisible(); @@ -910,11 +912,11 @@ for (const story of ['zoom', 'gallery'] as const) { }); } -test('a caption comes back under the photo once a drag to close springs back', async ({ +test('a caption stays in its band through a drag to close that springs back', async ({ page, }) => { - // A 3:1 panorama leaves the stage free space below the fitted photo, so - // the caption moves up under it. + // A 3:1 panorama leaves free space between the fitted photo and the + // caption's band. The band keeps its place through the drag. await page.route('https://picsum.photos/**', async route => route.fulfill({ contentType: 'image/svg+xml', @@ -939,15 +941,15 @@ test('a caption comes back under the photo once a drag to close springs back', a .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 place = async () => { const below = await caption.boundingBox(); - if (photo == null || below == null) { - throw new Error('no photo or caption'); + if (below == null) { + throw new Error('no caption'); } - return Math.round(below.y - (photo.y + photo.height)); + return {x: Math.round(below.x), y: Math.round(below.y)}; }; - await expect.poll(gap).toBe(0); + await expect(caption).toBeVisible(); + const before = await place(); const box = await img.boundingBox(); if (box == null) { throw new Error('no photo'); @@ -965,7 +967,7 @@ test('a caption comes back under the photo once a drag to close springs back', a ), ); await expect(dialog).toBeVisible(); - await expect.poll(gap).toBe(0); + await expect.poll(place).toEqual(before); }); test("while the controls fade with a drag, a tap on Close still reaches it, above a gallery's pages", async ({ diff --git a/packages/core/src/Lightbox/__tests__/LightboxSingleCaption.interaction.browser.spec.ts b/packages/core/src/Lightbox/__tests__/LightboxSingleCaption.interaction.browser.spec.ts new file mode 100644 index 0000000000000..d9b1111cb18e0 --- /dev/null +++ b/packages/core/src/Lightbox/__tests__/LightboxSingleCaption.interaction.browser.spec.ts @@ -0,0 +1,226 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file LightboxSingleCaption.interaction.browser.spec.ts + * @input The built Lightbox stories with a single photo and with a gallery, + * on the phone project and at a desktop size + * @output Proofs that a single photo presents its caption as a gallery's + * page does. The band has the same shape and backing, the text the same + * type, and the photo the same box. A long caption ends in "more", and a + * photo with no caption has no band. A single photo shows no paging + * controls + * @position Interaction tests for Lightbox's caption (browser), beside + * LightboxPaging.interaction.browser.spec.ts + */ + +import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright'; +import { + frames, + openStory, + withStorybook, +} from '@astryxdesign/interaction-harness'; + +const storybook = withStorybook(test); + +/** A plain 3:2 photo, served for every story photo. */ +const PHOTO_SVG = + ''; + +/** Opens a story's Lightbox and waits for its photos to load. */ +async function openViewer(page: Page, story: string, trigger: string) { + await page.route('https://picsum.photos/**', async route => + route.fulfill({contentType: 'image/svg+xml', body: PHOTO_SVG}), + ); + await openStory(page, storybook(), story); + await page.getByRole('button', {name: trigger}).click(); + const dialog = page.getByRole('dialog'); + await expect(dialog).toBeVisible(); + await expect + .poll(async () => + dialog.evaluate(el => + [...el.querySelectorAll('[data-current] img')].every( + img => (img as HTMLImageElement).naturalWidth === 1200, + ), + ), + ) + .toBe(true); + await frames(page, 2); + return dialog; +} + +/** + * The current page's photo box, photo and caption band, in what a gallery + * and a single photo share: no content-dependent size. + */ +async function captionShape(page: Page) { + return page.getByRole('dialog').evaluate(el => { + const viewer = el.querySelector('[data-lightbox-media] > :first-child'); + const current = viewer?.querySelector('[data-current]'); + const media = current?.querySelector('[data-lightbox-page-media]'); + const photo = media?.querySelector('img'); + const band = media?.nextElementSibling; + const caption = band?.querySelector('[data-lightbox-caption]'); + const text = caption?.querySelector('.astryx-text'); + if ( + viewer == null || + media == null || + photo == null || + band == null || + text == null + ) { + return null; + } + const round = (n: number) => Math.round(n * 2) / 2; + const v = viewer.getBoundingClientRect(); + const m = media.getBoundingClientRect(); + const p = photo.getBoundingClientRect(); + const b = band.getBoundingClientRect(); + const bandStyle = getComputedStyle(band); + const textStyle = getComputedStyle(text); + return { + band: { + height: round(b.height), + left: round(b.left - v.left), + right: round(v.right - b.right), + bottom: round(v.bottom - b.bottom), + backgroundColor: bandStyle.backgroundColor, + paddingBottom: bandStyle.paddingBottom, + }, + // The photo's row ends where the band starts. + photoRow: {height: round(m.height), gapToBand: round(b.top - m.bottom)}, + photo: { + top: round(p.top - v.top), + left: round(p.left - v.left), + width: round(p.width), + height: round(p.height), + }, + text: { + fontSize: textStyle.fontSize, + lineHeight: textStyle.lineHeight, + fontWeight: textStyle.fontWeight, + color: textStyle.color, + textAlign: textStyle.textAlign, + maxWidth: textStyle.maxWidth, + paddingTop: textStyle.paddingTop, + paddingInline: `${textStyle.paddingLeft} ${textStyle.paddingRight}`, + }, + }; + }); +} + +for (const size of ['phone', 'desktop'] as const) { + test.describe(`on a ${size}`, () => { + if (size === 'desktop') { + test.use({ + viewport: {width: 1280, height: 800}, + deviceScaleFactor: 1, + isMobile: false, + hasTouch: false, + }); + } + + test('a single photo presents its caption as a gallery page does: the same band, text and photo box', async ({ + page, + }) => { + await openViewer( + page, + 'core-lightbox--gallery-with-captions', + 'Open gallery with captions', + ); + const gallery = await captionShape(page); + expect(gallery).not.toBeNull(); + await openViewer( + page, + 'core-lightbox--with-caption', + 'Open with caption', + ); + expect(await captionShape(page)).toEqual(gallery); + await openViewer( + page, + 'core-lightbox--zoom-with-caption', + 'Open zoom with caption', + ); + expect(await captionShape(page)).toEqual(gallery); + }); + + test('a single photo’s long caption ends in "more", which opens it in full and "less" closes, as in a gallery', async ({ + page, + }) => { + const dialog = await openViewer( + page, + 'core-lightbox--single-with-long-caption', + 'Open single photo with a long caption', + ); + const more = dialog.getByRole('button', {name: 'more'}); + await expect(more).toBeVisible(); + await expect(more).toHaveAttribute('aria-expanded', 'false'); + const lines = async () => + dialog.evaluate(el => { + const text = el.querySelector( + '[data-current] [data-lightbox-caption] .astryx-text', + ); + if (text == null) { + return Number.NaN; + } + const style = getComputedStyle(text); + const height = + text.clientHeight - + parseFloat(style.paddingTop) - + parseFloat(style.paddingBottom); + return Math.round(height / parseFloat(style.lineHeight)); + }); + expect(await lines()).toBe(2); + await more.click(); + const less = dialog.getByRole('button', {name: 'less'}); + await expect(less).toHaveAttribute('aria-expanded', 'true'); + await expect.poll(lines).toBeGreaterThan(2); + await less.click(); + await expect(more).toHaveAttribute('aria-expanded', 'false'); + await expect.poll(lines).toBe(2); + }); + + test('a single photo with no caption has no band: its photo box fills the viewer, as a gallery’s with no caption', async ({ + page, + }) => { + const dialog = await openViewer( + page, + 'core-lightbox--with-zoom', + 'Open with zoom', + ); + const fill = await dialog.evaluate(el => { + const viewer = el.querySelector('[data-lightbox-media] > :first-child'); + const media = viewer?.querySelector( + '[data-current] [data-lightbox-page-media]', + ); + if (viewer == null || media == null) { + return null; + } + return { + captions: el.querySelectorAll('[data-lightbox-caption]').length, + band: media.nextElementSibling != null, + heightGap: Math.round( + viewer.getBoundingClientRect().height - + media.getBoundingClientRect().height, + ), + }; + }); + expect(fill).toEqual({captions: 0, band: false, heightGap: 0}); + }); + + test('a single photo shows no paging controls: no Previous, Next or counter', async ({ + page, + }) => { + const dialog = await openViewer( + page, + 'core-lightbox--with-caption', + 'Open with caption', + ); + await expect(dialog.getByRole('button', {name: 'Previous'})).toHaveCount( + 0, + ); + await expect(dialog.getByRole('button', {name: 'Next'})).toHaveCount(0); + await expect(dialog.getByText('1 / 1')).toHaveCount(0); + await expect(dialog.locator('[data-lightbox-page]')).toHaveCount(1); + }); + }); +} diff --git a/packages/core/src/Lightbox/__tests__/LightboxZoom.interaction.browser.spec.ts b/packages/core/src/Lightbox/__tests__/LightboxZoom.interaction.browser.spec.ts index e4aff14091ec7..2d8e9e1919b8b 100644 --- a/packages/core/src/Lightbox/__tests__/LightboxZoom.interaction.browser.spec.ts +++ b/packages/core/src/Lightbox/__tests__/LightboxZoom.interaction.browser.spec.ts @@ -580,6 +580,61 @@ for (const [photo, fill] of [ }); } +for (const [story, trigger] of [ + ['core-lightbox--with-caption', 'Open with caption'], + ['core-lightbox--zoom-with-caption', 'Open zoom with caption'], +] as const) { + for (const theme of SHIPPED_THEMES) { + test(`in light mode, a single photo's caption keeps 4.5:1 on its backing over a white page and photo (${story}, ${theme})`, async ({ + page, + }) => { + await page.route('https://picsum.photos/**', async route => + route.fulfill({ + contentType: 'image/svg+xml', + body: '', + }), + ); + await page.goto( + `${storybook()}/iframe.html?id=${story}&viewMode=story&globals=astryxTheme:${theme};colorMode:light`, + ); + await page.locator('#storybook-root > *').first().waitFor(); + // The page behind the viewer is white, the lightest it can be. + await page.addStyleTag({ + content: + 'html, body, #storybook-root { background: #ffffff !important; }', + }); + await frames(page, 2); + const driver = await touchDriver(page); + const opener = await page + .getByRole('button', {name: trigger}) + .boundingBox(); + if (opener == null) { + throw new Error('no trigger'); + } + await driver.tap({ + x: opener.x + opener.width / 2, + y: opener.y + opener.height / 2, + }); + const dialog = page.getByRole('dialog'); + await expect(dialog).toBeVisible(); + await expect + .poll(async () => + dialog + .locator('img') + .first() + .evaluate(img => (img as HTMLImageElement).naturalWidth), + ) + .toBe(1200); + // The caption is the viewer's description. + const captionId = await dialog.getAttribute('aria-describedby'); + const caption = page.locator(`[id="${captionId}"]`); + await expect(caption).toBeVisible(); + const {value} = await captionContrast(page, caption); + expect(value).toBeGreaterThanOrEqual(4.5); + }); + } +} + // A light page's overlay is the lightest backdrop under the caption's band. for (const theme of SHIPPED_THEMES) { test(`in light mode, a gallery's caption keeps 4.5:1 in its band (${theme})`, async ({ diff --git a/packages/core/src/Lightbox/__tests__/LightboxZoomModes.interaction.browser.spec.ts b/packages/core/src/Lightbox/__tests__/LightboxZoomModes.interaction.browser.spec.ts index c591a76421dde..22e3f492cb60d 100644 --- a/packages/core/src/Lightbox/__tests__/LightboxZoomModes.interaction.browser.spec.ts +++ b/packages/core/src/Lightbox/__tests__/LightboxZoomModes.interaction.browser.spec.ts @@ -176,18 +176,30 @@ test('with a fine pointer (a desktop) the stage fills the viewer, as under a coa const img = dialog.getByRole('img', {name: 'Forest path'}); await decoded(img); await frames(page, 2); - // The stage and its group stretch to fill the viewer for every pointer. A - // click or a drag beside the photo is the stage's, as a finger's is. + // The stage and its group stretch to fill the viewer for every pointer. + // The zoom button is the stage's one page, the photo's box, and with no + // caption it fills the stage. A click or a drag beside the photo is the + // stage's, as a finger's is. const layout = await stage.evaluate(el => { - const own = getComputedStyle(el); - const group = getComputedStyle(el.parentElement as HTMLElement); + const viewport = el.closest( + '[data-lightbox-media] > :first-child', + ) as HTMLElement; + const own = getComputedStyle(viewport); + const group = getComputedStyle(viewport.parentElement as HTMLElement); + const v = viewport.getBoundingClientRect(); + const b = el.getBoundingClientRect(); return { stage: [own.alignSelf, own.flexGrow], group: [group.alignSelf, group.flexGrow], + button: [ + Math.round(b.width - v.width), + Math.round(b.height - v.height), + ], }; }); expect(layout.stage).toEqual(['stretch', '1']); expect(layout.group).toEqual(['stretch', '1']); + expect(layout.button).toEqual([0, 0]); // The photo fits inside the viewer, as before. const imgBox = await img.boundingBox(); if (imgBox == null) { diff --git a/packages/core/src/Lightbox/useZoomCore.ts b/packages/core/src/Lightbox/useZoomCore.ts index 6cbaa44aa7afa..9889434a46518 100644 --- a/packages/core/src/Lightbox/useZoomCore.ts +++ b/packages/core/src/Lightbox/useZoomCore.ts @@ -5,8 +5,8 @@ /** * @file useZoomCore.ts * @input A stage element ref, which clips and centres the photo, and the - * element the gestures attach to: the stage, or a gallery's track. Also - * whether zoom is on, the current item's key and the zoom and fit callbacks + * element the gestures attach to, the viewer's track of pages. Also whether + * zoom is on, the current item's key and the zoom callback * @output Exports `useZoomCore`: Lightbox's zoom stage for every pointer. It * writes the photo's transform through the compositor animator and settles * every zoom, the keyboard's zoom and pan included, on `springs.settle`. Its @@ -65,21 +65,6 @@ export interface UseZoomCoreOptions { itemKey: unknown; /** The photo became zoomed or returned to the fitted size. */ onZoomedChange: (isZoomed: boolean) => void; - /** - * The photo left or came back to its fitted size on screen. It reads false - * from a gesture's first move or a settle's start, and true once a settle - * back lands. - */ - onFitChange?: (isAtFit: boolean) => void; -} - -/** Whether a shown transform is the fitted size, to within a pixel. */ -function isAtFit(transform: ZoomTransform): boolean { - return ( - Math.abs(transform.scale - 1) < 1e-3 && - Math.abs(transform.x) < 0.5 && - Math.abs(transform.y) < 0.5 - ); } /** What Lightbox calls: the photo's ref and the keyboard's zoom and pan. */ @@ -130,11 +115,6 @@ 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. */ @@ -260,21 +240,12 @@ export function useZoomCore(options: UseZoomCoreOptions): ZoomCore { [animator], ); - const atFitRef = useRef(true); - const setAtFit = useCallback((next: boolean) => { - if (atFitRef.current !== next) { - atFitRef.current = next; - optionsRef.current.onFitChange?.(next); - } - }, []); - const write = useCallback( (transform: ZoomTransform) => { targetRef.current = transform; animator.set({x: transform.x, y: transform.y, scale: transform.scale}); - setAtFit(isAtFit(transform)); }, - [animator, setAtFit], + [animator], ); const setTarget = useCallback((transform: ZoomTransform) => { @@ -333,12 +304,8 @@ export function useZoomCore(options: UseZoomCoreOptions): ZoomCore { from.y === target.y && from.scale === target.scale ) { - setAtFit(isAtFit(target)); return; } - // The photo is off its fitted size while it moves, back at it only - // once a settle there lands. - setAtFit(false); // Registers the reduced-motion cross-fade once; later calls do nothing. registerReducedMotionCrossFade(); // Every zoom settles on `springs.settle`, read where the stage is. A @@ -349,7 +316,7 @@ export function useZoomCore(options: UseZoomCoreOptions): ZoomCore { const span = target.scale - from.scale; const rate = Number.isFinite(scaleVelocity) && span !== 0 ? scaleVelocity / span : 0; - const handle = animator.animate( + animator.animate( {x: target.x, y: target.y, scale: target.scale}, { spring: resolveMotion(stageElement, springs.settle), @@ -361,15 +328,8 @@ export function useZoomCore(options: UseZoomCoreOptions): ZoomCore { }, {touchRelease}, ); - if (isAtFit(target)) { - void handle.finished.then(landed => { - if (landed && targetRef.current === target) { - setAtFit(true); - } - }); - } }, - [animator, current, setAtFit, setZoomed], + [animator, current, setZoomed], ); // Another item: back to the fitted size before it paints. Lightbox resets @@ -380,8 +340,7 @@ export function useZoomCore(options: UseZoomCoreOptions): ZoomCore { targetRef.current = IDENTITY; zoomedRef.current = false; geometryRef.current = null; - setAtFit(true); - }, [animator, options.itemKey, setAtFit]); + }, [animator, options.itemKey]); // A rotation or resize keeps the same photo point centred at the same // on-screen size (the shared resize observer). It watches the surface: in @@ -498,7 +457,6 @@ export function useZoomCore(options: UseZoomCoreOptions): ZoomCore { write, setTarget, setZoomed, - setAtFit, isMoving, isAtEdgeOf, settleTo, @@ -512,7 +470,6 @@ 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.ts index c1669ae54bd88..ee7083542a38d 100644 --- a/packages/core/src/Lightbox/useZoomStage.ts +++ b/packages/core/src/Lightbox/useZoomStage.ts @@ -221,7 +221,6 @@ export function useZoomStage( write, setTarget, setZoomed, - setAtFit, settleTo, isMoving, isAtEdgeOf, @@ -713,20 +712,12 @@ export function useZoomStage( {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); - } - } - }, - ); + // Back in its box: the stage clips again, unless another drag began. + void Promise.all([position.finished, size.finished]).then(() => { + if (dismissRef.current == null && !leavingRef.current) { + options.stageRef.current?.removeAttribute(ZOOM_DISMISSING_ATTRIBUTE); + } + }); }, {isEnabled: options.dismiss?.isEnabled === true, manageStyle: false}, ); @@ -753,10 +744,9 @@ export function useZoomStage( 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], + [animator, api, setTarget, stageRef], ); }