Files
fotospiel-app/resources/js/guest/pages/PhotoLightbox.tsx

483 lines
18 KiB
TypeScript

import React, { useState, useEffect } from 'react';
import { useParams, useLocation, useNavigate } from 'react-router-dom';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { Badge } from '@/components/ui/badge';
import { Heart, ChevronLeft, ChevronRight, X, Share2, Download } from 'lucide-react';
import { likePhoto, createPhotoShareLink } from '../services/photosApi';
import { useTranslation } from '../i18n/useTranslation';
import { useToast } from '../components/ToastHost';
import ShareSheet from '../components/ShareSheet';
import { useEventBranding } from '../context/EventBrandingContext';
import { getDeviceId } from '../lib/device';
type Photo = {
id: number;
file_path?: string;
thumbnail_path?: string;
likes_count?: number;
created_at?: string;
task_id?: number;
task_title?: string;
uploader_name?: string | null;
};
type Task = { id: number; title: string };
interface Props {
photos?: Photo[];
currentIndex?: number;
onClose?: () => void;
onIndexChange?: (index: number) => void;
token?: string;
eventName?: string | null;
}
export default function PhotoLightbox({ photos, currentIndex, onClose, onIndexChange, token, eventName }: Props) {
const params = useParams<{ token?: string; photoId?: string }>();
const location = useLocation();
const navigate = useNavigate();
const photoId = params.photoId;
const eventToken = params.token || token;
const { t, locale } = useTranslation();
const toast = useToast();
const { branding } = useEventBranding();
const [standalonePhoto, setStandalonePhoto] = useState<Photo | null>(null);
const [task, setTask] = useState<Task | null>(null);
const [taskLoading, setTaskLoading] = useState(false);
const [likes, setLikes] = useState<number>(0);
const [liked, setLiked] = useState(false);
const [shareSheet, setShareSheet] = useState<{ url: string | null; loading: boolean }>({
url: null,
loading: false,
});
// Determine mode and photo
const isStandalone = !photos || photos.length === 0;
const currentPhotos = isStandalone ? (standalonePhoto ? [standalonePhoto] : []) : photos || [];
const currentIndexVal = isStandalone ? 0 : (currentIndex || 0);
const photo = currentPhotos[currentIndexVal];
// Fallback onClose for standalone
const handleClose = onClose || (() => navigate(-1));
// Fetch single photo for standalone mode
useEffect(() => {
if (isStandalone && photoId && !standalonePhoto && eventToken) {
const fetchPhoto = async () => {
try {
const res = await fetch(`/api/v1/photos/${photoId}?locale=${encodeURIComponent(locale)}`, {
headers: {
Accept: 'application/json',
'X-Locale': locale,
},
});
if (res.ok) {
const fetchedPhoto: Photo = await res.json();
setStandalonePhoto(fetchedPhoto);
// Check state for initial photo
if (location.state?.photo) {
setStandalonePhoto(location.state.photo);
}
} else {
toast.push({ text: t('lightbox.errors.notFound'), type: 'error' });
}
} catch (err) {
console.warn('Standalone photo load failed', err);
toast.push({ text: t('lightbox.errors.loadFailed'), type: 'error' });
}
};
fetchPhoto();
}
}, [isStandalone, photoId, eventToken, standalonePhoto, location.state, t, locale, toast]);
// Update likes when photo changes
React.useEffect(() => {
if (photo) {
setLikes(photo.likes_count ?? 0);
// Check if liked from localStorage
try {
const raw = localStorage.getItem('liked-photo-ids');
const likedIds = raw ? JSON.parse(raw) : [];
setLiked(likedIds.includes(photo.id));
} catch {
setLiked(false);
}
}
}, [photo]);
const radius = branding.buttons?.radius ?? 12;
const bodyFont = branding.typography?.body ?? branding.fontFamily ?? null;
const headingFont = branding.typography?.heading ?? branding.fontFamily ?? null;
const touchRef = React.useRef<HTMLDivElement>(null);
const startX = React.useRef(0);
const currentX = React.useRef(0);
const handleTouchStart = (e: React.TouchEvent) => {
startX.current = e.touches[0].clientX;
};
const handleTouchMove = (e: React.TouchEvent) => {
if (!touchRef.current) return;
currentX.current = e.touches[0].clientX;
const deltaX = currentX.current - startX.current;
touchRef.current.style.transform = `translateX(${deltaX}px)`;
};
const handleTouchEnd = () => {
if (!touchRef.current) return;
const deltaX = currentX.current - startX.current;
const threshold = 50; // pixels
touchRef.current.style.transform = 'translateX(0)';
if (Math.abs(deltaX) > threshold) {
if (deltaX > 0 && currentIndexVal > 0) {
// Swipe right - previous
onIndexChange?.(currentIndexVal - 1);
} else if (deltaX < 0 && currentIndexVal < currentPhotos.length - 1) {
// Swipe left - next
onIndexChange?.(currentIndexVal + 1);
}
}
};
// Load task info if photo has task_id and event key is available
React.useEffect(() => {
if (!photo?.task_id || !eventToken) {
setTask(null);
setTaskLoading(false);
return;
}
const taskId = photo.task_id;
(async () => {
setTaskLoading(true);
try {
const res = await fetch(
`/api/v1/events/${encodeURIComponent(eventToken)}/tasks?locale=${encodeURIComponent(locale)}`,
{
headers: {
Accept: 'application/json',
'X-Locale': locale,
'X-Device-Id': getDeviceId(),
},
}
);
if (res.ok) {
const payload = (await res.json()) as unknown;
const tasks = Array.isArray(payload)
? payload
: Array.isArray((payload as any)?.data)
? (payload as any).data
: Array.isArray((payload as any)?.tasks)
? (payload as any).tasks
: [];
const foundTask = (tasks as Task[]).find((t) => t.id === taskId);
if (foundTask) {
setTask({
id: foundTask.id,
title: foundTask.title || t('lightbox.fallbackTitle').replace('{id}', `${taskId}`)
});
} else {
setTask({
id: taskId,
title: t('lightbox.unknownTitle').replace('{id}', `${taskId}`)
});
}
} else {
setTask({
id: taskId,
title: t('lightbox.unknownTitle').replace('{id}', `${taskId}`)
});
}
} catch (error) {
console.error('Failed to load task:', error);
setTask({
id: taskId,
title: t('lightbox.unknownTitle').replace('{id}', `${taskId}`)
});
} finally {
setTaskLoading(false);
}
})();
}, [photo?.task_id, eventToken, t, locale]);
async function onLike() {
if (liked || !photo) return;
setLiked(true);
try {
const count = await likePhoto(photo.id);
setLikes(count);
// Update localStorage
try {
const raw = localStorage.getItem('liked-photo-ids');
const arr: number[] = raw ? JSON.parse(raw) : [];
if (!arr.includes(photo.id)) {
localStorage.setItem('liked-photo-ids', JSON.stringify([...arr, photo.id]));
}
} catch (storageError) {
console.warn('Failed to persist liked photo IDs', storageError);
}
} catch (error) {
console.error('Like failed:', error);
setLiked(false);
}
}
const shareTitle = photo?.task_title ?? task?.title ?? t('share.title', 'Geteiltes Foto');
const shareText = t('share.shareText', { event: eventName ?? shareTitle ?? 'Fotospiel' });
const createdLabel = React.useMemo(() => {
if (!photo?.created_at) return null;
try {
const date = new Date(photo.created_at);
return date.toLocaleString(locale, { dateStyle: 'medium', timeStyle: 'short' });
} catch {
return null;
}
}, [photo?.created_at, locale]);
const uploaderInitial = React.useMemo(() => {
const name = photo?.uploader_name;
if (!name) return 'G';
return (name.trim()[0] || 'G').toUpperCase();
}, [photo?.uploader_name]);
const primaryColor = branding.primaryColor || '#0ea5e9';
const secondaryColor = branding.secondaryColor || '#6366f1';
async function openShareSheet() {
if (!photo || !eventToken) return;
setShareSheet({ url: null, loading: true });
try {
const payload = await createPhotoShareLink(eventToken, photo.id);
setShareSheet({ url: payload.url, loading: false });
} catch (error) {
console.error('share failed', error);
toast.push({ text: t('share.error', 'Teilen fehlgeschlagen'), type: 'error' });
setShareSheet({ url: null, loading: false });
}
}
function shareWhatsApp(url?: string | null) {
if (!url) return;
const waUrl = `https://wa.me/?text=${encodeURIComponent(`${shareText} ${url}`)}`;
window.open(waUrl, '_blank', 'noopener');
setShareSheet({ url: null, loading: false });
}
function shareMessages(url?: string | null) {
if (!url) return;
const smsUrl = `sms:?&body=${encodeURIComponent(`${shareText} ${url}`)}`;
window.open(smsUrl, '_blank', 'noopener');
setShareSheet({ url: null, loading: false });
}
function shareNative(url?: string | null) {
if (!url) return;
const data: ShareData = {
title: shareTitle,
text: shareText,
url,
};
if (navigator.share && (!navigator.canShare || navigator.canShare(data))) {
navigator.share(data).catch(() => {});
setShareSheet({ url: null, loading: false });
return;
}
void copyLink(url);
}
async function copyLink(url?: string | null) {
if (!url) return;
try {
await navigator.clipboard?.writeText(url);
toast.push({ text: t('share.copySuccess', 'Link kopiert!') });
} catch {
toast.push({ text: t('share.copyError', 'Link konnte nicht kopiert werden.'), type: 'error' });
} finally {
setShareSheet({ url: null, loading: false });
}
}
function closeShareSheet() {
setShareSheet({ url: null, loading: false });
}
function onOpenChange(open: boolean) {
if (!open) handleClose();
}
return (
<Dialog open={true} onOpenChange={onOpenChange}>
<DialogContent
hideClose
className="max-w-6xl overflow-hidden rounded-3xl border border-white/10 bg-white/5 p-0 text-white shadow-2xl backdrop-blur-3xl"
>
<div className="relative">
<div className="absolute inset-0 opacity-50" style={{ background: 'radial-gradient(circle at 20% 20%, rgba(255,255,255,0.12), transparent 40%), radial-gradient(circle at 80% 10%, rgba(255,255,255,0.1), transparent 35%)' }} />
<div className="absolute top-4 left-0 right-0 z-30 flex items-center justify-between px-5">
<div className="flex items-center gap-2 rounded-full border border-white/20 bg-black/40 px-2 py-1 shadow-lg backdrop-blur">
<Button variant="ghost" size="icon" onClick={onClose} className="h-10 w-10 rounded-full text-white hover:bg-white/10">
<X className="h-5 w-5" />
</Button>
<div className="rounded-full bg-white/10 px-3 py-1 text-xs font-semibold text-white/90">
{currentIndexVal + 1} / {currentPhotos.length}
</div>
</div>
<div className="flex items-center gap-2 rounded-full border border-white/20 bg-black/40 px-2 py-1 shadow-lg backdrop-blur">
<Button variant="ghost" size="icon" onClick={onLike} disabled={liked} className="h-10 w-10 rounded-full text-white hover:bg-white/10">
<Heart className={`h-5 w-5 ${liked ? 'fill-red-500 text-red-500' : ''}`} />
</Button>
<Button
variant="ghost"
size="icon"
onClick={openShareSheet}
disabled={!eventToken || !photo}
className="h-10 w-10 rounded-full text-white hover:bg-white/10"
>
<Share2 className="h-5 w-5" />
</Button>
</div>
</div>
<div className="px-3 pb-5 pt-16">
<div
ref={touchRef}
className="relative flex min-h-[60vh] items-center justify-center overflow-hidden rounded-[30px] border border-white/15 bg-black/30 p-4 shadow-xl backdrop-blur"
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
onTouchEnd={handleTouchEnd}
>
{currentIndexVal > 0 && (
<Button
variant="ghost"
size="icon"
onClick={() => onIndexChange?.(currentIndexVal - 1)}
className="absolute left-3 top-1/2 -translate-y-1/2 rounded-full bg-white/90 text-slate-800 shadow-lg hover:bg-white"
>
<ChevronLeft className="h-5 w-5" />
</Button>
)}
<img
src={photo?.file_path || photo?.thumbnail_path}
alt={t('lightbox.photoAlt')
.replace('{id}', `${photo?.id ?? ''}`)
.replace(
'{suffix}',
photo?.task_title
? t('lightbox.photoAltTaskSuffix').replace('{taskTitle}', photo.task_title)
: ''
)}
className="max-h-[70vh] max-w-full object-contain transition-transform duration-200"
onError={(e) => {
console.error('Image load error:', e);
(e.target as HTMLImageElement).style.display = 'none';
}}
/>
{currentIndexVal < currentPhotos.length - 1 && (
<Button
variant="ghost"
size="icon"
onClick={() => onIndexChange?.(currentIndexVal + 1)}
className="absolute right-3 top-1/2 -translate-y-1/2 rounded-full bg-white/90 text-slate-800 shadow-lg hover:bg-white"
>
<ChevronRight className="h-5 w-5" />
</Button>
)}
</div>
<div className="mt-5 grid gap-3 rounded-2xl border border-white/15 bg-black/35 px-4 py-3 text-sm text-white/90 shadow-md backdrop-blur sm:grid-cols-[1.3fr_1fr]">
<div className="flex items-center gap-3">
<Avatar className="h-11 w-11 border border-white/20 bg-white/10">
<AvatarFallback className="text-white">{uploaderInitial}</AvatarFallback>
</Avatar>
<div className="space-y-1">
{photo?.uploader_name ? (
<p className="font-semibold text-white">{photo.uploader_name}</p>
) : (
<p className="font-semibold text-white">{t('galleryPage.photo.anonymous', 'Gast')}</p>
)}
{createdLabel ? <p className="text-xs text-white/70">{createdLabel}</p> : null}
</div>
</div>
<div className="flex flex-wrap items-center justify-start gap-2 sm:justify-end">
{task ? (
<Badge variant="outline" className="border-white/30 bg-white/10 text-white">
{t('lightbox.taskLabel')}: {task.title}
</Badge>
) : null}
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="icon"
onClick={onLike}
disabled={liked}
className="h-9 w-9 rounded-full text-white hover:bg-white/10"
aria-label={t('lightbox.like', 'Like photo')}
>
<Heart className={`h-5 w-5 ${liked ? 'fill-red-500 text-red-500' : ''}`} />
</Button>
<Button
variant="ghost"
size="icon"
onClick={openShareSheet}
disabled={!eventToken || !photo}
className="h-9 w-9 rounded-full text-white hover:bg-white/10"
aria-label={t('share.button', 'Teilen')}
>
<Share2 className="h-5 w-5" />
</Button>
<Button
variant="ghost"
size="icon"
onClick={() => {
if (!photo?.file_path) return;
window.open(photo.file_path, '_blank', 'noopener');
}}
className="h-9 w-9 rounded-full text-white hover:bg-white/10"
aria-label={t('lightbox.download', 'Download')}
disabled={!photo?.file_path}
>
<Download className="h-5 w-5" />
</Button>
</div>
</div>
</div>
{taskLoading && !task && (
<div className="mt-4 rounded-xl border border-white/20 bg-black/40 p-3 text-center text-xs text-white/80 shadow-sm backdrop-blur">
<div className="mx-auto mb-1 h-4 w-4 animate-spin rounded-full border-b-2 border-white/70" />
{t('lightbox.loadingTask')}
</div>
)}
</div>
</div>
<ShareSheet
open={shareSheet.loading || Boolean(shareSheet.url)}
photoId={photo?.id}
eventName={eventName ?? null}
url={shareSheet.url}
loading={shareSheet.loading}
onClose={closeShareSheet}
onShareNative={() => shareNative(shareSheet.url)}
onShareWhatsApp={() => shareWhatsApp(shareSheet.url)}
onShareMessages={() => shareMessages(shareSheet.url)}
onCopyLink={() => copyLink(shareSheet.url)}
radius={radius}
bodyFont={bodyFont}
headingFont={headingFont}
/>
</DialogContent>
</Dialog>
);
}