image section

This commit is contained in:
hamid zarghami
2025-12-04 09:34:04 +03:30
parent 2c28218488
commit 26d3bd26ab
7 changed files with 292 additions and 27 deletions
@@ -1,29 +1,64 @@
import { Gallery } from "iconsax-react";
import Button from "@/components/Button";
import { type FC, useState, useRef } from "react";
import UploadBoxDraggble from "@/components/UploadBoxDraggble";
type ImageUploadProps = {
onImageUpload: (e: React.ChangeEvent<HTMLInputElement>) => void;
};
const ImageUpload = ({ onImageUpload }: ImageUploadProps) => {
const ImageUpload: FC<ImageUploadProps> = ({ onImageUpload }) => {
const [uploadedImages, setUploadedImages] = useState<string[]>([]);
const previousFilesCountRef = useRef<number>(0);
const handleFileChange = (files: File[]) => {
// Update ref to track current files count
if (files.length > previousFilesCountRef.current) {
// Process only new files
const newFiles = files.slice(previousFilesCountRef.current);
newFiles.forEach((file) => {
const reader = new FileReader();
reader.onload = (event) => {
const imageUrl = event.target?.result as string;
setUploadedImages((prev) => [...prev, imageUrl]);
// Create a synthetic event for onImageUpload
const syntheticEvent = {
target: {
files: [file],
},
} as unknown as React.ChangeEvent<HTMLInputElement>;
onImageUpload(syntheticEvent);
};
reader.readAsDataURL(file);
});
}
// Always update ref to track current files count
previousFilesCountRef.current = files.length;
};
const handlePreviewChange = (previews: string[]) => {
setUploadedImages(previews);
// Update ref when previews change (e.g., when files are deleted)
previousFilesCountRef.current = previews.length;
};
return (
<div>
<label className="block text-sm mb-2">آپلود تصویر</label>
<input
type="file"
accept="image/*"
onChange={onImageUpload}
className="hidden"
id="image-upload"
<div className="text-base font-bold mb-4">تصویر</div>
<UploadBoxDraggble
label="تصویر مورد نظر را آپلود کنید"
onChange={handleFileChange}
isMultiple={true}
preview={uploadedImages}
onChangePreview={handlePreviewChange}
/>
<Button
variant="outline"
onClick={() => document.getElementById("image-upload")?.click()}
className="w-full"
>
<Gallery size={20} />
انتخاب تصویر
</Button>
{uploadedImages.length > 0 && (
<div className="mt-4 text-description text-xs">
تصویر های آپلود شده
</div>
)}
</div>
);
};