-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImageLightbox.tsx
More file actions
373 lines (359 loc) · 12.8 KB
/
Copy pathImageLightbox.tsx
File metadata and controls
373 lines (359 loc) · 12.8 KB
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
import React, { useEffect, useRef, useState } from "react";
import {
Box,
CircularProgress,
IconButton,
Modal,
Typography,
} from "@mui/material";
import ArrowUpwardIcon from "@mui/icons-material/ArrowUpward";
import CheckIcon from "@mui/icons-material/Check";
import { useSwipeable } from "react-swipeable";
import type { CaptionedImage, ImageCrop } from "../util/types";
import { SuspenseAppImage } from "./AppImage";
import CropOverlay from "./CropOverlay";
const SWIPE_THRESHOLD = 50;
type ImageLightboxProps = {
images: CaptionedImage[];
initialIndex: number;
onClose: () => void;
onIndexChange?: (index: number) => void;
currentThumbnailUrl?: string;
onSetAsThumbnail?: (image: CaptionedImage) => Promise<void>;
onCropSave?: (image: CaptionedImage, crop: ImageCrop) => Promise<void>;
canEditImage?: (index: number) => boolean;
footerActions?: (opts: {
index: number;
onCrop?: () => void;
cropAvailable?: boolean;
onSetAsThumbnail?: () => Promise<void>;
isCurrentThumbnail: boolean;
}) => React.ReactNode;
};
export default function ImageLightbox({
images,
initialIndex,
onClose,
onIndexChange,
currentThumbnailUrl,
onSetAsThumbnail,
onCropSave,
canEditImage,
footerActions,
}: ImageLightboxProps) {
const [index, setIndex] = useState(initialIndex);
// Notify caller when index changes due to user navigation (swipe, arrow,
// thumbnail). Suppressed when the index already matches the URL-driven
// initialIndex so we don't write a duplicate history entry for an
// already-current URL. Refs are updated in effects (never during render);
// the ref-sync effects are declared first so they run before the notify
// effect within the same commit.
const onIndexChangeRef = useRef(onIndexChange);
useEffect(() => {
onIndexChangeRef.current = onIndexChange;
});
const initialIndexRef = useRef(initialIndex);
useEffect(() => {
initialIndexRef.current = initialIndex;
});
const mountedRef = useRef(false);
useEffect(() => {
if (!mountedRef.current) { mountedRef.current = true; return; }
if (index === initialIndexRef.current) return;
onIndexChangeRef.current?.(index);
}, [index]);
const [dragDeltaX, setDragDeltaX] = useState(0);
const [dragDeltaY, setDragDeltaY] = useState(0);
const [cropMode, setCropMode] = useState(false);
const [optimisticCroppedUrl, setOptimisticCroppedUrl] = useState<string | null>(null);
// "pending" = spinner shown while backend task runs; "done" = checkmark shown briefly
const [cropSaveStatus, setCropSaveStatus] = useState<"pending" | "done" | null>(null);
const image = images[index];
useEffect(() => {
setOptimisticCroppedUrl(prev => {
if (prev) URL.revokeObjectURL(prev);
return null;
});
setCropSaveStatus(null);
}, [image.image_id]);
// When the real cropped_url arrives, transition spinner → checkmark → cleanup.
// cropSaveStatus is intentionally read from the closure of the current render
// (not added to deps) — it will be current when image.cropped_url changes.
useEffect(() => {
if (!image.cropped_url) return;
// Guard: only act if we're tracking an in-flight save (canvas may have failed,
// leaving optimisticCroppedUrl null but cropSaveStatus still "pending").
if (!optimisticCroppedUrl && cropSaveStatus !== "pending") return;
if (optimisticCroppedUrl) {
URL.revokeObjectURL(optimisticCroppedUrl);
setOptimisticCroppedUrl(null);
}
setCropSaveStatus("done");
const t = setTimeout(() => setCropSaveStatus(null), 1200);
return () => clearTimeout(t);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [image.cropped_url]);
const [prevInitialIndex, setPrevInitialIndex] = useState(initialIndex);
// Sync to URL-driven index changes (e.g. browser Back while lightbox is
// open). The notify effect skips this update because the resulting index
// equals the URL's initialIndex.
if (initialIndex !== prevInitialIndex) {
setPrevInitialIndex(initialIndex);
setIndex(initialIndex);
}
function prev() {
setIndex((i) => {
if (i > 0) { setCropMode(false); return i - 1; }
return i;
});
}
function next() {
setIndex((i) => {
if (i < images.length - 1) { setCropMode(false); return i + 1; }
return i;
});
}
const swipeHandlers = useSwipeable({
onSwiping: ({ deltaX, deltaY, dir }) => {
if (dir === "Up" || dir === "Down") {
// Resist downward swipes — only upward closes
setDragDeltaY(dir === "Down" ? deltaY * 0.25 : deltaY);
} else {
// Resist at boundaries — dampen drag past the first/last image
if ((index === 0 && dir === "Right") || (index === images.length - 1 && dir === "Left")) {
setDragDeltaX(deltaX * 0.25);
} else {
setDragDeltaX(deltaX);
}
}
},
onSwipedLeft: ({ absX }) => {
setDragDeltaX(0);
if (absX >= SWIPE_THRESHOLD) next();
},
onSwipedRight: ({ absX }) => {
setDragDeltaX(0);
if (absX >= SWIPE_THRESHOLD) prev();
},
onSwipedUp: () => { setDragDeltaY(0); onClose(); },
onSwipedDown: () => setDragDeltaY(0),
onTouchEndOrOnMouseUp: () => {
setDragDeltaX(0);
setDragDeltaY(0);
},
trackMouse: false,
trackTouch: true,
delta: 10,
preventScrollOnSwipe: true,
});
const isCurrentThumbnail =
!!currentThumbnailUrl && image.url === currentThumbnailUrl;
return (
<Modal
open
onClose={onClose}
slotProps={{ backdrop: { sx: { backgroundColor: "rgba(0,0,0,0.92)" } } }}
>
<Box
data-testid="lightbox-backdrop"
onClick={cropMode ? undefined : onClose}
sx={{
position: "fixed",
inset: 0,
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
gap: 2,
outline: "none",
}}
>
{/* Swipe-up-to-close hint overlay */}
{dragDeltaY < 0 && (
<Box
sx={{
position: "fixed",
top: 0,
left: 0,
right: 0,
display: "flex",
flexDirection: "column",
alignItems: "center",
pt: 2,
gap: 0.5,
opacity: Math.min(1, Math.abs(dragDeltaY) / 80),
pointerEvents: "none",
color: "white",
}}
>
<ArrowUpwardIcon fontSize="small" />
<Typography variant="caption" sx={{ letterSpacing: 1, textTransform: "uppercase" }}>
drag to close
</Typography>
</Box>
)}
{cropMode ? (
<CropOverlay
url={image.url}
initialCrop={image.crop ?? null}
onSave={async (crop) => {
setCropMode(false);
setCropSaveStatus("pending");
try {
const img = new Image();
img.crossOrigin = "anonymous";
img.src = image.url;
await img.decode();
const srcX = crop.x * img.naturalWidth;
const srcY = crop.y * img.naturalHeight;
const srcW = crop.width * img.naturalWidth;
const srcH = crop.height * img.naturalHeight;
const canvas = document.createElement("canvas");
canvas.width = srcW;
canvas.height = srcH;
canvas.getContext("2d")!.drawImage(img, srcX, srcY, srcW, srcH, 0, 0, srcW, srcH);
const blob = await new Promise<Blob>((res) =>
canvas.toBlob(res as BlobCallback, "image/jpeg", 0.92)
);
setOptimisticCroppedUrl(URL.createObjectURL(blob));
} catch {
// CORS failure or canvas unavailable — no optimistic preview
}
try {
await onCropSave?.(image, crop);
} catch (err) {
// API save failed — revoke blob and clear optimistic state so
// the spinner doesn't stay stuck with no real crop incoming
setOptimisticCroppedUrl(prev => { if (prev) URL.revokeObjectURL(prev); return null; });
setCropSaveStatus(null);
throw err;
}
}}
onCancel={() => setCropMode(false)}
/>
) : (
<Box
{...swipeHandlers}
data-testid="lightbox-swipe-area"
onClick={(e) => { e.stopPropagation(); onClose(); }}
sx={{ touchAction: "pan-y", cursor: images.length > 1 ? "grab" : undefined }}
>
<Box
onClick={(e) => e.stopPropagation()}
sx={{
transform: `translate(${dragDeltaX}px, ${dragDeltaY}px)`,
transition: dragDeltaX === 0 && dragDeltaY === 0 ? "transform 0.25s ease" : "none",
width: "fit-content",
position: "relative",
}}
>
<SuspenseAppImage
key={index}
url={image.url}
croppedUrl={optimisticCroppedUrl ?? image.cropped_url}
crop={image.crop}
r2Key={image.r2_key}
cropTaskFailed={image.crop_task_failed}
alt={image.caption || "Pottery image"}
context="lightbox"
style={{
maxWidth: "90vw",
maxHeight: "80vh",
objectFit: "contain",
borderRadius: 4,
userSelect: "none",
pointerEvents: "none",
}}
/>
{cropSaveStatus && (
<Box
sx={{
position: "absolute",
bottom: 8,
right: 8,
width: 28,
height: 28,
borderRadius: "50%",
backgroundColor: "rgba(0,0,0,0.55)",
display: "flex",
alignItems: "center",
justifyContent: "center",
pointerEvents: "none",
}}
>
{cropSaveStatus === "pending"
? <CircularProgress size={16} sx={{ color: "white" }} />
: <CheckIcon sx={{ fontSize: 16, color: "white" }} />}
</Box>
)}
</Box>
</Box>
)}
{!cropMode && footerActions && (
<Box onClick={(e) => e.stopPropagation()} sx={{ alignSelf: "center" }}>
{footerActions({
index,
onCrop: onCropSave && canEditImage?.(index) && image.image_id
? () => setCropMode(true)
: undefined,
cropAvailable: !!onCropSave,
onSetAsThumbnail: onSetAsThumbnail ? () => onSetAsThumbnail(image) : undefined,
isCurrentThumbnail,
})}
</Box>
)}
{/* Nav row — centered */}
{!cropMode && images.length > 1 && (
<Box
onClick={(e) => e.stopPropagation()}
sx={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 0.5 }}
>
<IconButton
onClick={prev}
disabled={index === 0}
size="small"
sx={{ color: "white", display: { xs: "none", sm: "inline-flex" } }}
aria-label="previous image"
>
←
</IconButton>
<Box sx={{ display: "flex", gap: 0.75, alignItems: "center" }}>
{images.map((_, i) => (
<Box
key={i}
onClick={() => setIndex(i)}
sx={{
width: i === index ? 10 : 7,
height: i === index ? 10 : 7,
borderRadius: "50%",
backgroundColor: i === index ? "white" : "rgba(255,255,255,0.35)",
cursor: "pointer",
transition: "all 0.2s ease",
flexShrink: 0,
}}
role="button"
aria-label={`Go to image ${i + 1}`}
/>
))}
</Box>
<IconButton
onClick={next}
disabled={index === images.length - 1}
size="small"
sx={{ color: "white", display: { xs: "none", sm: "inline-flex" } }}
aria-label="next image"
>
→
</IconButton>
<Typography
variant="caption"
sx={{ color: "rgba(255,255,255,0.5)", display: { xs: "none", sm: "block" }, ml: 0.5 }}
>
{index + 1} / {images.length}
</Typography>
</Box>
)}
</Box>
</Modal>
);
}