'use client'; import React, { useState } from 'react'; import useImageUpload from '../../lib/hooks/useImageUpload'; import { cn, fetcher } from '@/lib/utils'; import { SignedPayload, MessageBase, ChatEntity } from '@/lib/types'; import { useRouter } from 'next/navigation'; import Loading from '../ui/Loading'; import toast from 'react-hot-toast'; export interface ImageSelectorProps { } type Example = { url: string; initMessages: MessageBase[]; }; const ImageSelector: React.FC = () => { const router = useRouter(); const [isUploading, setUploading] = useState(false); const { getRootProps, getInputProps, isDragActive } = useImageUpload( undefined, async files => { const formData = new FormData(); if (files.length !== 1) { throw new Error('Only one image can be uploaded at a time'); } setUploading(true); const reader = new FileReader(); reader.readAsDataURL(files[0]); reader.onload = async () => { const { id, signedUrl, publicUrl, fields } = await fetcher('/api/sign', { method: 'POST', body: JSON.stringify({ fileType: files[0].type, fileName: files[0].name, }), }); const formData = new FormData(); Object.entries(fields).forEach(([key, value]) => { formData.append(key, value as string) }) formData.append('file', files[0]); const uploadResponse = await fetch(signedUrl, { method: 'POST', body: formData, }) if (!uploadResponse.ok) { toast.error(uploadResponse.statusText); return; } const resp = await fetcher('/api/upload', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ id, url: publicUrl, }), }); setUploading(false); if (resp) { router.push(`/chat/${resp.id}`); } } }); return (
{isUploading ? ( ) : ( 'Drag or drop image here, or click to select images' )}
); }; export default ImageSelector;