CanvasAnvil is an open source AI diagram maker and flowchart generator - an infinite-canvas diagram editor and self-hosted drawio alternative that writes editable .drawio files. Text to diagram, then fix nodes, layout and labels in place. Also AI presentations, interior design CAD/BOM, posters and infographics.
TypeScript ai-agentsai-diagramai-presentationbomcadcanvasdiagramdiagram-generatordrawioflowchartinfographicspptppt-generatorpresentation-generatorreactsvgedittext-to-diagramtypescriptworkflow
cad_drawio_acc
codingFeng101bad967db8f9e
diff --git a/.dockerignore b/.dockerignorenew file mode 100644index 0000000..3c77fac--- /dev/null+++ b/.dockerignore@@ -0,0 +1,10 @@+node_modules+dist+.git+.DS_Store+*.log+.env+.env.*+coverage+.trae+diff --git a/deploy/README.md b/deploy/README.mdnew file mode 100644index 0000000..098776e--- /dev/null+++ b/deploy/README.md@@ -0,0 +1,49 @@+# Deploy++该项目为纯前端静态站点(Vite 构建产物为 `dist/`),可用任意静态资源服务器部署。++## 目录结构++- `deploy/host/`:传统(主机/裸机)部署+- `deploy/docker/`:Docker 镜像与 Compose 部署++## 传统部署(Host)++1. 构建产物++```bash+./deploy/host/build.sh+```++或(Windows)++```powershell+.\deploy\host\build.ps1+```++2. 上传 `dist/` 到服务器,例如:++- `/var/www/unified-ai-workspace/dist`++3. Nginx 配置++将 `deploy/host/nginx.conf` 作为站点配置启用(并按实际目录调整 `root`),重载 Nginx 后访问即可。++## Docker 部署++方式 A:Compose(推荐)++```bash+docker compose -f deploy/docker/docker-compose.yml up -d --build+```++默认对外端口:`http://localhost:8080/`++方式 B:直接构建镜像++```bash+docker build -f deploy/docker/Dockerfile -t unified-ai-workspace:latest .+docker run --rm -p 8080:80 unified-ai-workspace:latest+```++Docker 构建使用项目根目录的 `.dockerignore` 以避免把 `node_modules/` 等无关内容打进构建上下文。diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfilenew file mode 100644index 0000000..bdc9a87--- /dev/null+++ b/deploy/docker/Dockerfile@@ -0,0 +1,15 @@+FROM node:20-alpine AS build++WORKDIR /app+COPY package.json package-lock.json ./+RUN npm ci+COPY . .+RUN npm run build++FROM nginx:1.27-alpine++COPY deploy/docker/nginx.conf /etc/nginx/conf.d/default.conf+COPY --from=build /app/dist /usr/share/nginx/html++EXPOSE 80+diff --git a/deploy/docker/docker-compose.yml b/deploy/docker/docker-compose.ymlnew file mode 100644index 0000000..74cbe63--- /dev/null+++ b/deploy/docker/docker-compose.yml@@ -0,0 +1,8 @@+services:+ web:+ build:+ context: ../..+ dockerfile: deploy/docker/Dockerfile+ ports:+ - "8080:80"+diff --git a/deploy/docker/nginx.conf b/deploy/docker/nginx.confnew file mode 100644index 0000000..6caae47--- /dev/null+++ b/deploy/docker/nginx.conf@@ -0,0 +1,18 @@+server {+ listen 80;+ server_name _;++ root /usr/share/nginx/html;+ index index.html;++ location / {+ try_files $uri $uri/ /index.html;+ }++ location ~* \.(?:js|css|png|jpg|jpeg|gif|svg|webp|ico|woff2?|ttf|eot)$ {+ expires 30d;+ add_header Cache-Control "public, max-age=2592000, immutable";+ try_files $uri =404;+ }+}+diff --git a/deploy/host/build.ps1 b/deploy/host/build.ps1new file mode 100644index 0000000..25f6b49--- /dev/null+++ b/deploy/host/build.ps1@@ -0,0 +1,5 @@+$ErrorActionPreference = "Stop"++npm ci+npm run build+diff --git a/deploy/host/build.sh b/deploy/host/build.shnew file mode 100644index 0000000..1b6a4d2--- /dev/null+++ b/deploy/host/build.sh@@ -0,0 +1,6 @@+#!/usr/bin/env sh+set -euo pipefail++npm ci+npm run build+diff --git a/deploy/host/nginx.conf b/deploy/host/nginx.confnew file mode 100644index 0000000..1e2768c--- /dev/null+++ b/deploy/host/nginx.conf@@ -0,0 +1,18 @@+server {+ listen 80;+ server_name _;++ root /var/www/unified-ai-workspace/dist;+ index index.html;++ location / {+ try_files $uri $uri/ /index.html;+ }++ location ~* \.(?:js|css|png|jpg|jpeg|gif|svg|webp|ico|woff2?|ttf|eot)$ {+ expires 30d;+ add_header Cache-Control "public, max-age=2592000, immutable";+ try_files $uri =404;+ }+}+diff --git a/eslint.config.js b/eslint.config.jsindex 092408a..21469f2 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -19,6 +19,10 @@ export default tseslint.config(},rules: {...reactHooks.configs.recommended.rules,+ '@typescript-eslint/no-explicit-any': 'warn',+ '@typescript-eslint/no-unused-vars': 'warn',+ 'no-empty': 'warn',+ 'prefer-const': 'warn','react-refresh/only-export-components': ['warn',{ allowConstantExport: true },diff --git a/src/App.tsx b/src/App.tsxindex ee5be57..d056b07 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -18,6 +18,8 @@ import { Button } from "@/components/ui/button";type WorkspaceType = 'flow' | 'cad' | 'ppt';const HISTORY_STORAGE_KEY = 'unified-ai-workspace-history';+const CAD_WORKSPACE_STORAGE_KEY = 'unified-ai-workspace-cad-state-v1';+const FLOW_WORKSPACE_STORAGE_KEY = 'unified-ai-workspace-flow-state-v1';class ErrorBoundary extends React.Component<{ children: React.ReactNode }, { error: Error | null }> {state: { error: Error | null } = { error: null };@@ -56,18 +58,64 @@ class ErrorBoundary extends React.Component<{ children: React.ReactNode }, { err}function App() {+ const initialFlowState = (() => {+ if (typeof window === "undefined") return null;+ try {+ const raw = localStorage.getItem(FLOW_WORKSPACE_STORAGE_KEY);+ const parsed = raw ? JSON.parse(raw) : null;+ if (!parsed || typeof parsed !== "object") return null;+ return parsed as any;+ } catch {+ return null;+ }+ })();++ const initialCadState = (() => {+ if (typeof window === "undefined") return null;+ try {+ const raw = localStorage.getItem(CAD_WORKSPACE_STORAGE_KEY);+ const parsed = raw ? JSON.parse(raw) : null;+ if (!parsed || typeof parsed !== "object") return null;+ return parsed as any;+ } catch {+ return null;+ }+ })();+const [showLanding, setShowLanding] = useState(true);const [activeWorkspace, setActiveWorkspace] = useState<WorkspaceType>('flow');const [attachments, setAttachments] = useState<{ id: string; type: 'xml' | 'python' | 'json'; content: string; name: string }[]>([]);// Workspace specific states- const [generatedXml, setGeneratedXml] = useState<string | undefined>(undefined);- const [cad2dSvg, setCad2dSvg] = useState<string | undefined>(undefined);- const [cadPlan, setCadPlan] = useState<any>(null);- const [cadImages, setCadImages] = useState<{ title: string; url: string }[]>([]);+ const [generatedXml, setGeneratedXml] = useState<string | undefined>(() => {+ const v = initialFlowState?.generatedXml;+ return typeof v === "string" ? v : undefined;+ });+ const [cad2dSvg, setCad2dSvg] = useState<string | undefined>(() => {+ const v = initialCadState?.cad2dSvg;+ return typeof v === "string" ? v : undefined;+ });+ const [cadPlan, setCadPlan] = useState<any>(() => (initialCadState?.cadPlan ?? null));+ const [cadImages, setCadImages] = useState<{ title: string; url: string }[]>(() => {+ const v = initialCadState?.cadImages;+ return Array.isArray(v)+ ? v+ .filter((x: any) => x && typeof x.title === "string" && typeof x.url === "string")+ .map((x: any) => ({ title: x.title, url: x.url }))+ : [];+ });const [cadImagesLoading, setCadImagesLoading] = useState(false);- const [cadBom, setCadBom] = useState<{ columns: string[]; rows: any[] } | null>(null);- const [cadFocusPanel, setCadFocusPanel] = useState<"2d" | "renders" | "bom" | null>(null);+ const [cadBom, setCadBom] = useState<{ columns: string[]; rows: any[] } | null>(() => {+ const v = initialCadState?.cadBom;+ if (!v || typeof v !== "object") return null;+ const columns = Array.isArray((v as any).columns) ? (v as any).columns.filter((c: any) => typeof c === "string") : [];+ const rows = Array.isArray((v as any).rows) ? (v as any).rows : [];+ return { columns, rows };+ });+ const [cadFocusPanel, setCadFocusPanel] = useState<"2d" | "renders" | "bom" | null>(() => {+ const v = initialCadState?.cadFocusPanel;+ return v === "2d" || v === "renders" || v === "bom" ? v : null;+ });const [pptIncomingEdit, setPptIncomingEdit] = useState<{ id: string; payload: string } | null>(null);const [pptDraftSlides, setPptDraftSlides] = useState<Array<{ id: string; slideId: string; title: string; json: string; kind: "outline" | "slide_image"; imageUrl?: string }>>([]);const cadImageObjectUrlsRef = useRef<string[]>([]);@@ -99,6 +147,38 @@ function App() {localStorage.setItem(HISTORY_STORAGE_KEY, JSON.stringify(versionHistories));}, [versionHistories]);+ useEffect(() => {+ if (typeof window === "undefined") return;+ try {+ localStorage.setItem(+ FLOW_WORKSPACE_STORAGE_KEY,+ JSON.stringify({+ generatedXml: typeof generatedXml === "string" ? generatedXml : null,+ updatedAt: Date.now(),+ })+ );+ } catch {+ }+ }, [generatedXml]);++ useEffect(() => {+ if (typeof window === "undefined") return;+ try {+ localStorage.setItem(+ CAD_WORKSPACE_STORAGE_KEY,+ JSON.stringify({+ cad2dSvg: typeof cad2dSvg === "string" ? cad2dSvg : null,+ cadPlan: cadPlan ?? null,+ cadImages,+ cadBom,+ cadFocusPanel,+ updatedAt: Date.now(),+ })+ );+ } catch {+ }+ }, [cad2dSvg, cadPlan, cadImages, cadBom, cadFocusPanel]);+useEffect(() => {const nextObjectUrls = cadImages.map((x) => x?.url)@@ -372,6 +452,7 @@ function App() {{activeWorkspace === 'flow' && (<FlowchartWorkspaceinitialXml={generatedXml}+ onXmlChange={setGeneratedXml}onAddToChat={(code) => handleAddToChat(code, 'xml', 'diagram.xml')}/>)}diff --git a/src/components/ChatInput.tsx b/src/components/ChatInput.tsxindex 0f8dfd7..5b17a77 100644--- a/src/components/ChatInput.tsx+++ b/src/components/ChatInput.tsx@@ -28,7 +28,7 @@ interface ChatInputProps {insertPptToken?: { key: number; slideId: string; label: string; tag: string } | null;onInsertPptTokenHandled?: () => void;clearKey?: string | number;- uploadMode?: "all" | "imagesOnly" | "none";+ uploadMode?: "all" | "imagesOnly" | "filesOnly" | "none";}export function ChatInput({@@ -267,6 +267,12 @@ export function ChatInput({const showRichPlaceholder = isRich && !richPlainText.trim() && !richHasFocus;+ const filterByUploadMode = (incoming: File[]) => {+ if (uploadMode === "imagesOnly") return incoming.filter((f) => f.type.startsWith("image/"));+ if (uploadMode === "filesOnly") return incoming.filter((f) => !f.type.startsWith("image/"));+ return incoming;+ };+const handlePaste = (e: React.ClipboardEvent) => {if (uploadMode === "none") return;const items = e.clipboardData.items;@@ -280,7 +286,7 @@ export function ChatInput({}if (pastedFiles.length > 0) {- const filtered = uploadMode === "imagesOnly" ? pastedFiles.filter((f) => f.type.startsWith("image/")) : pastedFiles;+ const filtered = filterByUploadMode(pastedFiles);if (filtered.length === 0) return;e.preventDefault();handleFileChange([...files, ...filtered]);@@ -291,7 +297,7 @@ export function ChatInput({e.preventDefault();if (uploadMode === "none") return;const droppedFiles = Array.from(e.dataTransfer.files);- const filtered = uploadMode === "imagesOnly" ? droppedFiles.filter((f) => f.type.startsWith("image/")) : droppedFiles;+ const filtered = filterByUploadMode(droppedFiles);if (filtered.length > 0) {handleFileChange([...files, ...filtered]);}@@ -303,7 +309,7 @@ export function ChatInput({const onFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {if (e.target.files?.length) {const incoming = Array.from(e.target.files);- const filtered = uploadMode === "imagesOnly" ? incoming.filter((f) => f.type.startsWith("image/")) : incoming;+ const filtered = filterByUploadMode(incoming);if (filtered.length > 0) handleFileChange([...files, ...filtered]);e.target.value = ''; // Reset}@@ -319,7 +325,7 @@ export function ChatInput({onDragOver={(e) => e.preventDefault()}onDrop={handleDrop}>- {uploadMode !== "none" && (+ {(uploadMode === "all" || uploadMode === "imagesOnly") && (<inputtype="file"multiple@@ -329,10 +335,15 @@ export function ChatInput({onChange={onFileInputChange}/>)}- {uploadMode === "all" && (+ {(uploadMode === "all" || uploadMode === "filesOnly") && (<inputtype="file"multiple+ accept={+ uploadMode === "filesOnly"+ ? ".pdf,application/pdf,text/*,.txt,.md,.markdown,.json,.csv,.xml,.yaml,.yml,.toml"+ : "image/*,.pdf,application/pdf,text/*,.txt,.md,.markdown,.json,.csv,.xml,.yaml,.yml,.toml"+ }className="hidden"ref={fileInputRef}onChange={onFileInputChange}@@ -497,17 +508,19 @@ export function ChatInput({</ButtonWithTooltip>)}- <ButtonWithTooltip- tooltipContent="上传图片"- variant="ghost"- size="icon"- onClick={handleImageUpload}- className="h-9 w-9 text-muted-foreground hover:text-foreground rounded-lg"- >- <ImageIcon className="w-5 h-5" />- </ButtonWithTooltip>+ {(uploadMode === "all" || uploadMode === "imagesOnly") && (+ <ButtonWithTooltip+ tooltipContent="上传图片"+ variant="ghost"+ size="icon"+ onClick={handleImageUpload}+ className="h-9 w-9 text-muted-foreground hover:text-foreground rounded-lg"+ >+ <ImageIcon className="w-5 h-5" />+ </ButtonWithTooltip>+ )}- {uploadMode === "all" && (+ {(uploadMode === "all" || uploadMode === "filesOnly") && (<ButtonWithTooltiptooltipContent="上传文件"variant="ghost"diff --git a/src/components/ChatPanel.tsx b/src/components/ChatPanel.tsxindex 2b62995..32ae0b1 100644--- a/src/components/ChatPanel.tsx+++ b/src/components/ChatPanel.tsx@@ -367,6 +367,8 @@ export function ChatPanel({});};+ const displayFileTexts: string[] = [];+for (const file of files) {if (file.type.startsWith('image/')) {try {@@ -392,10 +394,14 @@ export function ChatPanel({} else {content = await extractTextFileContent(file);}- fileTexts.push(`[${isPdfFile(file) ? 'PDF' : 'File'}: ${file.name}]\n${content}`);+ const block = `[${isPdfFile(file) ? 'PDF' : 'File'}: ${file.name}]\n${content}`;+ fileTexts.push(block);+ displayFileTexts.push(block);} catch (e) {console.error("Failed to read file", file.name, e);- fileTexts.push(`[File: ${file.name}] (Failed to read content)`);+ const block = `[File: ${file.name}]\n(Failed to read content)`;+ fileTexts.push(block);+ displayFileTexts.push(block);}}}@@ -436,11 +442,10 @@ export function ChatPanel({const imageTags = currentUploadedImageItems.map((it) => `[[IMAGE|${safeTagText(it.name)}|${it.url}]]`).join("\n");- const nonImageFiles = files.filter((f) => !f.type.startsWith("image/"));const displayParts = [imageTags,rawInput,- nonImageFiles.length > 0 ? `(已附加文件:${nonImageFiles.map((f) => f.name).join(",")})` : "",+ displayFileTexts.length > 0 ? displayFileTexts.join("\n\n") : "",].filter(Boolean);const displayContent = displayParts.join("\n\n");@@ -849,7 +854,7 @@ export function ChatPanel({onStop={handleStop}onFilesChange={setFiles}files={files}- uploadMode={workspaceId === "ppt" ? "imagesOnly" : "all"}+ uploadMode={workspaceId === "ppt" ? "imagesOnly" : workspaceId === "cad" ? "filesOnly" : "all"}onOpenGlobalConstraints={() => setShowGlobalConstraints(true)}placeholder={inputPlaceholder}focusKey={workspaceId === "ppt" ? pptInputFocusTick : undefined}diff --git a/src/components/file-preview-list.tsx b/src/components/file-preview-list.tsxindex d7e5975..01d625e 100644--- a/src/components/file-preview-list.tsx+++ b/src/components/file-preview-list.tsx@@ -84,67 +84,68 @@ export function FilePreviewList({{files.map((file, index) => {const imageUrl = imageUrls.get(file) || nullconst pdfInfo = pdfData.get(file)+ const isImage = file.type.startsWith("image/")+ const isPdf = isPdfFile(file)+ const isText = isTextFile(file)+ const secondary = pdfInfo?.isExtracting+ ? "Reading..."+ : pdfInfo?.charCount+ ? `${formatCharCount(pdfInfo.charCount)} chars`+ : isPdf+ ? "PDF"+ : isText+ ? "Text"+ : ""return (- <div key={file.name + index} className="relative group">+ <div key={file.name + index} className="group"><div- className={`w-20 h-20 border rounded-md overflow-hidden bg-muted ${- file.type.startsWith("image/") && imageUrl- ? "cursor-pointer"- : ""- }`}- onClick={() =>- file.type.startsWith("image/") &&- imageUrl &&- setSelectedImage(imageUrl)- }+ className="flex items-center gap-2.5 w-[260px] max-w-full border rounded-lg overflow-hidden bg-background/70 px-3 py-2">- {file.type.startsWith("image/") && imageUrl ? (- <img- src={imageUrl}- alt={file.name}- className="object-cover w-full h-full"- />- ) : isPdfFile(file) || isTextFile(file) ? (- <div className="flex flex-col items-center justify-center h-full p-1">- {pdfInfo?.isExtracting ? (- <Loader2 className="h-6 w-6 text-blue-500 mb-1 animate-spin" />- ) : isPdfFile(file) ? (- <FileText className="h-6 w-6 text-red-500 mb-1" />- ) : (- <FileCode className="h-6 w-6 text-blue-500 mb-1" />- )}- <span className="text-xs text-center truncate w-full px-1">- {file.name.length > 10- ? `${file.name.slice(0, 7)}...`- : file.name}- </span>- {pdfInfo?.isExtracting ? (- <span className="text-[10px] text-muted-foreground">- Reading...- </span>- ) : pdfInfo?.charCount ? (- <span className="text-[10px] text-green-600 font-medium">- {formatCharCount(- pdfInfo.charCount,- )}{" "}- chars- </span>- ) : null}- </div>- ) : (- <div className="flex items-center justify-center h-full text-xs text-center p-1">- {file.name}- </div>- )}+ <div+ className={`h-11 w-11 rounded-md overflow-hidden bg-muted flex items-center justify-center ${+ isImage && imageUrl ? "cursor-pointer" : ""+ }`}+ onClick={() => {+ if (isImage && imageUrl) setSelectedImage(imageUrl)+ }}+ >+ {isImage && imageUrl ? (+ <img+ src={imageUrl}+ alt={file.name}+ className="object-cover w-full h-full"+ />+ ) : (+ <>+ {pdfInfo?.isExtracting ? (+ <Loader2 className="h-5 w-5 text-blue-500 animate-spin" />+ ) : isPdf ? (+ <FileText className="h-5 w-5 text-red-500" />+ ) : (+ <FileCode className="h-5 w-5 text-blue-500" />+ )}+ </>+ )}+ </div>++ <div className="min-w-0 flex-1">+ <div className="text-xs font-medium truncate">{file.name}</div>+ {secondary ? (+ <div className="text-[10px] text-muted-foreground truncate">+ {secondary}+ </div>+ ) : null}+ </div>++ <button+ type="button"+ onClick={() => onRemoveFile(file)}+ className="shrink-0 rounded-md p-1 text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"+ aria-label="Remove file"+ >+ <X className="h-4 w-4" />+ </button></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 text-destructive-foreground"- aria-label="Remove file"- >- <X className="h-3 w-3" />- </button></div>)})}diff --git a/src/components/workspaces/FlowchartWorkspace.tsx b/src/components/workspaces/FlowchartWorkspace.tsxindex af8773d..9f94e41 100644--- a/src/components/workspaces/FlowchartWorkspace.tsx+++ b/src/components/workspaces/FlowchartWorkspace.tsx@@ -11,12 +11,15 @@ import {interface FlowchartWorkspaceProps {initialXml?: string;onAddToChat?: (xmlSnippet: string) => void;+ onXmlChange?: (xml: string) => void;}-export function FlowchartWorkspace({ initialXml, onAddToChat }: FlowchartWorkspaceProps) {+export function FlowchartWorkspace({ initialXml, onAddToChat, onXmlChange }: FlowchartWorkspaceProps) {const iframeRef = useRef<HTMLIFrameElement>(null);const [isLoaded, setIsLoaded] = useState(false);const [selectedCells, setSelectedCells] = useState<any[]>([]);+ const lastEmittedXmlRef = useRef<string>("");+ const autosaveInFlightRef = useRef(false);// Default empty graphconst emptyXml = '<mxGraphModel><root><mxCell id="0"/><mxCell id="1" parent="0"/></root></mxGraphModel>';@@ -61,6 +64,47 @@ export function FlowchartWorkspace({ initialXml, onAddToChat }: FlowchartWorkspareturn () => window.removeEventListener('message', handleMessage);}, []);+ useEffect(() => {+ if (!isLoaded) return;+ const iframe = iframeRef.current;+ if (!iframe?.contentWindow) return;++ const requestExport = () => {+ if (autosaveInFlightRef.current) return;+ autosaveInFlightRef.current = true;++ const handleExport = (e: MessageEvent) => {+ if (typeof e.data !== "string") return;+ try {+ const msg = JSON.parse(e.data);+ if (msg.event !== "export") return;+ const xml = String(msg.data || "");+ autosaveInFlightRef.current = false;+ window.removeEventListener("message", handleExport);+ if (!xml) return;+ if (xml === lastEmittedXmlRef.current) return;+ lastEmittedXmlRef.current = xml;+ onXmlChange?.(xml);+ } catch {+ }+ };++ window.addEventListener("message", handleExport);+ iframe.contentWindow.postMessage(+ JSON.stringify({+ action: "export",+ format: "xml",+ spin: "Saving...",+ }),+ "*"+ );+ };++ requestExport();+ const id = window.setInterval(requestExport, 2500);+ return () => window.clearInterval(id);+ }, [isLoaded, onXmlChange]);+// Separate effect to handle XML loading when either loaded state or xml changesuseEffect(() => {if (isLoaded && initialXml) {diff --git a/src/components/workspaces/PptWorkspace.tsx b/src/components/workspaces/PptWorkspace.tsxindex 8bd70ae..0f08cb0 100644--- a/src/components/workspaces/PptWorkspace.tsx+++ b/src/components/workspaces/PptWorkspace.tsx@@ -46,6 +46,7 @@ type TemplateItem =const PPT_TEMPLATE_UPLOADS_KEY = "ppt_template_uploads_v1";const PPT_TEMPLATE_HIDDEN_PRESETS_KEY = "ppt_template_hidden_presets_v1";+const PPT_WORKSPACE_STORAGE_KEY = "unified-ai-workspace-ppt-state-v1";const PRESET_TEMPLATES: PresetTemplate[] = [{ id: "preset-tech-business", name: "科技商务", path: "/templates/template_b.png" },@@ -59,11 +60,42 @@ const PRESET_TEMPLATES: PresetTemplate[] = [const MODEL_CONCURRENCY = 30;export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit }: PptWorkspaceProps) {+ const initialPptState = (() => {+ if (typeof window === "undefined") return null;+ try {+ const raw = localStorage.getItem(PPT_WORKSPACE_STORAGE_KEY);+ const parsed = raw ? JSON.parse(raw) : null;+ if (!parsed || typeof parsed !== "object") return null;+ return parsed as any;+ } catch {+ return null;+ }+ })();+// If data is provided by AI, use it. Otherwise maintain local state for demo.- const [localSlides, setLocalSlides] = useState<SlideData[]>([]);- const [currentSlideIndex, setCurrentSlideIndex] = useState(0);+ const [localSlides, setLocalSlides] = useState<SlideData[]>(() => {+ const v = initialPptState?.localSlides;+ if (!Array.isArray(v)) return [];+ return v+ .filter((s: any) => s && typeof s.id === "string")+ .map((s: any) => ({+ id: String(s.id),+ title: typeof s.title === "string" ? s.title : "",+ content: Array.isArray(s.content) ? s.content.filter((x: any) => typeof x === "string") : [],+ note: typeof s.note === "string" ? s.note : undefined,+ layout: typeof s.layout === "string" ? s.layout : undefined,+ description: typeof s.description === "string" ? s.description : undefined,+ }));+ });+ const [currentSlideIndex, setCurrentSlideIndex] = useState(() => {+ const v = initialPptState?.currentSlideIndex;+ return typeof v === "number" && Number.isFinite(v) ? Math.max(0, Math.floor(v)) : 0;+ });const [templateImage, setTemplateImage] = useState<string | null>(null);- const [selectedTemplateId, setSelectedTemplateId] = useState<string | null>(null);+ const [selectedTemplateId, setSelectedTemplateId] = useState<string | null>(() => {+ const v = initialPptState?.selectedTemplateId;+ return typeof v === "string" ? v : null;+ });const [uploadedTemplates, setUploadedTemplates] = useState<UploadTemplate[]>(() => {if (typeof window === "undefined") return [];try {@@ -87,17 +119,57 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditreturn [];}});- const [generatedImages, setGeneratedImages] = useState<Record<string, string>>({});- const [imageVersions, setImageVersions] = useState<Record<string, Array<{ id: string; url: string; timestamp: number; type: 'generated' | 'edited'; instruction?: string }>>>({});- const [currentImageVersionId, setCurrentImageVersionId] = useState<Record<string, string>>({});+ const [generatedImages, setGeneratedImages] = useState<Record<string, string>>(() => {+ const v = initialPptState?.generatedImages;+ if (!v || typeof v !== "object" || Array.isArray(v)) return {};+ const out: Record<string, string> = {};+ for (const [k, val] of Object.entries(v)) {+ if (typeof k === "string" && typeof val === "string") out[k] = val;+ }+ return out;+ });+ const [imageVersions, setImageVersions] = useState<Record<string, Array<{ id: string; url: string; timestamp: number; type: 'generated' | 'edited'; instruction?: string }>>>(() => {+ const v = initialPptState?.imageVersions;+ if (!v || typeof v !== "object" || Array.isArray(v)) return {};+ const out: Record<string, Array<{ id: string; url: string; timestamp: number; type: 'generated' | 'edited'; instruction?: string }>> = {};+ for (const [k, val] of Object.entries(v)) {+ if (typeof k !== "string" || !Array.isArray(val)) continue;+ out[k] = val+ .filter((x: any) => x && typeof x.id === "string" && typeof x.url === "string" && typeof x.timestamp === "number" && (x.type === "generated" || x.type === "edited"))+ .map((x: any) => ({+ id: x.id,+ url: x.url,+ timestamp: x.timestamp,+ type: x.type,+ instruction: typeof x.instruction === "string" ? x.instruction : undefined,+ }));+ }+ return out;+ });+ const [currentImageVersionId, setCurrentImageVersionId] = useState<Record<string, string>>(() => {+ const v = initialPptState?.currentImageVersionId;+ if (!v || typeof v !== "object" || Array.isArray(v)) return {};+ const out: Record<string, string> = {};+ for (const [k, val] of Object.entries(v)) {+ if (typeof k === "string" && typeof val === "string") out[k] = val;+ }+ return out;+ });const [isGeneratingImage, setIsGeneratingImage] = useState(false);// Creation Wizard State- const [creationStep, setCreationStep] = useState<CreationStep>('idle');- const [creationMode, setCreationMode] = useState<CreationMode>('idea');- const [ideaInput, setIdeaInput] = useState("");- const [outlineInput, setOutlineInput] = useState("");- const [descriptionInput, setDescriptionInput] = useState("");+ const [creationStep, setCreationStep] = useState<CreationStep>(() => {+ const v = initialPptState?.creationStep;+ if (v === "idle" || v === "input" || v === "outline" || v === "generating_content" || v === "generating_images" || v === "done") return v;+ return localSlides.length > 0 ? "done" : "idle";+ });+ const [creationMode, setCreationMode] = useState<CreationMode>(() => {+ const v = initialPptState?.creationMode;+ return v === "idea" || v === "outline" || v === "description" ? v : "idea";+ });+ const [ideaInput, setIdeaInput] = useState(() => (typeof initialPptState?.ideaInput === "string" ? initialPptState.ideaInput : ""));+ const [outlineInput, setOutlineInput] = useState(() => (typeof initialPptState?.outlineInput === "string" ? initialPptState.outlineInput : ""));+ const [descriptionInput, setDescriptionInput] = useState(() => (typeof initialPptState?.descriptionInput === "string" ? initialPptState.descriptionInput : ""));const [referenceFiles, setReferenceFiles] = useState<ReferenceFile[]>([]);const [isParsingReferenceFiles, setIsParsingReferenceFiles] = useState(false);const [referencePreviewOpen, setReferencePreviewOpen] = useState(false);@@ -131,6 +203,46 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEdit}}, [hiddenPresetTemplateIds]);+ useEffect(() => {+ if (typeof window === "undefined") return;+ try {+ localStorage.setItem(+ PPT_WORKSPACE_STORAGE_KEY,+ JSON.stringify({+ localSlides,+ currentSlideIndex,+ selectedTemplateId,+ generatedImages,+ imageVersions,+ currentImageVersionId,+ creationStep,+ creationMode,+ ideaInput,+ outlineInput,+ descriptionInput,+ updatedAt: Date.now(),+ })+ );+ } catch {+ }+ }, [+ localSlides,+ currentSlideIndex,+ selectedTemplateId,+ generatedImages,+ imageVersions,+ currentImageVersionId,+ creationStep,+ creationMode,+ ideaInput,+ outlineInput,+ descriptionInput,+ ]);++ useEffect(() => {+ onPptReadyChange?.(localSlides.length > 0);+ }, [localSlides.length]);+useEffect(() => {if (typeof window === "undefined") return;const handleResize = () => {@@ -181,10 +293,19 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, incomingEditsetTemplateImage(null);return;}- const exists = selectedTemplateId && templates.some((t) => t.id === selectedTemplateId);- if (exists) return;- void setTemplateFromItem(templates[0]);- }, [selectedTemplateId, hiddenPresetTemplateIds.join("|"), uploadedTemplates.map((t) => t.id).join("|")]);+ const selected = selectedTemplateId ? templates.find((t) => t.id === selectedTemplateId) : null;+ if (!selected) {+ void setTemplateFromItem(templates[0]);+ return;+ }+ if (!templateImage) {+ void setTemplateFromItem(selected);+ return;+ }+ if (selected.kind === "upload" && templateImage !== selected.dataUrl) {+ setTemplateImage(selected.dataUrl);+ }+ }, [selectedTemplateId, templateImage, hiddenPresetTemplateIds.join("|"), uploadedTemplates.map((t) => t.id).join("|")]);const addUploadedTemplates = async (files: File[]) => {const imageFiles = Array.from(files || []).filter((f) => f && f.type.startsWith("image/"));diff --git a/src/pages/LandingPage.tsx b/src/pages/LandingPage.tsxindex f68e9a6..58b786f 100644--- a/src/pages/LandingPage.tsx+++ b/src/pages/LandingPage.tsx@@ -151,13 +151,12 @@ export function LandingPage({ onStart }: LandingPageProps) {<Layers className="w-5 h-5 text-blue-300" /></div><div>- <div className="text-white/90 font-semibold">GraphRAG 论文流程图</div>- <div className="text-white/45 text-sm mt-0.5">输入需求 → 逐步搭建 Approach 图</div>+ <div className="text-white/90 font-semibold">智绘流程蓝图</div>+ <div className="text-white/45 text-sm mt-0.5">输入需求 → 生成并迭代流程图</div></div></div>- <div className="mt-2 text-xs text-white/55 space-y-1">- <div>· 论文级呈现:Approach 图风格</div>- <div>· 结构清晰:索引/聚类/检索一眼懂</div>+ <div className="mt-2 text-sm text-white/60 space-y-1">+ <div>· 原子级修改:仅改不满意处,保留满意部分</div></div></button>@@ -178,9 +177,9 @@ export function LandingPage({ onStart }: LandingPageProps) {<div className="text-white/45 text-sm mt-0.5">输入需求 → 2D 平面 → 装修图 / 物料清单</div></div></div>- <div className="mt-2 text-xs text-white/55 space-y-1">- <div>· 先 2D 后 装修图/物料:方案落地更快</div>- <div>· 风格可控:一键切换风格</div>+ <div className="mt-2 text-sm text-white/55 space-y-1">+ <div>· 全流程覆盖:需求→方案→2D→出图/清单</div>+ <div>· 2D 支持原子修改</div></div></button>@@ -197,13 +196,12 @@ export function LandingPage({ onStart }: LandingPageProps) {<Layout className="w-5 h-5 text-cyan-300" /></div><div>- <div className="text-white/90 font-semibold">演示文稿生成</div>- <div className="text-white/45 text-sm mt-0.5">参考 PDF → 缩略图列表 → 幻灯片播放</div>+ <div className="text-white/90 font-semibold">智创演示文稿</div>+ <div className="text-white/45 text-sm mt-0.5">文案 → 结构 → 幻灯片</div></div></div>- <div className="mt-2 text-xs text-white/55 space-y-1">- <div>· 内容复用:PDF 直接变演示</div>- <div>· 展示顺滑:缩略图 + 自动播放</div>+ <div className="mt-2 text-sm text-white/60 space-y-1">+ <div>· 单页/多页修改:支持精修与批量统一调整</div></div></button></div>