Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions .changeset/resize-keeps-neighbors-off.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
'react-spring-lightbox': patch
---

Widening the window no longer shows the images beside the current one sliding into view.

- With 1.9.0, the positions of the images on either side of the current one were pixel offsets for the old stage width. A wider window put part of a wide neighbor inside the stage, and the lightbox then animated it back out. In Chromium, widening the window from 1280px to 1600px showed up to 320px of a panorama beside the current image in about 40 frames, about 0.7 seconds. Dragging the window wider showed it in about half the frames. Only images wide enough to reach past their own page showed this, such as panoramas and wide screenshots.
- Now each image's position is a percentage of the stage width it was laid out for, so the browser moves the images in the same layout that widens the stage. When the lightbox gets the new width, it rescales the positions without moving anything on screen. An image that was sliding when the window changed size keeps sliding from where it is.
- Narrowing the window never showed this, and still doesn't.
- Tested with the unit tests on React 19 and React 18.3.1, the Playwright tests in Chromium, Firefox, and mobile Chromium on React 19, and the Chromium Playwright tests on React 18.3.1. A frame-by-frame check in Chromium and Firefox found no neighbor on screen in any frame, whether the window widened at once or in 40px steps. Resizing while an image is zoomed in was not tested. In the repository's perf harness at 1,000 images, dragging showed no measurable change in task or script time, and the open lightbox used about 0.13MB more JavaScript heap, 27.52MB against 27.39MB without this change.

Upgrade notes:

- If a test of your app reads the `transform` of a `.lightbox-image-pager` element and expects pixels, it now gets a percentage of the stage width.

Before:

```js
expect(page.style.transform).toBe('translateX(-1280px)');
```

After:

```js
expect(page.style.transform).toBe('translateX(-100%)');
```
24 changes: 24 additions & 0 deletions e2e/paging.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -468,3 +468,27 @@ test('keeps the current image centered when the window resizes', async ({ page }

expect(await shownImage(page)).toBe('Image 3');
});

