mirror of
https://github.com/pacnpal/thrilltrack-explorer.git
synced 2025-12-22 14:31:12 -05:00
Refactor to defer photo uploads
This commit is contained in:
@@ -8,10 +8,12 @@ import { X, Eye, GripVertical, Edit3 } from 'lucide-react';
|
|||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
export interface PhotoWithCaption {
|
export interface PhotoWithCaption {
|
||||||
url: string;
|
url: string; // Object URL for preview, Cloudflare URL after upload
|
||||||
|
file?: File; // The actual file to upload later
|
||||||
caption: string;
|
caption: string;
|
||||||
title?: string;
|
title?: string;
|
||||||
order: number;
|
order: number;
|
||||||
|
uploadStatus?: 'pending' | 'uploading' | 'uploaded' | 'failed';
|
||||||
}
|
}
|
||||||
|
|
||||||
interface PhotoCaptionEditorProps {
|
interface PhotoCaptionEditorProps {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { Textarea } from '@/components/ui/textarea';
|
|||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { Separator } from '@/components/ui/separator';
|
import { Separator } from '@/components/ui/separator';
|
||||||
|
import { Progress } from '@/components/ui/progress';
|
||||||
import { UppyPhotoUpload } from './UppyPhotoUpload';
|
import { UppyPhotoUpload } from './UppyPhotoUpload';
|
||||||
import { PhotoCaptionEditor, PhotoWithCaption } from './PhotoCaptionEditor';
|
import { PhotoCaptionEditor, PhotoWithCaption } from './PhotoCaptionEditor';
|
||||||
import { supabase } from '@/integrations/supabase/client';
|
import { supabase } from '@/integrations/supabase/client';
|
||||||
@@ -28,15 +29,18 @@ export function UppyPhotoSubmissionUpload({
|
|||||||
const [description, setDescription] = useState('');
|
const [description, setDescription] = useState('');
|
||||||
const [photos, setPhotos] = useState<PhotoWithCaption[]>([]);
|
const [photos, setPhotos] = useState<PhotoWithCaption[]>([]);
|
||||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
|
const [uploadProgress, setUploadProgress] = useState<{ current: number; total: number } | null>(null);
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const { toast } = useToast();
|
const { toast } = useToast();
|
||||||
|
|
||||||
const handleUploadComplete = (urls: string[]) => {
|
const handleFilesSelected = (files: File[]) => {
|
||||||
// Convert URLs to photo objects with empty captions
|
// Convert files to photo objects with object URLs for preview
|
||||||
const newPhotos: PhotoWithCaption[] = urls.map((url, index) => ({
|
const newPhotos: PhotoWithCaption[] = files.map((file, index) => ({
|
||||||
url,
|
url: URL.createObjectURL(file), // Object URL for preview
|
||||||
|
file, // Store the file for later upload
|
||||||
caption: '',
|
caption: '',
|
||||||
order: photos.length + index,
|
order: photos.length + index,
|
||||||
|
uploadStatus: 'pending' as const,
|
||||||
}));
|
}));
|
||||||
setPhotos(prev => [...prev, ...newPhotos]);
|
setPhotos(prev => [...prev, ...newPhotos]);
|
||||||
};
|
};
|
||||||
@@ -46,7 +50,14 @@ export function UppyPhotoSubmissionUpload({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleRemovePhoto = (index: number) => {
|
const handleRemovePhoto = (index: number) => {
|
||||||
setPhotos(prev => prev.filter((_, i) => i !== index));
|
setPhotos(prev => {
|
||||||
|
const photo = prev[index];
|
||||||
|
// Revoke object URL if it exists
|
||||||
|
if (photo.file && photo.url.startsWith('blob:')) {
|
||||||
|
URL.revokeObjectURL(photo.url);
|
||||||
|
}
|
||||||
|
return prev.filter((_, i) => i !== index);
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
@@ -80,6 +91,105 @@ export function UppyPhotoSubmissionUpload({
|
|||||||
setIsSubmitting(true);
|
setIsSubmitting(true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// Upload all photos that haven't been uploaded yet
|
||||||
|
const uploadedPhotos: PhotoWithCaption[] = [];
|
||||||
|
const photosToUpload = photos.filter(p => p.file);
|
||||||
|
|
||||||
|
if (photosToUpload.length > 0) {
|
||||||
|
setUploadProgress({ current: 0, total: photosToUpload.length });
|
||||||
|
|
||||||
|
for (let i = 0; i < photosToUpload.length; i++) {
|
||||||
|
const photo = photosToUpload[i];
|
||||||
|
setUploadProgress({ current: i + 1, total: photosToUpload.length });
|
||||||
|
|
||||||
|
// Update status
|
||||||
|
setPhotos(prev => prev.map(p =>
|
||||||
|
p === photo ? { ...p, uploadStatus: 'uploading' as const } : p
|
||||||
|
));
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Get upload URL from edge function
|
||||||
|
const { data: uploadData, error: uploadError } = await supabase.functions.invoke('upload-image', {
|
||||||
|
body: { metadata: { requireSignedURLs: false }, variant: 'public' }
|
||||||
|
});
|
||||||
|
|
||||||
|
if (uploadError) throw uploadError;
|
||||||
|
|
||||||
|
const { uploadURL, id: cloudflareId } = uploadData;
|
||||||
|
|
||||||
|
// Upload file to Cloudflare
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file', photo.file);
|
||||||
|
|
||||||
|
const uploadResponse = await fetch(uploadURL, {
|
||||||
|
method: 'POST',
|
||||||
|
body: formData,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!uploadResponse.ok) {
|
||||||
|
throw new Error('Failed to upload to Cloudflare');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Poll for processing completion
|
||||||
|
let attempts = 0;
|
||||||
|
const maxAttempts = 30;
|
||||||
|
let cloudflareUrl = '';
|
||||||
|
|
||||||
|
while (attempts < maxAttempts) {
|
||||||
|
const { data: { session } } = await supabase.auth.getSession();
|
||||||
|
const statusResponse = await fetch(
|
||||||
|
`https://ydvtmnrszybqnbcqbdcy.supabase.co/functions/v1/upload-image?id=${cloudflareId}`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
'Authorization': `Bearer ${session?.access_token || ''}`,
|
||||||
|
'apikey': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InlkdnRtbnJzenlicW5iY3FiZGN5Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTgzMjYzNTYsImV4cCI6MjA3MzkwMjM1Nn0.DM3oyapd_omP5ZzIlrT0H9qBsiQBxBRgw2tYuqgXKX4',
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
if (statusResponse.ok) {
|
||||||
|
const status = await statusResponse.json();
|
||||||
|
if (status.uploaded && status.urls) {
|
||||||
|
cloudflareUrl = status.urls.public;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||||
|
attempts++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!cloudflareUrl) {
|
||||||
|
throw new Error('Upload processing timeout');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Revoke object URL
|
||||||
|
URL.revokeObjectURL(photo.url);
|
||||||
|
|
||||||
|
uploadedPhotos.push({
|
||||||
|
...photo,
|
||||||
|
url: cloudflareUrl,
|
||||||
|
uploadStatus: 'uploaded' as const,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Update status
|
||||||
|
setPhotos(prev => prev.map(p =>
|
||||||
|
p === photo ? { ...p, url: cloudflareUrl, uploadStatus: 'uploaded' as const } : p
|
||||||
|
));
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Upload error:', error);
|
||||||
|
setPhotos(prev => prev.map(p =>
|
||||||
|
p === photo ? { ...p, uploadStatus: 'failed' as const } : p
|
||||||
|
));
|
||||||
|
throw new Error(`Failed to upload ${photo.title || 'photo'}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setUploadProgress(null);
|
||||||
|
|
||||||
|
// Submit to database with Cloudflare URLs
|
||||||
const submissionData = {
|
const submissionData = {
|
||||||
user_id: user.id,
|
user_id: user.id,
|
||||||
submission_type: 'photo',
|
submission_type: 'photo',
|
||||||
@@ -87,7 +197,7 @@ export function UppyPhotoSubmissionUpload({
|
|||||||
title: title.trim(),
|
title: title.trim(),
|
||||||
description: description.trim(),
|
description: description.trim(),
|
||||||
photos: photos.map((photo, index) => ({
|
photos: photos.map((photo, index) => ({
|
||||||
url: photo.url,
|
url: photo.uploadStatus === 'uploaded' ? photo.url : uploadedPhotos.find(p => p.order === photo.order)?.url || photo.url,
|
||||||
caption: photo.caption.trim(),
|
caption: photo.caption.trim(),
|
||||||
title: photo.title?.trim(),
|
title: photo.title?.trim(),
|
||||||
order: index,
|
order: index,
|
||||||
@@ -112,7 +222,13 @@ export function UppyPhotoSubmissionUpload({
|
|||||||
description: 'Your photos have been submitted for review. Thank you for contributing!',
|
description: 'Your photos have been submitted for review. Thank you for contributing!',
|
||||||
});
|
});
|
||||||
|
|
||||||
// Reset form
|
// Cleanup and reset form
|
||||||
|
photos.forEach(photo => {
|
||||||
|
if (photo.url.startsWith('blob:')) {
|
||||||
|
URL.revokeObjectURL(photo.url);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
setTitle('');
|
setTitle('');
|
||||||
setDescription('');
|
setDescription('');
|
||||||
setPhotos([]);
|
setPhotos([]);
|
||||||
@@ -122,13 +238,25 @@ export function UppyPhotoSubmissionUpload({
|
|||||||
toast({
|
toast({
|
||||||
variant: 'destructive',
|
variant: 'destructive',
|
||||||
title: 'Submission Failed',
|
title: 'Submission Failed',
|
||||||
description: 'There was an error submitting your photos. Please try again.',
|
description: error instanceof Error ? error.message : 'There was an error submitting your photos. Please try again.',
|
||||||
});
|
});
|
||||||
} finally {
|
} finally {
|
||||||
setIsSubmitting(false);
|
setIsSubmitting(false);
|
||||||
|
setUploadProgress(null);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Cleanup on unmount
|
||||||
|
React.useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
photos.forEach(photo => {
|
||||||
|
if (photo.url.startsWith('blob:')) {
|
||||||
|
URL.revokeObjectURL(photo.url);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
const metadata = {
|
const metadata = {
|
||||||
submissionType: 'photo',
|
submissionType: 'photo',
|
||||||
parkId,
|
parkId,
|
||||||
@@ -181,6 +309,7 @@ export function UppyPhotoSubmissionUpload({
|
|||||||
placeholder="Give your photos a descriptive title"
|
placeholder="Give your photos a descriptive title"
|
||||||
maxLength={100}
|
maxLength={100}
|
||||||
required
|
required
|
||||||
|
disabled={isSubmitting}
|
||||||
className="transition-all duration-200 focus:ring-2 focus:ring-primary/20"
|
className="transition-all duration-200 focus:ring-2 focus:ring-primary/20"
|
||||||
/>
|
/>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
@@ -199,6 +328,7 @@ export function UppyPhotoSubmissionUpload({
|
|||||||
placeholder="Add a general description about these photos..."
|
placeholder="Add a general description about these photos..."
|
||||||
maxLength={500}
|
maxLength={500}
|
||||||
rows={3}
|
rows={3}
|
||||||
|
disabled={isSubmitting}
|
||||||
className="transition-all duration-200 focus:ring-2 focus:ring-primary/20 resize-none"
|
className="transition-all duration-200 focus:ring-2 focus:ring-primary/20 resize-none"
|
||||||
/>
|
/>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
@@ -216,7 +346,8 @@ export function UppyPhotoSubmissionUpload({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<UppyPhotoUpload
|
<UppyPhotoUpload
|
||||||
onUploadComplete={handleUploadComplete}
|
onFilesSelected={handleFilesSelected}
|
||||||
|
deferUpload={true}
|
||||||
maxFiles={10}
|
maxFiles={10}
|
||||||
maxSizeMB={25}
|
maxSizeMB={25}
|
||||||
metadata={metadata}
|
metadata={metadata}
|
||||||
@@ -224,6 +355,7 @@ export function UppyPhotoSubmissionUpload({
|
|||||||
showPreview={false}
|
showPreview={false}
|
||||||
size="default"
|
size="default"
|
||||||
enableDragDrop={true}
|
enableDragDrop={true}
|
||||||
|
disabled={isSubmitting}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -242,6 +374,18 @@ export function UppyPhotoSubmissionUpload({
|
|||||||
<Separator />
|
<Separator />
|
||||||
|
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
|
{uploadProgress && (
|
||||||
|
<div className="space-y-2">
|
||||||
|
<div className="flex items-center justify-between text-sm">
|
||||||
|
<span className="font-medium">Uploading photos...</span>
|
||||||
|
<span className="text-muted-foreground">
|
||||||
|
{uploadProgress.current} of {uploadProgress.total}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<Progress value={(uploadProgress.current / uploadProgress.total) * 100} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
onClick={handleSubmit}
|
onClick={handleSubmit}
|
||||||
disabled={isSubmitting || !title.trim() || photos.length === 0}
|
disabled={isSubmitting || !title.trim() || photos.length === 0}
|
||||||
@@ -251,7 +395,7 @@ export function UppyPhotoSubmissionUpload({
|
|||||||
{isSubmitting ? (
|
{isSubmitting ? (
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<div className="w-4 h-4 border-2 border-primary-foreground/30 border-t-primary-foreground rounded-full animate-spin" />
|
<div className="w-4 h-4 border-2 border-primary-foreground/30 border-t-primary-foreground rounded-full animate-spin" />
|
||||||
Submitting Photos...
|
{uploadProgress ? `Uploading ${uploadProgress.current}/${uploadProgress.total}...` : 'Submitting...'}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { Progress } from '@/components/ui/progress';
|
|||||||
|
|
||||||
interface UppyPhotoUploadProps {
|
interface UppyPhotoUploadProps {
|
||||||
onUploadComplete?: (urls: string[]) => void;
|
onUploadComplete?: (urls: string[]) => void;
|
||||||
|
onFilesSelected?: (files: File[]) => void;
|
||||||
onUploadStart?: () => void;
|
onUploadStart?: () => void;
|
||||||
onUploadError?: (error: Error) => void;
|
onUploadError?: (error: Error) => void;
|
||||||
maxFiles?: number;
|
maxFiles?: number;
|
||||||
@@ -24,6 +25,7 @@ interface UppyPhotoUploadProps {
|
|||||||
size?: 'default' | 'compact' | 'large';
|
size?: 'default' | 'compact' | 'large';
|
||||||
enableDragDrop?: boolean;
|
enableDragDrop?: boolean;
|
||||||
showUploadModal?: boolean;
|
showUploadModal?: boolean;
|
||||||
|
deferUpload?: boolean; // If true, don't upload immediately
|
||||||
}
|
}
|
||||||
|
|
||||||
interface CloudflareResponse {
|
interface CloudflareResponse {
|
||||||
@@ -46,6 +48,7 @@ interface UploadSuccessResponse {
|
|||||||
|
|
||||||
export function UppyPhotoUpload({
|
export function UppyPhotoUpload({
|
||||||
onUploadComplete,
|
onUploadComplete,
|
||||||
|
onFilesSelected,
|
||||||
onUploadStart,
|
onUploadStart,
|
||||||
onUploadError,
|
onUploadError,
|
||||||
maxFiles = 5,
|
maxFiles = 5,
|
||||||
@@ -59,6 +62,7 @@ export function UppyPhotoUpload({
|
|||||||
showPreview = true,
|
showPreview = true,
|
||||||
size = 'default',
|
size = 'default',
|
||||||
enableDragDrop = true,
|
enableDragDrop = true,
|
||||||
|
deferUpload = false,
|
||||||
}: UppyPhotoUploadProps) {
|
}: UppyPhotoUploadProps) {
|
||||||
const [uploadedImages, setUploadedImages] = useState<string[]>([]);
|
const [uploadedImages, setUploadedImages] = useState<string[]>([]);
|
||||||
const [isUploading, setIsUploading] = useState(false);
|
const [isUploading, setIsUploading] = useState(false);
|
||||||
@@ -171,6 +175,13 @@ export function UppyPhotoUpload({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// If deferUpload is true, just notify and don't upload
|
||||||
|
if (deferUpload) {
|
||||||
|
onFilesSelected?.(files);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise, upload immediately (old behavior)
|
||||||
setIsUploading(true);
|
setIsUploading(true);
|
||||||
setUploadProgress(0);
|
setUploadProgress(0);
|
||||||
onUploadStart?.();
|
onUploadStart?.();
|
||||||
|
|||||||
Reference in New Issue
Block a user