Fix header/footer placement on image upload step

This commit is contained in:
2025-02-26 21:39:09 -05:00
parent c185d4e3ca
commit 3ca72674af

View File

@@ -3,8 +3,6 @@ import { useRsi } from "../../hooks/useRsi";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Loader2, Upload, Trash2, AlertCircle, GripVertical, Maximize2, X } from "lucide-react"; import { Loader2, Upload, Trash2, AlertCircle, GripVertical, Maximize2, X } from "lucide-react";
import { Card, CardContent } from "@/components/ui/card"; import { Card, CardContent } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { ScrollArea } from "@/components/ui/scroll-area";
import { toast } from "sonner"; import { toast } from "sonner";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import config from "@/config"; import config from "@/config";
@@ -13,7 +11,6 @@ import { cn } from "@/lib/utils";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { import {
DndContext, DndContext,
closestCenter,
KeyboardSensor, KeyboardSensor,
PointerSensor, PointerSensor,
useSensor, useSensor,
@@ -23,10 +20,7 @@ import {
DragStartEvent, DragStartEvent,
pointerWithin, pointerWithin,
rectIntersection, rectIntersection,
getFirstCollision,
useDndMonitor,
DragMoveEvent, DragMoveEvent,
closestCorners,
CollisionDetection, CollisionDetection,
useDroppable useDroppable
} from '@dnd-kit/core'; } from '@dnd-kit/core';
@@ -35,7 +29,6 @@ import {
SortableContext, SortableContext,
sortableKeyboardCoordinates, sortableKeyboardCoordinates,
useSortable, useSortable,
rectSortingStrategy,
horizontalListSortingStrategy horizontalListSortingStrategy
} from '@dnd-kit/sortable'; } from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities'; import { CSS } from '@dnd-kit/utilities';
@@ -45,7 +38,7 @@ import {
DialogTrigger, DialogTrigger,
} from "@/components/ui/dialog"; } from "@/components/ui/dialog";
type Props<T extends string> = { type Props<T extends string = string> = {
data: any[]; data: any[];
file: File; file: File;
onBack?: () => void; onBack?: () => void;
@@ -129,14 +122,13 @@ export const ImageUploadStep = <T extends string>({
// Handle drag over to track which product container is being hovered // Handle drag over to track which product container is being hovered
const handleDragOver = (event: DragMoveEvent) => { const handleDragOver = (event: DragMoveEvent) => {
const { active, over } = event; const { over } = event;
if (!over) { if (!over) {
setActiveDroppableId(null); setActiveDroppableId(null);
return; return;
} }
const activeContainer = findContainer(active.id.toString());
let overContainer = null; let overContainer = null;
// Check if we're over a product container directly // Check if we're over a product container directly
@@ -224,7 +216,7 @@ export const ImageUploadStep = <T extends string>({
setActiveDroppableId(`product-${index}`); setActiveDroppableId(`product-${index}`);
}; };
const handleNativeDragLeave = (e: DragEvent) => { const handleNativeDragLeave = () => {
// Remove highlight when drag leaves // Remove highlight when drag leaves
container.classList.remove('border-primary', 'bg-primary/5'); container.classList.remove('border-primary', 'bg-primary/5');
if (activeDroppableId === `product-${index}`) { if (activeDroppableId === `product-${index}`) {
@@ -414,7 +406,6 @@ export const ImageUploadStep = <T extends string>({
newItems.push(...newFilteredItems); newItems.push(...newFilteredItems);
// Update the product data with the new image order // Update the product data with the new image order
const updatedData = updateProductImageOrder(sourceProductIndex, newFilteredItems);
return newItems; return newItems;
} }
@@ -436,7 +427,6 @@ export const ImageUploadStep = <T extends string>({
newItems.push(...newFilteredItems); newItems.push(...newFilteredItems);
// Update the product data with the new image order // Update the product data with the new image order
const updatedData = updateProductImageOrder(sourceProductIndex, newFilteredItems);
return newItems; return newItems;
}); });
@@ -484,24 +474,6 @@ export const ImageUploadStep = <T extends string>({
}; };
// Function to update product data with the new image order // Function to update product data with the new image order
const updateProductImageOrder = (productIndex: number, orderedImages: ProductImageSortable[]) => {
// Create a copy of the data
const newData = [...data];
// Get the current product
const product = newData[productIndex];
// Get the ordered URLs
const orderedUrls = orderedImages.map(img => img.imageUrl);
// Update the product with the ordered URLs
product.image_url = orderedUrls.join(',');
// Update the data
newData[productIndex] = product;
return newData;
};
// Function to handle image upload // Function to handle image upload
const handleImageUpload = async (files: FileList | File[], productIndex: number) => { const handleImageUpload = async (files: FileList | File[], productIndex: number) => {
@@ -551,7 +523,6 @@ export const ImageUploadStep = <T extends string>({
); );
// Update the product data with the new image URL // Update the product data with the new image URL
const updatedData = addImageToProduct(productIndex, result.imageUrl);
toast.success(`Image uploaded for ${data[productIndex].name || `Product #${productIndex + 1}`}`); toast.success(`Image uploaded for ${data[productIndex].name || `Product #${productIndex + 1}`}`);
} catch (error) { } catch (error) {
@@ -778,7 +749,6 @@ export const ImageUploadStep = <T extends string>({
setProductImages(prev => prev.filter((_, idx) => idx !== imageIndex)); setProductImages(prev => prev.filter((_, idx) => idx !== imageIndex));
// Remove the image URL from the product data // Remove the image URL from the product data
const updatedData = removeImageFromProduct(image.productIndex, image.imageUrl);
toast.success('Image removed successfully'); toast.success('Image removed successfully');
} catch (error) { } catch (error) {
@@ -883,7 +853,7 @@ export const ImageUploadStep = <T extends string>({
<div <div
{...getRootProps()} {...getRootProps()}
className={cn( className={cn(
"border-2 border-dashed border-secondary-foreground/30 bg-muted/90 rounded-md h-24 w-24 flex flex-col items-center justify-center cursor-pointer hover:bg-muted/70 transition-colors shrink-0", "border-2 border-dashed border-secondary-foreground/30 bg-muted/90 rounded-md h-24 w-24 flex flex-col items-center justify-center self-center cursor-pointer hover:bg-muted/70 transition-colors shrink-0",
isDragActive && "border-primary bg-muted" isDragActive && "border-primary bg-muted"
)} )}
> >
@@ -909,7 +879,7 @@ export const ImageUploadStep = <T extends string>({
<img <img
src={image.previewUrl} src={image.previewUrl}
alt={`Unassigned image ${index + 1}`} alt={`Unassigned image ${index + 1}`}
className="h-28 w-full object-cover" className="h-full w-full object-cover"
/> />
<div className="absolute bottom-0 left-0 right-0 bg-black/60 p-2"> <div className="absolute bottom-0 left-0 right-0 bg-black/60 p-2">
<p className="text-white text-xs mb-1 truncate">{image.file.name}</p> <p className="text-white text-xs mb-1 truncate">{image.file.name}</p>
@@ -943,7 +913,7 @@ export const ImageUploadStep = <T extends string>({
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}> <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
<DialogTrigger asChild> <DialogTrigger asChild>
<button <button
className="absolute top-1 left-1 bg-black/60 rounded-full p-1.5 text-white z-10 hover:bg-black/80" className="absolute top-1 left-1 bg-black/60 rounded-full p-1 text-white z-10 hover:bg-black/80"
onClick={(e) => { onClick={(e) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
@@ -1018,57 +988,6 @@ export const ImageUploadStep = <T extends string>({
}; };
// Add the ZoomedImage component to show a larger version of the image // Add the ZoomedImage component to show a larger version of the image
const ZoomedImage = ({ imageUrl, alt }: { imageUrl: string; alt: string }) => {
const [open, setOpen] = useState(false);
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>
<button
className="absolute bottom-1 left-1 bg-black/60 rounded-full p-1.5 text-white z-10 hover:bg-black/80"
onClick={(e) => {
e.preventDefault();
e.stopPropagation(); // Prevent triggering drag listeners
setOpen(true);
}}
onPointerDown={(e) => {
e.stopPropagation(); // Prevent drag from starting
}}
onMouseDown={(e) => {
e.stopPropagation(); // Prevent drag from starting
}}
onTouchStart={(e) => {
e.stopPropagation(); // Prevent drag from starting on touch
}}
>
<Maximize2 className="h-3.5 w-3.5" />
</button>
</DialogTrigger>
<DialogContent className="sm:max-w-[650px] max-h-[90vh] p-6 bg-background/95 backdrop-blur-sm border border-border rounded-lg shadow-2xl">
<div className="relative flex flex-col items-center justify-center">
<Button
variant="ghost"
size="icon"
className="absolute -top-2 -right-2 bg-black/60 text-white hover:bg-black/80 rounded-full z-10 h-8 w-8"
onClick={() => setOpen(false)}
>
<X className="h-4 w-4" />
</Button>
<div className="overflow-hidden rounded-md border border-border shadow-md bg-white dark:bg-black">
<img
src={imageUrl}
alt={alt}
className="max-h-[70vh] max-w-full object-contain"
/>
</div>
<div className="mt-2 text-sm text-muted-foreground text-center">
{alt || "Product Image"}
</div>
</div>
</DialogContent>
</Dialog>
);
};
// Sortable Image component with enhanced drag prevention // Sortable Image component with enhanced drag prevention
const SortableImage = ({ image, productIndex, imgIndex }: { image: ProductImageSortable, productIndex: number, imgIndex: number }) => { const SortableImage = ({ image, productIndex, imgIndex }: { image: ProductImageSortable, productIndex: number, imgIndex: number }) => {
@@ -1114,7 +1033,7 @@ export const ImageUploadStep = <T extends string>({
<div <div
ref={setNodeRef} ref={setNodeRef}
style={style} style={style}
className="relative border rounded-md overflow-hidden flex items-center justify-center shrink-0 cursor-grab active:cursor-grabbing select-none no-native-drag" className="relative border rounded-md overflow-hidden flex items-center justify-center shrink-0 cursor-grab active:cursor-grabbing select-none no-native-drag group hover:ring-2 hover:ring-primary/30 transition-all"
{...attributes} {...attributes}
{...listeners} {...listeners}
onDragStart={(e) => { onDragStart={(e) => {
@@ -1136,9 +1055,13 @@ export const ImageUploadStep = <T extends string>({
className="h-full w-full object-cover select-none no-native-drag" className="h-full w-full object-cover select-none no-native-drag"
draggable={false} draggable={false}
/> />
<div className="absolute inset-0 bg-black/0 group-hover:bg-black/10 transition-colors duration-200"></div>
<div className="absolute right-0 top-0 p-1 opacity-0 group-hover:opacity-90 transition-opacity">
<GripVertical className="h-3 w-3 text-white drop-shadow-md" />
</div>
<button <button
ref={deleteButtonRef} ref={deleteButtonRef}
className="absolute top-1 right-1 bg-black/60 rounded-full p-1 text-white z-10 hover:bg-black/80" className="absolute opacity-0 group-hover:opacity-100 transition-opacity duration-200 top-1 right-1 bg-black/40 hover:bg-black/70 hover:scale-110 rounded-full p-1 text-white z-10"
onClick={(e) => { onClick={(e) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); // Prevent triggering drag listeners e.stopPropagation(); // Prevent triggering drag listeners
@@ -1154,7 +1077,7 @@ export const ImageUploadStep = <T extends string>({
e.stopPropagation(); // Prevent drag from starting on touch e.stopPropagation(); // Prevent drag from starting on touch
}} }}
> >
<Trash2 className="h-3 w-3" /> <Trash2 className="h-3.5 w-3.5" />
</button> </button>
{/* Fix zoom button with proper state management */} {/* Fix zoom button with proper state management */}
@@ -1162,7 +1085,7 @@ export const ImageUploadStep = <T extends string>({
<DialogTrigger asChild> <DialogTrigger asChild>
<button <button
ref={zoomButtonRef} ref={zoomButtonRef}
className="absolute bottom-1 left-1 bg-black/60 rounded-full p-1 text-white z-10 hover:bg-black/80" className="absolute opacity-0 group-hover:opacity-100 transition-opacity duration-200 bottom-1 left-1 bg-black/40 hover:bg-black/70 hover:scale-110 rounded-full p-1 text-white z-10"
onClick={(e) => { onClick={(e) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); // Prevent triggering drag listeners e.stopPropagation(); // Prevent triggering drag listeners
@@ -1251,23 +1174,28 @@ export const ImageUploadStep = <T extends string>({
}; };
return ( return (
<div className="flex flex-col h-full"> <div className="flex flex-col h-[calc(100vh-9.5rem)] overflow-hidden">
<div className="p-4"> {/* Header - fixed at top */}
<h2 className="text-2xl font-semibold mb-2">Add Product Images</h2> <div className="px-8 py-6 bg-background shrink-0">
<p className="text-sm text-muted-foreground mb-2"> <h2 className="text-2xl font-semibold">Add Product Images</h2>
<p className="text-sm text-muted-foreground mt-1">
Upload images for each product. Drag images to reorder them or move them between products. Upload images for each product. Drag images to reorder them or move them between products.
</p> </p>
</div> </div>
<div className="px-4 mb-4"> {/* Content area - only this part scrolls */}
<div className="flex-1 overflow-hidden">
<div className="h-full flex flex-col overflow-auto">
<div className="px-8 py-4 shrink-0">
<GenericDropzone /> <GenericDropzone />
</div> </div>
<div className="px-8 py-2 shrink-0">
<UnassignedImagesSection /> <UnassignedImagesSection />
</div>
<Separator /> {/* Scrollable product cards */}
<div className="px-8 py-2 flex-1">
<ScrollArea className="flex-1 p-4">
<DndContext <DndContext
sensors={sensors} sensors={sensors}
collisionDetection={customCollisionDetection} collisionDetection={customCollisionDetection}
@@ -1277,11 +1205,10 @@ export const ImageUploadStep = <T extends string>({
autoScroll={{ autoScroll={{
threshold: { threshold: {
x: 0, x: 0,
y: 0.2, // Start scrolling when dragging near the edges y: 0.2,
} }
}} }}
> >
{/* Add helper invisible div to handle global styles during drag */}
{activeId && ( {activeId && (
<style dangerouslySetInnerHTML={{ <style dangerouslySetInnerHTML={{
__html: ` __html: `
@@ -1317,10 +1244,8 @@ export const ImageUploadStep = <T extends string>({
</div> </div>
<div className="flex items-start gap-2"> <div className="flex items-start gap-2">
{/* Dropzone for image upload always on the left */}
<ImageDropzone productIndex={index} /> <ImageDropzone productIndex={index} />
{/* Images appear to the right of the dropzone in a sortable container */}
<div <div
className={getProductContainerClasses(index)} className={getProductContainerClasses(index)}
style={{ style={{
@@ -1329,7 +1254,6 @@ export const ImageUploadStep = <T extends string>({
minHeight: '100px' minHeight: '100px'
}} }}
onDragOver={(e) => { onDragOver={(e) => {
// This is a native event handler to ensure the browser recognizes the drop zone
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
setActiveDroppableId(`product-${index}`); setActiveDroppableId(`product-${index}`);
@@ -1359,7 +1283,6 @@ export const ImageUploadStep = <T extends string>({
</DroppableContainer> </DroppableContainer>
</div> </div>
{/* Hidden file input for backwards compatibility */}
<Input <Input
ref={el => fileInputRefs.current[index] = el} ref={el => fileInputRefs.current[index] = el}
type="file" type="file"
@@ -1375,7 +1298,6 @@ export const ImageUploadStep = <T extends string>({
))} ))}
</div> </div>
{/* Drag overlay for showing the dragged image */}
<DragOverlay adjustScale={false} zIndex={1000} dropAnimation={null}> <DragOverlay adjustScale={false} zIndex={1000} dropAnimation={null}>
{activeId && activeImage && ( {activeId && activeImage && (
<div <div
@@ -1398,17 +1320,22 @@ export const ImageUploadStep = <T extends string>({
)} )}
</DragOverlay> </DragOverlay>
</DndContext> </DndContext>
</ScrollArea> </div>
</div>
</div>
<Separator /> {/* Footer - fixed at bottom */}
<div className="flex items-center justify-between border-t bg-muted px-8 py-4 mt-1 shrink-0">
<div className="p-4 flex justify-between">
{onBack && ( {onBack && (
<Button variant="outline" onClick={onBack}> <Button variant="outline" onClick={onBack}>
Back Back
</Button> </Button>
)} )}
<Button onClick={handleSubmit} disabled={isSubmitting || unassignedImages.length > 0}> <Button
className="ml-auto"
onClick={handleSubmit}
disabled={isSubmitting || unassignedImages.length > 0}
>
{isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />} {isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{unassignedImages.length > 0 ? 'Assign all images first' : 'Submit'} {unassignedImages.length > 0 ? 'Assign all images first' : 'Submit'}
</Button> </Button>