-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathZoomImage.tsx
270 lines (239 loc) · 8.68 KB
/
ZoomImage.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
'use client';
import clsx from 'clsx';
import { Icon } from '@gitbook/icons';
import React from 'react';
import ReactDOM from 'react-dom';
import styles from './ZoomImage.module.css';
/**
* Replacement for an <img> tag that allows zooming.
* The implementation uses the experimental View Transition API in Chrome for a smooth transition.
*/
export function ZoomImage(
props: React.ComponentPropsWithoutRef<'img'> & {
src: string;
},
) {
const { src, alt, width } = props;
const imgRef = React.useRef<HTMLImageElement>(null);
const [zoomable, setZoomable] = React.useState(false);
const [active, setActive] = React.useState(false);
const [opened, setOpened] = React.useState(false);
const [placeholderRect, setPlaceholderRect] = React.useState<DOMRect | null>(null);
// Only allow zooming when image will not actually be larger and on mobile
React.useEffect(() => {
if (isTouchDevice()) {
return;
}
const imageWidth = typeof width === 'number' ? width : 0;
let viewWidth = 0;
const mediaQueryList = window.matchMedia('(min-width: 768px)');
const resizeObserver =
typeof ResizeObserver !== 'undefined'
? new ResizeObserver((entries) => {
const imgEntry = entries[0];
// Since the image is removed from the DOM when the modal is opened,
// We only care when the size is defined.
if (imgEntry && imgEntry.contentRect.width !== 0) {
viewWidth = entries[0]?.contentRect.width;
setPlaceholderRect(entries[0].contentRect);
onChange();
}
})
: null;
const onChange = () => {
if (!mediaQueryList.matches) {
// Don't allow zooming on mobile
setZoomable(false);
} else if (resizeObserver && imageWidth && viewWidth && imageWidth <= viewWidth) {
// Image can't be zoomed if it's already rendered as it's largest size
setZoomable(false);
} else {
setZoomable(true);
}
};
if ('addEventListener' in mediaQueryList) {
mediaQueryList.addEventListener('change', onChange);
}
if (imgRef.current) {
resizeObserver?.observe(imgRef.current);
}
if (!resizeObserver) {
// When resizeObserver is available, it'll take care of calling the changelog as soon as the element is observed
onChange();
}
return () => {
resizeObserver?.disconnect();
if ('removeEventListener' in mediaQueryList) {
mediaQueryList.removeEventListener('change', onChange);
}
};
}, [imgRef, width]);
// Preload the image that will be displayed in the modal
if (zoomable) {
ReactDOM.preload(src, {
as: 'image',
});
}
const preloadImage = React.useCallback(
(onLoad?: () => void) => {
const image = new Image();
image.src = src;
image.onload = () => {
onLoad?.();
};
},
[src],
);
// When closing the modal, animate the transition back to the original image
const onClose = React.useCallback(() => {
startViewTransition(
() => {
setOpened(false);
},
() => {
setActive(false);
},
);
}, []);
return (
<>
{opened ? (
<>
{placeholderRect ? (
// Placeholder to keep the layout stable when the image is removed from the DOM
<span
style={{
display: 'block',
width: placeholderRect.width,
height: placeholderRect.height,
}}
/>
) : null}
{ReactDOM.createPortal(
<ZoomImageModal
src={src}
crossOrigin={props.crossOrigin}
alt={alt ?? ''}
onClose={onClose}
/>,
document.body,
)}
</>
) : (
// When zooming, remove the image from the DOM to let the browser animates it with View Transition.
<img
data-testid="zoom-image"
ref={imgRef}
{...props}
alt={alt ?? ''}
onMouseEnter={() => {
if (zoomable) {
preloadImage();
}
}}
onClick={() => {
if (!zoomable) {
return;
}
// Preload the image before opening the modal to ensure the animation is smooth
preloadImage(() => {
const change = () => {
setOpened(true);
};
ReactDOM.flushSync(() => setActive(true));
startViewTransition(change);
});
}}
className={clsx(
props.className,
zoomable ? styles.zoomImg : null,
active ? styles.zoomImageActive : null,
)}
/>
)}
</>
);
}
function ZoomImageModal(props: {
src: string;
alt: string;
crossOrigin: React.ComponentPropsWithoutRef<'img'>['crossOrigin'];
onClose: () => void;
}) {
const { src, alt, crossOrigin, onClose } = props;
const buttonRef = React.useRef<HTMLButtonElement>(null);
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
onClose();
}
};
document.addEventListener('keydown', handleKeyDown);
return () => {
document.removeEventListener('keydown', handleKeyDown);
};
}, [onClose]);
React.useEffect(() => {
buttonRef.current?.focus();
}, []);
return (
<div
data-testid="zoom-image-modal"
className={clsx(
styles.zoomModal,
'fixed inset-0 z-50 flex items-center justify-center bg-light dark:bg-dark p-8',
)}
onClick={onClose}
>
<img
src={src}
alt={alt}
crossOrigin={crossOrigin}
className="max-w-full max-h-full object-contain bg-light dark:bg-dark"
/>
<button
ref={buttonRef}
className="absolute top-5 right-5 flex flex-row items-center justify-center text-sm text-dark/6 dark:text-light/5 hover:text-primary p-4 dark:text-light/5 rounded-full bg-white dark:bg-dark/3 shadow-sm hover:shadow-md border-slate-300 dark:border-dark/2 border dark:text-light/5 hover:text-primary p-4 dark:text-light/5 rounded-full bg-white dark:bg-dark/3 shadow-sm hover:shadow-md border-slate-300 dark:border-dark/2 border"
onClick={onClose}
>
<Icon icon="compress-wide" className="size-5" />
</button>
</div>
);
}
function startViewTransition(callback: () => void, onEnd?: () => void) {
if (document.startViewTransition) {
try {
const transition = document.startViewTransition(() => {
ReactDOM.flushSync(() => callback());
});
transition.finished.then(() => {
if (onEnd) {
onEnd();
}
});
} catch (error) {
// Safari can throw an error if another transition is already in progress
if (
error instanceof Error &&
(error.name === 'AbortError' || error.name === 'InvalidStateError')
) {
callback();
onEnd?.();
return;
}
throw error;
}
} else {
callback();
onEnd?.();
}
}
function isTouchDevice(): boolean {
return (
'ontouchstart' in window ||
navigator.maxTouchPoints > 0 ||
// @ts-ignore
navigator.msMaxTouchPoints > 0
);
}