vision-agent / lib /hooks /useImageUpload.ts
MingruiZhang's picture
mutil image selection
93dd66e
raw
history blame
1.53 kB
import { useAtom } from 'jotai';
import { DropzoneOptions, useDropzone } from 'react-dropzone';
import { DatasetImageEntity, datasetAtom } from '../../state';
import { toast } from 'react-hot-toast';
const useImageUpload = (options?: Partial<DropzoneOptions>) => {
const [, setTarget] = useAtom(datasetAtom);
const { getRootProps, getInputProps, isDragActive } = useDropzone({
accept: {
'image/*': ['.jpeg', '.png'],
},
multiple: true,
onDrop: acceptedFiles => {
if (acceptedFiles.length > 10) {
toast('You can only upload 10 images max.', {
icon: '⚠️',
});
}
acceptedFiles.slice(0, 10).forEach(file => {
try {
const reader = new FileReader();
reader.onloadend = () => {
const newImage = reader.result as string;
setTarget(prev => {
// Check if the image already exists in the state
if (
prev.length >= 10 ||
prev.find(entity => entity.url === newImage)
) {
// If it does, return the state unchanged
return prev;
} else {
// If it doesn't, add the new image to the state
return [
...prev,
{
url: newImage,
selected: false,
name: `i-${prev.length + 1}`,
} satisfies DatasetImageEntity,
];
}
});
};
reader.readAsDataURL(file);
} catch (err) {
console.error(err);
}
});
},
...options,
});
return { getRootProps, getInputProps, isDragActive };
};
export default useImageUpload;