test.describe('widening the window', () => {
test.skip(({ isMobile }) => isMobile, 'A desktop window');

test('keeps the images beside the current one off the screen', async ({ page }) => {
await page.setViewportSize({ height: 720, width: 1280 });
// The Panorama beside the Portrait is wide enough to reach into a stage that grows
await openHarness(page, 'variety&index=2');
const stop = await recordImagesOnScreen(page);

await page.setViewportSize({ height: 720, width: 1600 });
await page.waitForTimeout(300);
for (let width = 1640; width <= 1920; width += 40) {
await page.setViewportSize({ height: 720, width });
await page.waitForTimeout(40);
}
await settle(page);
const frames = await stop();

expect(frames.length).toBeGreaterThan(0);
expect(frames.filter((alts) => !alts.includes('Portrait'))).toEqual([]);
expect(frames.filter((alts) => alts.some((alt) => alt !== 'Portrait'))).toEqual([]);
});
});
12 changes: 8 additions & 4 deletions perf/jumps.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,14 @@ const startSampling = () => {
const sample = (time) => {
const pages = [...document.querySelectorAll('.lightbox-image-pager')]
.filter((span) => getComputedStyle(span).display !== 'none')
.map((span) => [
Number(span.querySelector('img').alt.replace('Image ', '')),
Number(/translateX\((-?[\d.e+-]+)px\)/.exec(span.style.transform)?.[1]),
]);
.map((span) => {
// A page writes translateX in pixels, or in percent of its own width
const [, value, unit] = /translateX\((-?[\d.e+-]+)(px|%)\)/.exec(span.style.transform) ?? [];
return [
Number(span.querySelector('img').alt.replace('Image ', '')),
unit === '%' ? (Number(value) / 100) * span.offsetWidth : Number(value),
];
});
state.frames.push({ pages, time });
if (state.recording) {
requestAnimationFrame(sample);
Expand Down
8 changes: 5 additions & 3 deletions src/__tests__/helpers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,11 @@ export const lightboxContainer = () => screen.getByTestId('lightbox-container');

const NUMBER = '(-?[\\d.]+(?:e[-+]?\\d+)?)';

/** Pixel offset of an element's `translateX(...)` transform */
export const translateX = (element: HTMLElement) =>
Number(new RegExp(`translateX\\(${NUMBER}px\\)`).exec(element.style.transform)?.[1]);
/** Pixel offset of an element's `translateX(...)` transform, written in pixels or in percent of its width */
export const translateX = (element: HTMLElement) => {
const [, value, unit] = new RegExp(`translateX\\(${NUMBER}(px|%)\\)`).exec(element.style.transform) ?? [];
return unit === '%' ? (Number(value) / 100) * element.clientWidth : Number(value);
};

/** The alt text of the image the pager has centered */
export const shownImage = () =>
Expand Down
12 changes: 12 additions & 0 deletions src/__tests__/paging.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1111,6 +1111,18 @@ describe('page layout', () => {
expect(translateX(pageOf(4))).toBe(1000);
});

test('a wider window puts the images beside the current one in their new places at once', async () => {
await openGallery();

layout.stage.width = 1000;
fireEvent(window, new Event('resize'));
await advance(FRAME);

expect(translateX(pageOf(2))).toBe(-1000);
expect(translateX(pageOf(3))).toBe(0);
expect(translateX(pageOf(4))).toBe(1000);
});

test('fits images to the stage height, minus 50px of room for controls', () => {
render(<Lightbox {...lightboxProps()} />);

Expand Down
16 changes: 13 additions & 3 deletions src/components/ImageStage/components/ImagePager/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { animated, useSprings } from '@react-spring/web';
import { animated, useSpringValue, useSprings } from '@react-spring/web';
import { useGesture } from '@use-gesture/react';
import React, { useEffect, useRef, useState } from 'react';

Expand Down Expand Up @@ -80,6 +80,9 @@ const ImagePager = ({
* @see https://www.react-spring.io/docs/hooks/use-springs
*/
const [pagerSprings, springsApi] = useSprings(images.length, (i) => getPagePositions(i));
// The stage width the pages' x was laid out for. Each page's transform is x as a percentage of it, so a wider
// window moves the pages in the same layout that widens them, before the pager learns the new width.
const layoutWidth = useSpringValue(imageStageWidth);

// Animate page change if currentIndex changes
useEffect(() => {
Expand All @@ -94,6 +97,12 @@ const ImagePager = ({
if (currentIndex === previous.index && imageStageWidth === previous.width) {
return;
}
if (imageStageWidth !== previous.width) {
// Rescale x with the width, so no page moves on screen. Pages at rest are then in their new places. The
// width changes first, because a page's transform reads it when its x changes.
layoutWidth.set(imageStageWidth);
springsApi.set((_, ctrl) => ({ x: (ctrl.springs.x.get() * imageStageWidth) / previous.width }));
}
const step = currentIndex - previous.index;
// The old image's page holds another image now, as after images are added or swapped
const replaced = images[previous.index]?.src !== previous.src;
Expand Down Expand Up @@ -143,7 +152,7 @@ const ImagePager = ({
}
return target;
});
}, [currentIndex, getPagePositions, imageStageWidth, images, shownSrc, springsApi]);
}, [currentIndex, getPagePositions, imageStageWidth, images, layoutWidth, shownSrc, springsApi]);

/**
* Update each Image's visibility and translateX offset during dragging
Expand Down Expand Up @@ -300,7 +309,8 @@ const ImagePager = ({
right: 0,
top: 0,
touchAction: !inline ? 'none' : 'pan-y',
transform: x.to((xInterp: number) => `translateX(${xInterp}px)`),
// Observing only x keeps one observer per page. A resize changes x along with the width.
transform: x.to((xValue: number) => `translateX(${(xValue / layoutWidth.get()) * 100}%)`),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
width: '100%',
willChange: 'transform',
}}
Expand Down
Loading