Skip to content

Commit 54ebf13

Browse files
committed
feat(Lightbox): touch zoom like the iOS Photos viewer
Lightbox's zoom moves to the gesture recognizers and the compositor animator: a pinch about the fingers with the pan riding along, UIKit's give past the zoom limits and its eased return about the last centroid, Photos' aspect-fill double tap (the tapped point to the centre), and a zoomed pan with UIScrollView's rubber band, coast and edge bounce. The mouse uses the same recognizers. On a touch screen the photo's stage fills the viewer and takes the pinch; the controls and caption keep the page's pinch-zoom. Keyboard panning stops at the photo's edges.
1 parent 2ac75ad commit 54ebf13

7 files changed

Lines changed: 2051 additions & 144 deletions

File tree

‎.changeset/lightbox-touch-zoom.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
'@astryxdesign/core': patch
3+
---
4+
5+
[feat] Lightbox's zoom now works on touch screens the way the iOS Photos viewer does. Pinch the photo to zoom around your fingers, and move them to pan while you zoom. Past the zoom limits the photo gives way, then eases back when you let go. Double-tap zooms until the photo fills the screen, bringing the tapped point to the centre; double-tap again to go back. A zoomed photo pans with momentum, stretches past its edges and settles back. Keyboard panning now stops at the photo's edges.
6+
7+
On a phone the photo's stage fills the viewer. A pinch on the photo no longer zooms the page, and a pinch on the controls or caption still does. The zoom animations run on the compositor, so they stay smooth while the page is busy. With `hasZoom` off, nothing changes.
8+
9+
@vjeux

