import React, { useRef, useState } from "react"; import { Image as ImageIcon, Send, Trash2 } from "lucide-react"; import { MessageBlock } from "./types"; import { useUploadFile } from "@/app/service/domain/service"; interface InputBarProps { onSend: (blocks: MessageBlock[]) => void; } export function InputBar({ onSend }: InputBarProps) { const [text, setText] = useState(""); const [isUploading, setIsUploading] = useState(false); const [uploadProgress, setUploadProgress] = useState(0); const [imageUrl, setImageUrl] = useState(null); const { uploadFile } = useUploadFile(); const handleSend = () => { const blocks: MessageBlock[] = []; if (text.trim()) blocks.push({ type: "text" as const, text: text.trim() }); if (imageUrl) blocks.push({ type: "image" as const, url: imageUrl }); if (!blocks.length) return; onSend(blocks); setText(""); setImageUrl(null); }; const handleFileUpload = async (file: File) => { try { setIsUploading(true); const url = await uploadFile(file, (progress) => { setUploadProgress(progress); }); setImageUrl(url); } catch (error) { console.error("上传失败:", error); // 可以添加错误提示 } finally { setIsUploading(false); setUploadProgress(0); } }; const onFileChange = async (e: React.ChangeEvent) => { const file = e.target.files?.[0]; // 保存对 input 元素的引用 const inputElement = e.currentTarget; if (file) { if (!file.type.startsWith('image/')) { alert('请选择图片文件'); inputElement.value = ""; // 重置 input return; } await handleFileUpload(file); // 使用保存的引用重置 input inputElement.value = ""; } }; const removeImage = () => { setImageUrl(null); }; return (
{/* 图片预览 */} {imageUrl && (
预览图
)} {/* 上传进度 */} {isUploading && (
)}
{/* 图片上传 */} {/* 文本输入 */} setText(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleSend(); } }} data-alt="text-input" /> {/* 发送按钮 */}
); }