Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 | 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 195x 195x 195x 2x 15x 15x 2x 180x 180x 20x 15x 196x 216x 216x 216x 216x 216x 216x 216x 216x 216x 216x 216x 216x 216x 216x 216x 216x 216x 216x 216x 216x 17x 216x 18x 1x 1x 216x 216x 216x 216x 216x 216x 15x 15x 15x 216x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 2x 1x 3x 3x 216x 216x 216x 216x 216x 216x 216x 216x 216x 216x 1x 215x 15x 15x 15x 15x 43x 15x 15x | import { AddPhotoAlternate, InfoOutlined } from "@mui/icons-material";
import {
Box,
ImageList,
styled,
Typography,
useMediaQuery,
useTheme,
} from "@mui/material";
import Alert from "components/Alert";
import BetaFlag from "components/BetaFlag";
import Button from "components/Button";
import CircularProgress from "components/CircularProgress";
import {
useAddPhotoToGallery,
useGallery,
useGalleryEditInfo,
useMovePhoto,
useRemovePhotoFromGallery,
} from "features/profile/hooks/useGallery";
import { useTranslation } from "i18n";
import { PROFILE } from "i18n/namespaces";
import Sentry from "platform/sentry";
import React, { useEffect, useRef, useState } from "react";
import { settingsRoute } from "routes";
import { service } from "service";
import { base64ToFile, useNativeImagePicker } from "utils/nativeLink";
import GalleryItem, { DropPlaceholder } from "./GalleryItem";
export interface GalleryItemData {
itemId: number;
fullUrl: string;
thumbnailUrl: string;
caption: string;
}
interface GalleryEditorProps {
galleryId: number | undefined;
userId?: number;
title?: string;
description?: string;
hasStrongVerification?: boolean;
}
const Root = styled(Box)(({ theme }) => ({
width: "100%",
}));
const Header = styled(Box)(({ theme }) => ({
display: "flex",
flexDirection: "column",
gap: theme.spacing(1),
marginBottom: theme.spacing(2),
}));
const HeaderRow = styled(Box)(({ theme }) => ({
display: "flex",
alignItems: "center",
justifyContent: "space-between",
flexWrap: "wrap",
gap: theme.spacing(2),
}));
const InfoBox = styled(Box)(({ theme }) => ({
display: "flex",
alignItems: "center",
gap: theme.spacing(1),
padding: theme.spacing(1.5, 2),
backgroundColor: theme.palette.grey[50],
borderRadius: theme.shape.borderRadius,
border: `1px solid ${theme.palette.grey[200]}`,
}));
const StyledImageList = styled(ImageList)(({ theme }) => ({
width: "100%",
borderRadius: theme.shape.borderRadius * 2,
margin: 0,
}));
const UploadButton = styled(Button)(({ theme }) => ({
minWidth: 140,
}));
const HiddenInput = styled("input")({
display: "none",
});
const EmptyState = styled(Box)(({ theme }) => ({
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
padding: theme.spacing(6),
backgroundColor: theme.palette.grey[50],
borderRadius: theme.shape.borderRadius * 2,
border: `2px dashed ${theme.palette.grey[300]}`,
textAlign: "center",
cursor: "pointer",
transition: "all 0.2s ease",
"&:hover": {
backgroundColor: theme.palette.grey[100],
borderColor: theme.palette.primary.main,
},
}));
const EmptyStateIcon = styled(AddPhotoAlternate)(({ theme }) => ({
fontSize: 64,
color: theme.palette.grey[400],
marginBottom: theme.spacing(2),
}));
const LoadingContainer = styled(Box)(({ theme }) => ({
display: "flex",
alignItems: "center",
justifyContent: "center",
padding: theme.spacing(4),
}));
const PhotoCountBadge = styled(Typography)(({ theme }) => ({
color: theme.palette.text.secondary,
fontSize: "0.875rem",
}));
export default function GalleryEditor({
galleryId,
userId,
title,
description,
hasStrongVerification,
}: GalleryEditorProps) {
const { t } = useTranslation([PROFILE]);
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down("sm"));
const isTablet = useMediaQuery(theme.breakpoints.down("md"));
const inputRef = useRef<HTMLInputElement>(null);
const [draggedItemId, setDraggedItemId] = useState<number | null>(null);
const [dropIndex, setDropIndex] = useState<number | null>(null);
const [isUploading, setIsUploading] = useState(false);
const [uploadError, setUploadError] = useState<string | null>(null);
const [deletingItemId, setDeletingItemId] = useState<number | null>(null);
const [showReorderSuccess, setShowReorderSuccess] = useState(false);
const [showUploadSuccess, setShowUploadSuccess] = useState(false);
// Touch support for mobile
const [touchStartItemId, setTouchStartItemId] = useState<number | null>(null);
// Native image picker for mobile app
const { isNative, pickImage } = useNativeImagePicker();
const { data: gallery, isLoading: galleryLoading } = useGallery(galleryId);
const { data: editInfo, isLoading: editInfoLoading } =
useGalleryEditInfo(galleryId);
const addPhotoMutation = useAddPhotoToGallery(galleryId || 0, userId);
const removePhotoMutation = useRemovePhotoFromGallery(galleryId || 0, userId);
const movePhotoMutation = useMovePhoto(galleryId || 0, userId);
// Auto-dismiss success messages after 3 seconds
useEffect(() => {
Iif (showReorderSuccess) {
const timer = setTimeout(() => {
setShowReorderSuccess(false);
}, 3000);
return () => clearTimeout(timer);
}
}, [showReorderSuccess]);
useEffect(() => {
if (showUploadSuccess) {
const timer = setTimeout(() => {
setShowUploadSuccess(false);
}, 3000);
return () => clearTimeout(timer);
}
}, [showUploadSuccess]);
const canEdit = gallery?.canEdit ?? false;
const photos: GalleryItemData[] = (gallery?.photosList ??
[]) as GalleryItemData[];
const maxPhotos = editInfo?.maxPhotos ?? 0;
const currentPhotoCount = photos.length;
const canAddMore = currentPhotoCount < maxPhotos;
// Get column count based on screen size
const getCols = () => {
Iif (isMobile) return 2;
Iif (isTablet) return 3;
return 4;
};
const handleUploadClick = async () => {
// Use native image picker in mobile app (WebView file input crashes)
if (isNative) {
setIsUploading(true);
setUploadError(null);
setShowUploadSuccess(false);
try {
const result = await pickImage();
if (result.success) {
// Convert base64 to File and upload using existing service
const file = base64ToFile(
result.imageBase64,
result.mimeType,
`photo.${result.mimeType.split("/")[1] || "jpg"}`,
);
const uploadResult = await service.api.uploadFile(file);
await addPhotoMutation.mutateAsync({ uploadKey: uploadResult.key });
setShowUploadSuccess(true);
} else if (!result.canceled) {
setUploadError(result.error || "Upload failed");
}
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : "Upload failed";
setUploadError(errorMessage);
Sentry.captureException(error, {
tags: { component: "GalleryEditor", native: true },
});
} finally {
setIsUploading(false);
}
return;
}
// Standard web file input
Iif (inputRef.current) {
inputRef.current.value = "";
inputRef.current.click();
}
};
const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
setUploadError(null);
setShowUploadSuccess(false);
Iif (!e.target.files?.length) return;
const file = e.target.files[0];
setIsUploading(true);
try {
const uploadResult = await service.api.uploadFile(file);
await addPhotoMutation.mutateAsync({ uploadKey: uploadResult.key });
setShowUploadSuccess(true);
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : "Upload failed";
setUploadError(errorMessage);
Sentry.captureException(error, {
tags: { component: "GalleryEditor" },
});
} finally {
setIsUploading(false);
}
};
const handleDelete = async (itemId: number) => {
setDeletingItemId(itemId);
try {
await removePhotoMutation.mutateAsync(itemId);
} catch (error) {
Sentry.captureException(error, {
tags: { component: "GalleryEditor" },
});
} finally {
setDeletingItemId(null);
}
};
const handleDragStart = (e: React.DragEvent, itemId: number) => {
setDraggedItemId(itemId);
e.dataTransfer.effectAllowed = "move";
e.dataTransfer.setData("text/plain", String(itemId));
};
const handleDragEnd = () => {
setDraggedItemId(null);
setDropIndex(null);
};
const handleDragOver = (
e: React.DragEvent,
targetItemId: number,
targetIndex: number,
) => {
e.preventDefault();
e.dataTransfer.dropEffect = "move";
Iif (!draggedItemId) return;
const draggedIndex = photos.findIndex((p) => p.itemId === draggedItemId);
Iif (draggedIndex === -1) return;
// Determine drop position based on cursor position within target element
const rect = e.currentTarget.getBoundingClientRect();
const x = e.clientX - rect.left;
const isLeftHalf = x < rect.width / 2;
// Calculate the drop index
let newDropIndex: number;
if (isLeftHalf) {
newDropIndex = targetIndex;
} else {
newDropIndex = targetIndex + 1;
}
// Adjust for the fact that dragged item will be removed from its position
Iif (draggedIndex < newDropIndex) {
newDropIndex -= 1;
}
// Don't show indicator at the current position
if (newDropIndex === draggedIndex) {
setDropIndex(null);
} else {
setDropIndex(newDropIndex);
}
};
const handleDrop = async (e: React.DragEvent) => {
e.preventDefault();
const draggedId = draggedItemId;
const currentDropIndex = dropIndex;
setDraggedItemId(null);
setDropIndex(null);
Iif (!draggedId || currentDropIndex === null) return;
const draggedIndex = photos.findIndex((p) => p.itemId === draggedId);
Iif (draggedIndex === -1 || currentDropIndex === draggedIndex) return;
// Determine afterItemId based on dropIndex
let afterItemId: number;
if (currentDropIndex === 0) {
afterItemId = 0; // Move to first position
} else {
// Get the item that will be before our dropped item
// If dragging forward, account for the shift
const beforeIndex =
draggedIndex < currentDropIndex
? currentDropIndex
: currentDropIndex - 1;
afterItemId = photos[beforeIndex].itemId;
}
try {
await movePhotoMutation.mutateAsync({
itemId: draggedId,
afterItemId,
});
setShowReorderSuccess(true);
} catch (error) {
Sentry.captureException(error, {
tags: { component: "GalleryEditor" },
});
}
};
// Touch handlers for mobile drag and drop
const handleTouchStart = (e: React.TouchEvent, itemId: number) => {
Iif (!canEdit) return;
setTouchStartItemId(itemId);
setDraggedItemId(itemId);
};
const handleTouchMove = (e: React.TouchEvent) => {
Iif (!touchStartItemId) return;
const touch = e.touches[0];
const draggedIndex = photos.findIndex((p) => p.itemId === touchStartItemId);
Iif (draggedIndex === -1) return;
// Find which item we're currently over
const element = document.elementFromPoint(touch.clientX, touch.clientY);
const imageListItem = element?.closest("[data-item-id]");
Iif (imageListItem) {
const itemId = Number(imageListItem.getAttribute("data-item-id"));
const targetIndex = photos.findIndex((p) => p.itemId === itemId);
Iif (itemId && targetIndex !== -1) {
// Determine drop position based on touch position within the element
const rect = imageListItem.getBoundingClientRect();
const x = touch.clientX - rect.left;
const isLeftHalf = x < rect.width / 2;
// Calculate new drop index
let newDropIndex: number;
if (isLeftHalf) {
newDropIndex = targetIndex;
} else {
newDropIndex = targetIndex + 1;
}
// Adjust for the dragged item being removed
Iif (draggedIndex < newDropIndex) {
newDropIndex -= 1;
}
// Don't show indicator at current position
if (newDropIndex === draggedIndex) {
setDropIndex(null);
} else {
setDropIndex(newDropIndex);
}
}
}
};
const handleTouchEnd = async () => {
Iif (!touchStartItemId || dropIndex === null) {
setTouchStartItemId(null);
setDraggedItemId(null);
setDropIndex(null);
return;
}
const draggedId = touchStartItemId;
const currentDropIndex = dropIndex;
setTouchStartItemId(null);
setDraggedItemId(null);
setDropIndex(null);
const draggedIndex = photos.findIndex((p) => p.itemId === draggedId);
Iif (draggedIndex === -1 || currentDropIndex === draggedIndex) return;
// Determine afterItemId based on dropIndex
let afterItemId: number;
if (currentDropIndex === 0) {
afterItemId = 0;
} else {
const beforeIndex =
draggedIndex < currentDropIndex
? currentDropIndex
: currentDropIndex - 1;
afterItemId = photos[beforeIndex].itemId;
}
try {
await movePhotoMutation.mutateAsync({
itemId: draggedId,
afterItemId,
});
setShowReorderSuccess(true);
} catch (error) {
Sentry.captureException(error, {
tags: { component: "GalleryEditor" },
});
}
};
if (!galleryId) {
return null;
}
if (galleryLoading || editInfoLoading) {
return (
<LoadingContainer>
<CircularProgress />
</LoadingContainer>
);
}
return (
<Root>
<Header>
<HeaderRow>
<Box>
{title && (
<Box sx={{ display: "flex", alignItems: "center" }}>
<Typography variant="h3" gutterBottom sx={{ mb: 0 }}>
{title}
</Typography>
<BetaFlag />
</Box>
)}
{description && (
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
{description}
</Typography>
)}
</Box>
{canEdit && (
<Box sx={{ display: "flex", alignItems: "center", gap: 2 }}>
<PhotoCountBadge>
{t("profile:gallery.photo_count", {
current: currentPhotoCount,
total: maxPhotos,
})}
</PhotoCountBadge>
<UploadButton
variant="contained"
color="primary"
startIcon={
isUploading ? (
<CircularProgress size={16} />
) : (
<AddPhotoAlternate />
)
}
onClick={handleUploadClick}
disabled={!canAddMore || isUploading}
>
{isUploading
? t("profile:gallery.uploading")
: t("profile:gallery.add_photo")}
</UploadButton>
</Box>
)}
</HeaderRow>
{canEdit && photos.length > 0 && (
<>
{!canAddMore && !hasStrongVerification && (
<InfoBox
sx={{
backgroundColor: "var(--mui-palette-grey-50)",
border: `1px solid var(--mui-palette-grey-300)`,
marginTop: 1,
}}
>
<InfoOutlined fontSize="small" sx={{ color: "primary.main" }} />
<Typography
variant="body2"
color="var(--mui-palette-text-secondary)"
>
{t("profile:gallery.verification_required_for_more_photos")}{" "}
<a
href={`${settingsRoute}#strong-verification`}
style={{ color: "var(--mui-palette-primary-main)" }}
target="_blank"
rel="noopener noreferrer"
>
{t("profile:gallery.get_verified")}
</a>
</Typography>
</InfoBox>
)}
</>
)}
</Header>
<HiddenInput
ref={inputRef}
type="file"
accept="image/jpeg,image/png,image/gif"
onChange={handleFileChange}
aria-label={t("profile:gallery.select_photo")}
/>
{showReorderSuccess && (
<Alert severity="success" sx={{ mb: 2 }}>
{t("profile:gallery.reorder_success")}
</Alert>
)}
{showUploadSuccess && (
<Alert severity="success" sx={{ mb: 2 }}>
{t("profile:gallery.upload_success")}
</Alert>
)}
{uploadError && (
<Alert severity="error" sx={{ mb: 2 }}>
{uploadError}
</Alert>
)}
{photos.length === 0 ? (
canEdit ? (
<EmptyState onClick={handleUploadClick}>
<EmptyStateIcon />
<Typography variant="h3" gutterBottom>
{t("profile:gallery.empty_title")}
</Typography>
<Typography variant="body2" color="text.secondary">
{t("profile:gallery.empty_description")}
</Typography>
</EmptyState>
) : (
<EmptyState sx={{ cursor: "default", "&:hover": {} }}>
<EmptyStateIcon />
<Typography variant="body2" color="text.secondary">
{t("profile:gallery.no_photos")}
</Typography>
</EmptyState>
)
) : (
<StyledImageList
cols={getCols()}
gap={12}
rowHeight={180}
onDragOver={(e) => e.preventDefault()}
onDrop={handleDrop}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
>
{(() => {
const draggedIndex = draggedItemId
? photos.findIndex((p) => p.itemId === draggedItemId)
: -1;
// Determine if this is a touch drag (simpler preview) or mouse drag (full reorder preview)
const isTouchDrag = touchStartItemId !== null;
// For MOUSE drag: full reorder preview with items moving
Iif (!isTouchDrag && dropIndex !== null && draggedIndex !== -1) {
// Build a reordered array with placeholder
const reorderedItems: (GalleryItemData | "placeholder")[] = [];
let photoIndex = 0;
for (let i = 0; i <= photos.length; i++) {
Iif (i === dropIndex) {
// Insert placeholder at drop position
reorderedItems.push("placeholder");
}
Iif (photoIndex < photos.length) {
// Skip the dragged item in its original position
Iif (photos[photoIndex].itemId === draggedItemId) {
photoIndex++;
}
Iif (photoIndex < photos.length) {
reorderedItems.push(photos[photoIndex]);
photoIndex++;
}
}
}
// Find index of first real item (not placeholder)
const firstRealItemIndex = reorderedItems.findIndex(
(i) => i !== "placeholder",
);
return reorderedItems.map((item, renderIndex) => {
Iif (item === "placeholder") {
return (
<DropPlaceholder
key="drop-placeholder"
onDragOver={(e) => e.preventDefault()}
/>
);
}
// Find original index for drag handlers
const originalIndex = photos.findIndex(
(p) => p.itemId === item.itemId,
);
return (
<GalleryItem
key={item.itemId}
item={item}
isFirst={renderIndex === firstRealItemIndex}
isDragging={false}
isDeleting={deletingItemId === item.itemId}
canEdit={canEdit}
onDelete={handleDelete}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
onDragOver={(e) =>
handleDragOver(e, item.itemId, originalIndex)
}
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
/>
);
});
}
// For TOUCH drag or normal render: keep items in original order
// Show placeholder at dropIndex position for touch drag
const items = photos.map((item, index) => (
<React.Fragment key={item.itemId}>
{/* Show placeholder before this item if dropIndex matches */}
{isTouchDrag && dropIndex === index && (
<DropPlaceholder key={`drop-placeholder-${index}`} />
)}
<GalleryItem
item={item}
isFirst={index === 0}
isDragging={draggedItemId === item.itemId}
isDeleting={deletingItemId === item.itemId}
canEdit={canEdit}
onDelete={handleDelete}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
onDragOver={(e) => handleDragOver(e, item.itemId, index)}
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
/>
</React.Fragment>
));
// Add placeholder at end if dropping at last position
Iif (isTouchDrag && dropIndex === photos.length) {
items.push(<DropPlaceholder key="drop-placeholder-end" />);
}
return items;
})()}
</StyledImageList>
)}
</Root>
);
}
|