‎packages/core/src/Lightbox/Lightbox.doc.mjs‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ export const docs = {
9898
name: 'hasZoom',
9999
type: 'boolean',
100100
description:
101-
'Enable zoom on double-click, or Enter/Space/+/- via keyboard (images only). When zoomed, drag or use arrow keys to pan.',
101+
'Enable zoom (images only): pinch, or double-tap or double-click to zoom in at that point and back, or Enter/Space/+/- via keyboard. When zoomed, drag (with momentum) or use arrow keys to pan.',
102102
default: 'false',
103103
},
104104
{
@@ -211,7 +211,8 @@ export const docsZh = {
211211
{
212212
name: 'hasZoom',
213213
type: 'boolean',
214-
description: '启用双击缩放(仅图片)。缩放后可拖动平移。',
214+
description:
215+
'启用缩放(仅图片):双指捏合,或双击/双点按在该处放大并还原,或使用 Enter/Space/+/- 键。缩放后可拖动(带惯性)或用方向键平移。',
215216
default: 'false',
216217
},
217218
{
@@ -296,7 +297,7 @@ export const docsDense = {
296297
index: 'Current index in gallery mode.',
297298
onIndexChange: 'Callback when gallery index changes.',
298299
hasZoom:
299-
'Enable zoom (double-click, Enter/Space, or +/-) and pan (drag or arrow keys) for images.',
300+
'Enable zoom (pinch, double-tap or double-click, Enter/Space, or +/-) and pan (drag or arrow keys) for images.',
300301
xstyle: 'StyleX styles for layout customization.',
301302
},
302303
};

‎packages/core/src/Lightbox/Lightbox.test.tsx‎

Lines changed: 184 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,57 @@ function politeRegion(): HTMLElement | null {
2929
return document.querySelector('[data-astryx-live-region="polite"]');
3030
}
3131

32+
/**
33+
* jsdom has no layout, so give the zoom stage what a browser measures: a
34+
* 400 × 600 stage showing a landscape photo fitted 400 × 200 at its vertical
35+
* centre. Photos' aspect-fill double tap zooms that photo 3×. Returns the
36+
* undo.
37+
*/
38+
function stubStageLayout(): () => void {
39+
const undo: (() => void)[] = [];
40+
const define = (
41+
proto: object,
42+
key: string,
43+
get: (element: HTMLElement) => number,
44+
) => {
45+
const original = Object.getOwnPropertyDescriptor(proto, key);
46+
Object.defineProperty(proto, key, {
47+
configurable: true,
48+
get(this: HTMLElement) {
49+
return get(this);
50+
},
51+
});
52+
undo.push(() => {
53+
if (original) {
54+
Object.defineProperty(proto, key, original);
55+
} else {
56+
Reflect.deleteProperty(proto, key);
57+
}
58+
});
59+
};
60+
const isPhoto = (element: Element) => element instanceof HTMLImageElement;
61+
const isStage = (element: Element) =>
62+
element.querySelector(':scope > img') != null;
63+
define(HTMLElement.prototype, 'offsetWidth', element =>
64+
isPhoto(element) ? 400 : 0,
65+
);
66+
define(HTMLElement.prototype, 'offsetHeight', element =>
67+
isPhoto(element) ? 200 : 0,
68+
);
69+
define(Element.prototype, 'clientWidth', element =>
70+
isStage(element) ? 400 : 0,
71+
);
72+
define(Element.prototype, 'clientHeight', element =>
73+
isStage(element) ? 600 : 0,
74+
);
75+
return () => undo.reverse().forEach(restore => restore());
76+
}
77+
78+
/** The photo's inline `translate` and `scale`, as the zoom stage wrote them. */
79+
function photoTransform(img: HTMLElement): {translate: string; scale: string} {
80+
return {translate: img.style.translate, scale: img.style.scale};
81+
}
82+
3283
// Both position messages, supplied by the test. Overriding the pair means an
3384
// assertion also proves which of the two keys the component reached for.
3485
const POSITION_MESSAGES = {
@@ -493,6 +544,13 @@ describe('Lightbox', () => {
493544
{src: '/b.jpg', alt: 'Image B'},
494545
{src: '/c.jpg', alt: 'Image C'},
495546
];
547+
let restoreLayout: () => void = () => {};
548+
beforeEach(() => {
549+
restoreLayout = stubStageLayout();
550+
});
551+
afterEach(() => {
552+
restoreLayout();
553+
});
496554

497555
function zoomTarget(): HTMLElement {
498556
return screen.getByRole('button', {name: 'Zoom'});
@@ -578,24 +636,51 @@ describe('Lightbox', () => {
578636
const dialog = document.querySelector('dialog')!;
579637
fireEvent.keyDown(zoomTarget(), {key: 'Enter'});
580638
const img = screen.getByAltText('Image B');
581-
expect(img.getAttribute('style') ?? '').toContain('translate(0px, 0px)');
639+
// Zoomed about the stage's centre until the photo fills the stage's
640+
// height (3×): 1200 × 600, its centre on the stage's centre.
641+
expect(photoTransform(img)).toEqual({
642+
translate: '-400px -200px',
643+
scale: '3 3',
644+
});
582645
// ArrowRight reveals content to the right (image shifts left) and must
583646
// not fall through to gallery navigation.
584647
fireEvent.keyDown(dialog, {key: 'ArrowRight'});
585648
expect(onIndexChange).not.toHaveBeenCalled();
586-
expect(img.getAttribute('style') ?? '').toContain(
587-
'translate(-25px, 0px)',
588-
);
649+
expect(photoTransform(img).translate).toBe('-450px -200px');
650+
// The photo fills the stage's height exactly, so it cannot move
651+
// vertically.
589652
fireEvent.keyDown(dialog, {key: 'ArrowDown'});
590-
expect(img.getAttribute('style') ?? '').toContain(
591-
'translate(-25px, -25px)',
592-
);
653+
expect(photoTransform(img).translate).toBe('-450px -200px');
593654
fireEvent.keyDown(dialog, {key: 'ArrowLeft'});
594655
fireEvent.keyDown(dialog, {key: 'ArrowUp'});
595-
expect(img.getAttribute('style') ?? '').toContain('translate(0px, 0px)');
656+
expect(photoTransform(img).translate).toBe('-400px -200px');
596657
expect(onIndexChange).not.toHaveBeenCalled();
597658
});
598659

660+
it('stops panning at the edges of the photo', () => {
661+
render(
662+
<Lightbox
663+
isOpen={true}
664+
onOpenChange={() => {}}
665+
media={{src: '/photo.jpg', alt: 'Photo'}}
666+
hasZoom
667+
/>,
668+
);
669+
const dialog = document.querySelector('dialog')!;
670+
fireEvent.keyDown(dialog, {key: '+'});
671+
const img = screen.getByAltText('Photo');
672+
for (let i = 0; i < 12; i++) {
673+
fireEvent.keyDown(dialog, {key: 'ArrowLeft'});
674+
}
675+
// The photo's left edge rests on the stage's left edge, no gap.
676+
expect(photoTransform(img).translate).toBe('0px -200px');
677+
for (let i = 0; i < 24; i++) {
678+
fireEvent.keyDown(dialog, {key: 'ArrowRight'});
679+
}
680+
// 1200 px wide on a 400 px stage: its right edge on the stage's.
681+
expect(photoTransform(img).translate).toBe('-800px -200px');
682+
});
683+
599684
it('navigates the gallery with arrows when not zoomed, even with hasZoom', () => {
600685
const onIndexChange = vi.fn();
601686
render(
@@ -631,9 +716,7 @@ describe('Lightbox', () => {
631716
const img = screen.getByAltText('Image B');
632717
// ArrowRight still reveals what is to the right of the photo.
633718
fireEvent.keyDown(dialog, {key: 'ArrowRight'});
634-
expect(img.getAttribute('style') ?? '').toContain(
635-
'translate(-25px, 0px)',
636-
);
719+
expect(photoTransform(img).translate).toBe('-450px -200px');
637720
expect(onIndexChange).not.toHaveBeenCalled();
638721
});
639722

@@ -746,7 +829,91 @@ describe('Lightbox', () => {
746829
});
747830
});
748831

832+
describe('Lightbox touch zoom (synthetic touches)', () => {
833+
let restoreLayout: () => void = () => {};
834+
beforeEach(() => {
835+
restoreLayout = stubStageLayout();
836+
});
837+
afterEach(() => {
838+
restoreLayout();
839+
});
840+
841+
interface Contact {
842+
id: number;
843+
x: number;
844+
y: number;
845+
}
846+
847+
/** A touch event as a browser sends it: who is down, and who changed. */
848+
function touch(
849+
type: 'touchstart' | 'touchmove' | 'touchend',
850+
target: Element,
851+
down: Contact[],
852+
changed: Contact[],
853+
time: number,
854+
): void {
855+
const event = new Event(type, {bubbles: true, cancelable: true});
856+
const entry = (contact: Contact) => ({
857+
identifier: contact.id,
858+
clientX: contact.x,
859+
clientY: contact.y,
860+
target,
861+
});
862+
Object.defineProperty(event, 'touches', {value: down.map(entry)});
863+
Object.defineProperty(event, 'changedTouches', {value: changed.map(entry)});
864+
Object.defineProperty(event, 'timeStamp', {value: time});
865+
target.dispatchEvent(event);
866+
}
867+
868+
it('keeps panning with the finger left down after a pinch, without a jump', () => {
869+
render(
870+
<Lightbox
871+
isOpen={true}
872+
onOpenChange={() => {}}
873+
media={{src: '/photo.jpg', alt: 'Photo'}}
874+
hasZoom
875+
/>,
876+
);
877+
const stage = screen.getByRole('button', {name: 'Zoom'});
878+
const img = screen.getByAltText('Photo');
879+
const x = () => parseFloat(photoTransform(img).translate || '0');
880+
// Two fingers land on the photo, spread (100 → 140 px) and drift left
881+
// together (the midpoint 200 → 180).
882+
let a: Contact = {id: 1, x: 150, y: 300};
883+
let b: Contact = {id: 2, x: 250, y: 300};
884+
touch('touchstart', stage, [a], [a], 0);
885+
touch('touchstart', stage, [a, b], [b], 0);
886+
for (let i = 1; i <= 10; i++) {
887+
a = {...a, x: 150 - 4 * i};
888+
b = {...b, x: 250};
889+
touch('touchmove', stage, [a, b], [a, b], i * 16);
890+
}
891+
const scaled = parseFloat(photoTransform(img).scale);
892+
expect(scaled).toBeGreaterThan(1.2);
893+
// The right finger lifts: nothing moves.
894+
const beforeLift = x();
895+
touch('touchend', stage, [a], [b], 11 * 16);
896+
expect(x()).toBeCloseTo(beforeLift, 6);
897+
// The left finger drags on 40 px: the photo follows it 1:1, zoom kept.
898+
for (let i = 1; i <= 8; i++) {
899+
a = {...a, x: a.x - 5};
900+
touch('touchmove', stage, [a], [a], (11 + i) * 16);
901+
}
902+
expect(x()).toBeCloseTo(beforeLift - 40, 6);
903+
expect(parseFloat(photoTransform(img).scale)).toBeCloseTo(scaled, 6);
904+
touch('touchend', stage, [], [a], 20 * 16);
905+
});
906+
});
907+
749908
describe('Lightbox zoom reset timing', () => {
909+
let restoreLayout: () => void = () => {};
910+
beforeEach(() => {
911+
restoreLayout = stubStageLayout();
912+
});
913+
afterEach(() => {
914+
restoreLayout();
915+
});
916+
750917
it('shows the next image unzoomed in the same commit that changes it', () => {
751918
const media = [
752919
{src: '/a.jpg', alt: 'Image A'},
@@ -781,6 +948,12 @@ describe('Lightbox zoom reset timing', () => {
781948
'aria-pressed',
782949
'false',
783950
);
951+
// The photo element is reused for the next image: it is back at the
952+
// fitted size before that image paints.
953+
expect(photoTransform(screen.getByAltText('Image B'))).toEqual({
954+
translate: '0px 0px',
955+
scale: '1 1',
956+
});
784957
});
785958
});
786959

0 commit comments

Comments
 (0)