"use client"; import { useEffect, useState, useCallback, use } from "react"; import { useRouter } from "next/navigation"; import Link from "next/link"; import { ArrowLeft, Save, Undo2, Redo2, ZoomIn, ZoomOut, MousePointer, Hand, Plus, ImagePlus, Video, Type, Loader2, Settings, Trash2, Scissors, Sparkles, Expand, Maximize2, Move3D, Layers, MoreHorizontal, PanelLeftClose, PanelLeft, Download, Upload, Wand2, Grid3X3, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Textarea } from "@/components/ui/textarea"; import { Label } from "@/components/ui/label"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "@/components/ui/tooltip"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Separator } from "@/components/ui/separator"; import { Slider } from "@/components/ui/slider"; import { ScrollArea } from "@/components/ui/scroll-area"; import { toast } from "sonner"; import { useCanvasStore, canvasSelectors } from "@/store/canvas"; import { canvasService, imageGenerationService } from "@/services/canvas"; import { CanvasWorkspace } from "@/components/canvas"; import { cn } from "@/lib/utils"; interface PageProps { params: Promise<{ id: string }>; } // 图片尺寸预设 const SIZE_PRESETS = [ { label: "1:1", value: "1:1", width: 1024, height: 1024 }, { label: "3:2", value: "3:2", width: 1536, height: 1024 }, { label: "2:3", value: "2:3", width: 1024, height: 1536 }, { label: "4:3", value: "4:3", width: 1365, height: 1024 }, { label: "3:4", value: "3:4", width: 1024, height: 1365 }, { label: "16:9", value: "16:9", width: 1820, height: 1024 }, { label: "9:16", value: "9:16", width: 1024, height: 1820 }, ]; export default function CanvasEditorPage({ params }: PageProps) { const { id } = use(params); const router = useRouter(); // Store state const projectTitle = useCanvasStore((state) => state.projectTitle); const viewport = useCanvasStore(canvasSelectors.viewport); const tool = useCanvasStore(canvasSelectors.tool); const canUndo = useCanvasStore(canvasSelectors.canUndo); const canRedo = useCanvasStore(canvasSelectors.canRedo); const isGenerating = useCanvasStore(canvasSelectors.isGenerating); const selectedNodeIds = useCanvasStore(canvasSelectors.selectedNodeIds); const nodes = useCanvasStore(canvasSelectors.nodes); // Store actions const setProject = useCanvasStore((state) => state.setProject); const setProjectTitle = useCanvasStore((state) => state.setProjectTitle); const setTool = useCanvasStore((state) => state.setTool); const zoomIn = useCanvasStore((state) => state.zoomIn); const zoomOut = useCanvasStore((state) => state.zoomOut); const undo = useCanvasStore((state) => state.undo); const redo = useCanvasStore((state) => state.redo); const loadCanvas = useCanvasStore((state) => state.loadCanvas); const getCanvasState = useCanvasStore((state) => state.getCanvasState); const addNode = useCanvasStore((state) => state.addNode); const updateNode = useCanvasStore((state) => state.updateNode); const setGenerating = useCanvasStore((state) => state.setGenerating); // Local state const [isLoading, setIsLoading] = useState(true); const [isSaving, setIsSaving] = useState(false); const [isEditingTitle, setIsEditingTitle] = useState(false); const [editTitle, setEditTitle] = useState(""); const [isPanelOpen, setIsPanelOpen] = useState(true); // 生成配置 const [prompt, setPrompt] = useState(""); const [negativePrompt, setNegativePrompt] = useState(""); const [aspectRatio, setAspectRatio] = useState("1:1"); const [imageCount, setImageCount] = useState(1); // 获取选中的图片节点 const selectedImageNode = selectedNodeIds.length === 1 ? nodes.find(n => n.id === selectedNodeIds[0] && n.type === 'image') : null; // 加载画布数据 useEffect(() => { const loadProject = async () => { setIsLoading(true); const result = await canvasService.getProject(id); if (result.success && result.data) { setProject(id, result.data.title); if (result.data.canvasData) { loadCanvas(result.data.canvasData); } } else { toast.error(result.error || "加载画布失败"); router.push("/canvas"); } setIsLoading(false); }; loadProject(); }, [id]); // 保存画布 const handleSave = useCallback(async () => { setIsSaving(true); const canvasData = getCanvasState(); const result = await canvasService.saveCanvasState(id, canvasData); if (result.success) { toast.success("保存成功"); } else { toast.error(result.error || "保存失败"); } setIsSaving(false); }, [id, getCanvasState]); // 更新标题 const handleUpdateTitle = async () => { if (!editTitle.trim() || editTitle === projectTitle) { setIsEditingTitle(false); return; } const result = await canvasService.updateProject(id, { title: editTitle.trim() }); if (result.success) { setProjectTitle(editTitle.trim()); } else { toast.error(result.error || "更新标题失败"); } setIsEditingTitle(false); }; // 添加文本节点 const handleAddTextNode = () => { addNode({ type: 'text', position: { x: 100 + Math.random() * 200, y: 100 + Math.random() * 200 }, size: { width: 200, height: 100 }, data: { content: '双击编辑文本' }, connections: [], }); }; // 添加图片节点 const handleAddImageNode = () => { addNode({ type: 'image', position: { x: 100 + Math.random() * 200, y: 100 + Math.random() * 200 }, size: { width: 300, height: 300 }, data: { src: '', status: 'pending', prompt: '', }, connections: [], }); }; // 添加视频节点 const handleAddVideoNode = () => { addNode({ type: 'video', position: { x: 100 + Math.random() * 200, y: 100 + Math.random() * 200 }, size: { width: 400, height: 300 }, data: { src: '', status: 'pending', prompt: '', }, connections: [], }); }; // AI 生成图片 const handleGenerate = async () => { if (!prompt.trim()) { toast.error("请输入提示词"); return; } setGenerating(true); // 获取尺寸预设 const sizePreset = SIZE_PRESETS.find(s => s.value === aspectRatio) || SIZE_PRESETS[0]; // 先创建占位节点(显示生成中状态) const placeholderNodeIds: string[] = []; for (let i = 0; i < imageCount; i++) { const nodeId = addNode({ type: 'image', position: { x: 100 + (i % 3) * 320, y: 100 + Math.floor(i / 3) * 320 }, size: { width: 300, height: 300 }, data: { src: '', status: 'generating', prompt: prompt, }, connections: [], }); placeholderNodeIds.push(nodeId); } try { // 调用 AI 图片生成 API const result = await imageGenerationService.generateImage({ prompt, negativePrompt, aspectRatio, imageCount, }); if (result.success && result.data?.images) { // 更新节点为生成的图片 result.data.images.forEach((image, index) => { if (placeholderNodeIds[index]) { updateNode(placeholderNodeIds[index], { data: { src: image.originalUrl || image.thumbnailUrl, status: 'completed', prompt: prompt, }, }); } }); toast.success(`成功生成 ${result.data.images.length} 张图片`); setPrompt(""); // 清空提示词 } else { // 生成失败,更新节点状态 placeholderNodeIds.forEach(nodeId => { updateNode(nodeId, { data: { src: '', status: 'failed', prompt: prompt, }, }); }); toast.error(result.error || "图片生成失败"); } } catch (error) { console.error("AI 图片生成失败:", error); // 生成失败,更新节点状态 placeholderNodeIds.forEach(nodeId => { updateNode(nodeId, { data: { src: '', status: 'failed', prompt: prompt, }, }); }); toast.error("图片生成失败,请重试"); } finally { setGenerating(false); } }; // 键盘快捷键 useEffect(() => { const handleKeyDown = (e: KeyboardEvent) => { // 如果正在输入则不触发快捷键 if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) { return; } // Ctrl/Cmd + S 保存 if ((e.ctrlKey || e.metaKey) && e.key === 's') { e.preventDefault(); handleSave(); } // Ctrl/Cmd + Z 撤销 if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) { e.preventDefault(); undo(); } // Ctrl/Cmd + Shift + Z 重做 if ((e.ctrlKey || e.metaKey) && e.key === 'z' && e.shiftKey) { e.preventDefault(); redo(); } // V 选择工具 if (e.key === 'v' && !e.ctrlKey && !e.metaKey) { setTool('select'); } // H 平移工具 if (e.key === 'h' && !e.ctrlKey && !e.metaKey) { setTool('pan'); } // Delete 删除选中 if (e.key === 'Delete' || e.key === 'Backspace') { useCanvasStore.getState().deleteSelectedNodes(); } }; window.addEventListener('keydown', handleKeyDown); return () => window.removeEventListener('keydown', handleKeyDown); }, [handleSave, undo, redo, setTool]); if (isLoading) { return (
选中图片节点以使用编辑工具
)}