refactor: update setFiles prop type to accept File[] and simplify file handling

This commit is contained in:
dayuan.jiang
2025-03-27 08:02:03 +00:00
parent 34cc437523
commit 7e0790d60f
6 changed files with 199 additions and 67 deletions

View File

@@ -3,13 +3,8 @@ export default function ExamplePanel({
setFiles, setFiles,
}: { }: {
setInput: (input: string) => void; setInput: (input: string) => void;
setFiles: (files: FileList | undefined) => void; setFiles: (files: File[]) => void;
}) { }) {
const createFileList = (file: File): FileList => {
const dt = new DataTransfer();
dt.items.add(file);
return dt.files;
};
// New handler for the "Replicate this flowchart" button // New handler for the "Replicate this flowchart" button
const handleReplicateFlowchart = async () => { const handleReplicateFlowchart = async () => {
setInput("Replicate this flowchart."); setInput("Replicate this flowchart.");
@@ -21,7 +16,7 @@ export default function ExamplePanel({
const file = new File([blob], "example.png", { type: "image/png" }); const file = new File([blob], "example.png", { type: "image/png" });
// Set the file to the files state // Set the file to the files state
setFiles(createFileList(file)); setFiles([file]);
} catch (error) { } catch (error) {
console.error("Error loading example image:", error); console.error("Error loading example image:", error);
} }

View File

@@ -13,8 +13,7 @@ import {
History, History,
} from "lucide-react"; } from "lucide-react";
import { ButtonWithTooltip } from "@/components/button-with-tooltip"; import { ButtonWithTooltip } from "@/components/button-with-tooltip";
import Image from "next/image"; import { FilePreviewList } from "./file-preview-list";
import { useDiagram } from "@/contexts/diagram-context"; import { useDiagram } from "@/contexts/diagram-context";
import { HistoryDialog } from "@/components/history-dialog"; import { HistoryDialog } from "@/components/history-dialog";
@@ -24,8 +23,8 @@ interface ChatInputProps {
onSubmit: (e: React.FormEvent<HTMLFormElement>) => void; onSubmit: (e: React.FormEvent<HTMLFormElement>) => void;
onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void; onChange: (e: React.ChangeEvent<HTMLTextAreaElement>) => void;
onClearChat: () => void; onClearChat: () => void;
files?: FileList; files?: File[];
onFileChange?: (files: FileList | undefined) => void; onFileChange?: (files: File[]) => void;
showHistory?: boolean; showHistory?: boolean;
onToggleHistory?: (show: boolean) => void; onToggleHistory?: (show: boolean) => void;
} }
@@ -36,8 +35,8 @@ export function ChatInput({
onSubmit, onSubmit,
onChange, onChange,
onClearChat, onClearChat,
files, files = [],
onFileChange, onFileChange = () => {},
showHistory = false, showHistory = false,
onToggleHistory = () => {}, onToggleHistory = () => {},
}: ChatInputProps) { }: ChatInputProps) {
@@ -73,19 +72,24 @@ export function ChatInput({
// Handle file changes // Handle file changes
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => { const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (onFileChange) { const newFiles = Array.from(e.target.files || []);
onFileChange(e.target.files || undefined); onFileChange([...files, ...newFiles]);
};
// Remove individual file
const handleRemoveFile = (fileToRemove: File) => {
onFileChange(files.filter((file) => file !== fileToRemove));
if (fileInputRef.current) {
fileInputRef.current.value = "";
} }
}; };
// Clear file selection // Clear all files
const clearFiles = () => { const clearFiles = () => {
if (fileInputRef.current) { if (fileInputRef.current) {
fileInputRef.current.value = ""; fileInputRef.current.value = "";
} }
if (onFileChange) { onFileChange([]);
onFileChange(undefined);
}
}; };
// Trigger file input click // Trigger file input click
@@ -116,17 +120,12 @@ export function ChatInput({
const droppedFiles = e.dataTransfer.files; const droppedFiles = e.dataTransfer.files;
// Only process image files // Only process image files
if (droppedFiles.length > 0) {
const imageFiles = Array.from(droppedFiles).filter((file) => const imageFiles = Array.from(droppedFiles).filter((file) =>
file.type.startsWith("image/") file.type.startsWith("image/")
); );
if (imageFiles.length > 0 && onFileChange) { if (imageFiles.length > 0) {
// Create a new FileList-like object with only image files onFileChange([...files, ...imageFiles]);
const dt = new DataTransfer();
imageFiles.forEach((file) => dt.items.add(file));
onFileChange(dt.files);
}
} }
}; };
@@ -156,38 +155,7 @@ export function ChatInput({
onDragLeave={handleDragLeave} onDragLeave={handleDragLeave}
onDrop={handleDrop} onDrop={handleDrop}
> >
{/* File preview area */} <FilePreviewList files={files} onRemoveFile={handleRemoveFile} />
{files && files.length > 0 && (
<div className="flex flex-wrap gap-2 mt-2 p-2 bg-muted/50 rounded-md">
{Array.from(files).map((file, index) => (
<div key={index} className="relative group">
<div className="w-20 h-20 border rounded-md overflow-hidden bg-muted">
{file.type.startsWith("image/") ? (
<Image
src={URL.createObjectURL(file)}
alt={file.name}
width={80}
height={80}
className="object-cover w-full h-full"
/>
) : (
<div className="flex items-center justify-center h-full text-xs text-center p-1">
{file.name}
</div>
)}
</div>
<button
type="button"
onClick={clearFiles}
className="absolute -top-2 -right-2 bg-destructive rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
aria-label="Remove file"
>
<X className="h-3 w-3" />
</button>
</div>
))}
</div>
)}
<Textarea <Textarea
ref={textareaRef} ref={textareaRef}

View File

@@ -14,7 +14,7 @@ interface ChatMessageDisplayProps {
messages: Message[]; messages: Message[];
error?: Error | null; error?: Error | null;
setInput: (input: string) => void; setInput: (input: string) => void;
setFiles: (files: FileList | undefined) => void; setFiles: (files: File[]) => void;
} }
export function ChatMessageDisplay({ export function ChatMessageDisplay({

View File

@@ -33,10 +33,17 @@ export default function ChatPanel() {
// Add a step counter to track updates // Add a step counter to track updates
// Add state for file attachments // Add state for file attachments
const [files, setFiles] = useState<FileList | undefined>(undefined); const [files, setFiles] = useState<File[]>([]);
// Add state for showing the history dialog // Add state for showing the history dialog
const [showHistory, setShowHistory] = useState(false); const [showHistory, setShowHistory] = useState(false);
// Convert File[] to FileList for experimental_attachments
const createFileList = (files: File[]): FileList => {
const dt = new DataTransfer();
files.forEach((file) => dt.items.add(file));
return dt.files;
};
// Remove the currentXmlRef and related useEffect // Remove the currentXmlRef and related useEffect
const { const {
messages, messages,
@@ -79,11 +86,12 @@ export default function ChatPanel() {
data: { data: {
xml: chartXml, xml: chartXml,
}, },
experimental_attachments: files, experimental_attachments:
files.length > 0 ? createFileList(files) : undefined,
}); });
// Clear files after submission // Clear files after submission
setFiles(undefined); setFiles([]);
} catch (error) { } catch (error) {
console.error("Error fetching chart data:", error); console.error("Error fetching chart data:", error);
} }
@@ -91,10 +99,9 @@ export default function ChatPanel() {
}; };
// Helper function to handle file changes // Helper function to handle file changes
const handleFileChange = (newFiles: FileList | undefined) => { const handleFileChange = (newFiles: File[]) => {
setFiles(newFiles); setFiles(newFiles);
}; };
// Helper function to handle file input change
return ( return (
<Card className="h-full flex flex-col rounded-none py-0 gap-0"> <Card className="h-full flex flex-col rounded-none py-0 gap-0">

View File

@@ -0,0 +1,57 @@
"use client";
import React, { useEffect } from "react";
import Image from "next/image";
import { X } from "lucide-react";
interface FilePreviewListProps {
files: File[];
onRemoveFile: (fileToRemove: File) => void;
}
export function FilePreviewList({ files, onRemoveFile }: FilePreviewListProps) {
// Cleanup object URLs on unmount
useEffect(() => {
const objectUrls = files
.filter((file) => file.type.startsWith("image/"))
.map((file) => URL.createObjectURL(file));
return () => {
objectUrls.forEach(URL.revokeObjectURL);
};
}, [files]);
if (files.length === 0) return null;
return (
<div className="flex flex-wrap gap-2 mt-2 p-2 bg-muted/50 rounded-md">
{files.map((file, index) => (
<div key={file.name + index} className="relative group">
<div className="w-20 h-20 border rounded-md overflow-hidden bg-muted">
{file.type.startsWith("image/") ? (
<Image
src={URL.createObjectURL(file)}
alt={file.name}
width={80}
height={80}
className="object-cover w-full h-full"
/>
) : (
<div className="flex items-center justify-center h-full text-xs text-center p-1">
{file.name}
</div>
)}
</div>
<button
type="button"
onClick={() => onRemoveFile(file)}
className="absolute -top-2 -right-2 bg-destructive rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
aria-label="Remove file"
>
<X className="h-3 w-3" />
</button>
</div>
))}
</div>
);
}

105
package-lock.json generated
View File

@@ -4315,6 +4315,111 @@
"type": "github", "type": "github",
"url": "https://github.com/sponsors/wooorm" "url": "https://github.com/sponsors/wooorm"
} }
},
"node_modules/@next/swc-darwin-arm64": {
"version": "15.2.3",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-15.2.3.tgz",
"integrity": "sha512-uaBhA8aLbXLqwjnsHSkxs353WrRgQgiFjduDpc7YXEU0B54IKx3vU+cxQlYwPCyC8uYEEX7THhtQQsfHnvv8dw==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-darwin-x64": {
"version": "15.2.3",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-15.2.3.tgz",
"integrity": "sha512-pVwKvJ4Zk7h+4hwhqOUuMx7Ib02u3gDX3HXPKIShBi9JlYllI0nU6TWLbPT94dt7FSi6mSBhfc2JrHViwqbOdw==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-arm64-gnu": {
"version": "15.2.3",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-15.2.3.tgz",
"integrity": "sha512-50ibWdn2RuFFkOEUmo9NCcQbbV9ViQOrUfG48zHBCONciHjaUKtHcYFiCwBVuzD08fzvzkWuuZkd4AqbvKO7UQ==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-arm64-musl": {
"version": "15.2.3",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-15.2.3.tgz",
"integrity": "sha512-2gAPA7P652D3HzR4cLyAuVYwYqjG0mt/3pHSWTCyKZq/N/dJcUAEoNQMyUmwTZWCJRKofB+JPuDVP2aD8w2J6Q==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-x64-musl": {
"version": "15.2.3",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-15.2.3.tgz",
"integrity": "sha512-ZR9kLwCWrlYxwEoytqPi1jhPd1TlsSJWAc+H/CJHmHkf2nD92MQpSRIURR1iNgA/kuFSdxB8xIPt4p/T78kwsg==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-win32-arm64-msvc": {
"version": "15.2.3",
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-15.2.3.tgz",
"integrity": "sha512-+G2FrDcfm2YDbhDiObDU/qPriWeiz/9cRR0yMWJeTLGGX6/x8oryO3tt7HhodA1vZ8r2ddJPCjtLcpaVl7TE2Q==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-win32-x64-msvc": {
"version": "15.2.3",
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-15.2.3.tgz",
"integrity": "sha512-gHYS9tc+G2W0ZC8rBL+H6RdtXIyk40uLiaos0yj5US85FNhbFEndMA2nW3z47nzOWiSvXTZ5kBClc3rD0zJg0w==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
} }
} }
} }