Skip to content

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.

bubble_fix

codingFeng1011ac9672189e6
diff --git a/src/workspaces/flow/next/components/chat-message-display.tsx b/src/workspaces/flow/next/components/chat-message-display.tsx
index 8d8580c..6a876dd 100644
--- a/src/workspaces/flow/next/components/chat-message-display.tsx
+++ b/src/workspaces/flow/next/components/chat-message-display.tsx
@@ -15,8 +15,6 @@ import {
Pencil,
Plus,
RotateCcw,
- ThumbsDown,
- ThumbsUp,
X,
} from "lucide-react"
import Image from "@/workspaces/flow/next/shims/next-image"
@@ -223,7 +221,6 @@ export function ChatMessageDisplay({
const [copyFailedMessageId, setCopyFailedMessageId] = useState<
string | null
>(null)
- const [feedback, setFeedback] = useState<Record<string, "good" | "bad">>({})
const [editingMessageId, setEditingMessageId] = useState<string | null>(
null,
)
@@ -262,34 +259,6 @@ export function ChatMessageDisplay({
}
}
- const submitFeedback = async (messageId: string, value: "good" | "bad") => {
- // Toggle off if already selected
- if (feedback[messageId] === value) {
- setFeedback((prev) => {
- const next = { ...prev }
- delete next[messageId]
- return next
- })
- return
- }
-
- setFeedback((prev) => ({ ...prev, [messageId]: value }))
-
- try {
- await fetch("/api/log-feedback", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- messageId,
- feedback: value,
- sessionId,
- }),
- })
- } catch (error) {
- console.warn("Failed to log feedback:", error)
- }
- }
-
const handleDisplayChart = useCallback(
(xml: string) => {
const currentXml = xml || ""
@@ -505,7 +474,7 @@ export function ChatMessageDisplay({
animationDelay: `${messageIndex * 50}ms`,
}}
>
- <div className="max-w-[85%] min-w-0">
+ <div className="max-w-[95%] min-w-0">
{/* Reasoning blocks - displayed first for assistant messages */}
{message.role === "assistant" &&
message.parts?.map(
@@ -882,10 +851,10 @@ export function ChatMessageDisplay({
)}
{hasTextContent || message.role !== "user" ? (
- <div className={message.role === "user" ? "flex items-center justify-end gap-1.5" : ""}>
+ <div className={message.role === "user" ? "flex flex-col items-end gap-1.5" : ""}>
{message.role === "user" &&
!isEditing && (
- <div className="flex items-center gap-1 self-center">
+ <div className="order-2 flex items-center gap-1 self-end">
{onEditMessage &&
isLastUserMessage && (
<button
@@ -949,10 +918,10 @@ export function ChatMessageDisplay({
</div>
)}
<div
- className={`px-4 py-3 text-sm leading-relaxed ${
+ className={`order-1 w-full px-4 py-3 text-sm leading-relaxed ${
message.role ===
"user"
- ? "bg-primary text-primary-foreground rounded-2xl rounded-br-md shadow-sm"
+ ? "bg-background text-foreground rounded-2xl rounded-br-md border border-border/50 shadow-sm"
: message.role ===
"system"
? "bg-destructive/10 text-destructive border border-destructive/20 rounded-2xl rounded-bl-md"
@@ -1059,12 +1028,7 @@ export function ChatMessageDisplay({
return (
<div
key={`${message.id}-textsection-${partIndex}-${sectionIndex}`}
- className={`prose prose-sm max-w-none break-words [&>*:first-child]:mt-0 [&>*:last-child]:mb-0 ${
- message.role ===
- "user"
- ? "[&_*]:!text-primary-foreground prose-code:bg-white/20"
- : "dark:prose-invert"
- }`}
+ className="prose prose-sm max-w-none break-words [&>*:first-child]:mt-0 [&>*:last-child]:mb-0 dark:prose-invert"
>
<ReactMarkdown>
{
@@ -1146,46 +1110,6 @@ export function ChatMessageDisplay({
<RotateCcw className="h-3.5 w-3.5" />
</button>
)}
- {/* Divider */}
- <div className="w-px h-4 bg-border mx-1" />
- {/* Thumbs up */}
- <button
- type="button"
- onClick={() =>
- submitFeedback(
- message.id,
- "good",
- )
- }
- className={`p-1.5 rounded-lg transition-colors ${
- feedback[message.id] ===
- "good"
- ? "text-green-600 bg-green-100"
- : "text-muted-foreground/60 hover:text-green-600 hover:bg-green-50"
- }`}
- title={t("message.good")}
- >
- <ThumbsUp className="h-3.5 w-3.5" />
- </button>
- {/* Thumbs down */}
- <button
- type="button"
- onClick={() =>
- submitFeedback(
- message.id,
- "bad",
- )
- }
- className={`p-1.5 rounded-lg transition-colors ${
- feedback[message.id] ===
- "bad"
- ? "text-red-600 bg-red-100"
- : "text-muted-foreground/60 hover:text-red-600 hover:bg-red-50"
- }`}
- title={t("message.bad")}
- >
- <ThumbsDown className="h-3.5 w-3.5" />
- </button>
</div>
)}
</div>
diff --git a/src/workspaces/ppt/chat/ChatMessageDisplay.tsx b/src/workspaces/ppt/chat/ChatMessageDisplay.tsx
index 3fc00c9..d988a7f 100644
--- a/src/workspaces/ppt/chat/ChatMessageDisplay.tsx
+++ b/src/workspaces/ppt/chat/ChatMessageDisplay.tsx
@@ -4,7 +4,6 @@ import {
ChevronDown,
ChevronUp,
Copy,
- Cpu,
FileCode,
FileText,
Loader2,
@@ -67,7 +66,7 @@ interface PptEditSlidePatch {
}
interface PptToolPayload {
- type: "ppt_edit" | "ppt_delete" | "ppt_crate";
+ type: "ppt_edit";
slides: PptEditSlidePatch[];
}
@@ -208,15 +207,8 @@ const getMessageTextContent = (message: UIMessage): string => {
const getUserOriginalText = (message: UIMessage): string => {
const fullText = getMessageTextContent(message);
- const withoutTags = fullText
- .split(/\r?\n/)
- .filter((line) => !/^\[\[PPT_SLIDE\|(\d+)\|([^|]*)\|(outline|slide_image)\]\]$/.test(line))
- .filter((line) => !/^\[\[PPT_SLIDE\|(\d+)\|(.*)\]\]$/.test(line))
- .filter((line) => !/^\[\[IMAGE\|([^|]*)\|([\s\S]+)\]\]$/.test(line))
- .join("\n")
- .trim();
const filePattern = /\n\n\[(PDF|File):\s*[^\]]+\]\n[\s\S]*$/;
- return withoutTags.replace(filePattern, "").trim();
+ return fullText.replace(filePattern, "").trim();
};
function extractPptToolPayload(text: string): PptToolPayload | null {
@@ -235,12 +227,8 @@ function extractPptToolPayload(text: string): PptToolPayload | null {
}
if (!parsed || typeof parsed !== "object") return null;
const typeRaw = String((parsed as any).type || "").trim().toLowerCase();
- const type: "ppt_edit" | "ppt_delete" | "ppt_crate" =
- typeRaw === "ppt_delete"
- ? "ppt_delete"
- : typeRaw === "ppt_crate" || typeRaw === "ppt_create"
- ? "ppt_crate"
- : "ppt_edit";
+ if (typeRaw && typeRaw !== "ppt_edit") return null;
+ const type: "ppt_edit" = "ppt_edit";
const slides = Array.isArray((parsed as any).slides)
? (parsed as any).slides.filter((s: any) => s && typeof s === "object")
: [];
@@ -295,10 +283,6 @@ function slideFieldLabel(key: string, uiLang: "zh" | "en"): string {
return key;
}
-function pptToolTypeLabel(type: "ppt_edit" | "ppt_delete" | "ppt_crate"): string {
- return type;
-}
-
export function ChatMessageDisplay({
messages,
setInput,
@@ -350,29 +334,50 @@ export function ChatMessageDisplay({
const getViewport = useCallback(() => {
const root = scrollRootRef.current;
if (!root) return null;
- return root.querySelector('[data-radix-scroll-area-viewport]') as HTMLElement | null;
+ return (
+ (root.querySelector('[data-slot="scroll-area-viewport"]') as HTMLElement | null) ||
+ (root.querySelector('[data-radix-scroll-area-viewport]') as HTMLElement | null)
+ );
}, []);
const scrollToBottom = useCallback((behavior: ScrollBehavior = "auto") => {
const viewport = getViewport();
- if (!viewport) return;
+ if (!viewport) {
+ messagesEndRef.current?.scrollIntoView({ behavior });
+ return;
+ }
viewport.scrollTo({ top: viewport.scrollHeight, behavior });
}, [getViewport]);
useEffect(() => {
- const viewport = getViewport();
- if (!viewport) return;
-
- const onScroll = () => {
- const threshold = 48;
- const distanceToBottom = viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;
- setIsAtBottom(distanceToBottom <= threshold);
+ let mounted = true;
+ let cleanup: null | (() => void) = null;
+ let rafId = 0;
+
+ const bind = () => {
+ if (!mounted) return;
+ const viewport = getViewport();
+ if (!viewport) {
+ rafId = requestAnimationFrame(bind);
+ return;
+ }
+ const onScroll = () => {
+ const threshold = 48;
+ const distanceToBottom = viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;
+ setIsAtBottom(distanceToBottom <= threshold);
+ };
+ onScroll();
+ viewport.addEventListener("scroll", onScroll, { passive: true });
+ cleanup = () => viewport.removeEventListener("scroll", onScroll as any);
};
- onScroll();
- viewport.addEventListener("scroll", onScroll, { passive: true });
- return () => viewport.removeEventListener("scroll", onScroll as any);
- }, [getViewport]);
+ bind();
+ return () => {
+ mounted = false;
+ if (rafId) cancelAnimationFrame(rafId);
+ if (cleanup) cleanup();
+ };
+ }, [getViewport, messages.length]);
useEffect(() => {
return () => {
@@ -435,10 +440,36 @@ export function ChatMessageDisplay({
message.role === "user" &&
(messageIndex === messages.length - 1 || messages.slice(messageIndex + 1).every((m) => m.role !== "user"));
const isEditing = editingMessageId === message.id;
+ const messageText = getMessageTextContent(message);
+ const { images: probeImages, rest: probeWithoutImages } = extractImageTags(messageText);
+ const { tags: probePptTags, rest: probeText } = extractPptSlideTags(probeWithoutImages);
+ const probeSections = splitTextIntoFileSections(probeText);
+ const hasProbeText = probeSections.some((s) => s.type === "text" && String(s.content || "").trim().length > 0);
+ const hasProbeFiles = probeSections.some((s) => s.type === "file" && String(s.content || "").trim().length > 0);
+ const hasProbePptTool = probeSections.some(
+ (s) => s.type === "text" && !!extractPptToolPayload(String(s.content || ""))
+ );
+ const hasProbeReasoning = (message.parts || []).some(
+ (p) => p?.type === "reasoning" && String(p.text || "").trim().length > 0
+ );
+ const hasRenderableContent =
+ probeImages.length > 0 ||
+ probePptTags.length > 0 ||
+ hasProbeText ||
+ hasProbeFiles ||
+ hasProbePptTool ||
+ hasProbeReasoning;
+ const isAssistantEmpty = message.role === "assistant" && !hasRenderableContent;
+ const showPendingIndicator =
+ message.role === "user" &&
+ isLastUserMessage &&
+ (status === "submitted" || status === "streaming");
+
+ if (isAssistantEmpty) return null;
return (
+ <React.Fragment key={message.id}>
<div
- key={message.id}
className={`flex w-full ${message.role === "user" ? "justify-end" : "justify-start"}`}
>
<div
@@ -447,29 +478,29 @@ export function ChatMessageDisplay({
message.role === "assistant" ? "w-full max-w-[95%] items-start" : "max-w-[95%] items-end"
)}
>
- {/* Role Icon / Header */}
- <div className="flex items-center gap-2 mb-1.5 px-1">
- {message.role === 'assistant' ? (
- <>
- <div className="w-5 h-5 rounded-full bg-blue-600 flex items-center justify-center">
- <Cpu className="w-3 h-3 text-white" />
- </div>
- <span className="text-xs font-medium text-muted-foreground">{tr("AI 助手", "AI Assistant")}</span>
- </>
- ) : (
- <>
- <span className="text-xs font-medium text-muted-foreground">{tr("你", "You")}</span>
- </>
- )}
- </div>
-
{/* Content Bubble */}
<div className={cn(
"relative px-4 py-3 text-sm leading-relaxed break-words overflow-hidden border border-border/50 bg-background/70 backdrop-blur-md shadow-sm transition-shadow hover:shadow-md",
message.role === "user"
- ? "text-foreground rounded-2xl rounded-tr-sm w-full"
+ ? "text-foreground rounded-2xl rounded-tr-sm w-full cursor-pointer"
: "text-foreground rounded-2xl rounded-tl-sm w-full"
- )}>
+ )}
+ role={message.role === "user" && isLastUserMessage && onEditMessage ? "button" : undefined}
+ tabIndex={message.role === "user" && isLastUserMessage && onEditMessage ? 0 : undefined}
+ title={message.role === "user" && isLastUserMessage && onEditMessage ? tr("点击编辑", "Click to edit") : undefined}
+ onClick={() => {
+ if (isEditing || message.role !== "user" || !isLastUserMessage || !onEditMessage) return;
+ setEditingMessageId(message.id);
+ setEditText(getUserOriginalText(message));
+ }}
+ onKeyDown={(e) => {
+ if (isEditing || message.role !== "user" || !isLastUserMessage || !onEditMessage) return;
+ if (e.key === "Enter" || e.key === " ") {
+ e.preventDefault();
+ setEditingMessageId(message.id);
+ setEditText(getUserOriginalText(message));
+ }
+ }}>
{/* Reasoning Parts */}
{message.parts?.map((part, partIndex) => {
@@ -500,24 +531,60 @@ export function ChatMessageDisplay({
// Edit Mode
if (isEditing && message.role === "user") {
+ const editParts = splitInlinePptTags(editText);
return (
- <div className="flex flex-col gap-2 min-w-[300px]">
- <textarea
- ref={editTextareaRef}
- value={editText}
- onChange={(e) => setEditText(e.target.value)}
- className="w-full px-3 py-2 text-sm rounded-md border border-input bg-background text-foreground resize-none focus:outline-none focus:ring-2 focus:ring-primary"
- rows={4}
- />
+ <div className="flex flex-col gap-2 min-w-[300px]" onClick={(e) => e.stopPropagation()}>
+ <div className="relative w-full">
+ <textarea
+ ref={editTextareaRef}
+ value={editText}
+ onChange={(e) => setEditText(e.target.value)}
+ onClick={(e) => e.stopPropagation()}
+ className="relative z-10 w-full px-3 py-2 text-sm rounded-md border border-input bg-transparent text-transparent caret-foreground resize-none focus:outline-none focus:ring-2 focus:ring-primary"
+ rows={4}
+ />
+ <div className="pointer-events-none absolute inset-0 z-0 overflow-hidden rounded-md border border-input bg-background px-3 py-2 text-sm leading-6 whitespace-pre-wrap break-words text-foreground">
+ {editParts.map((p, i) => {
+ if (p.type === "text") return <span key={`edit-t-${i}`}>{p.text}</span>;
+ const kind = p.kind === "outline" ? "outline" : "slide_image";
+ const label = p.title ? tr(`第 ${p.n} 页:${p.title}`, `Slide ${p.n}: ${p.title}`) : tr(`第 ${p.n} 页`, `Slide ${p.n}`);
+ return (
+ <span
+ key={`edit-ppt-${i}`}
+ className={cn(
+ "mx-0.5 inline-flex items-center gap-1.5 rounded-full border px-2 py-0.5 text-xs font-medium align-middle",
+ kind === "outline"
+ ? "border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-400/30 dark:bg-blue-950/40 dark:text-blue-200"
+ : "border-red-200 bg-red-50 text-red-700 dark:border-red-400/30 dark:bg-red-950/40 dark:text-red-200"
+ )}
+ >
+ <span
+ className={cn(
+ "inline-flex h-4 w-4 items-center justify-center rounded-full text-[10px] font-semibold text-white",
+ kind === "outline" ? "bg-blue-600" : "bg-red-600"
+ )}
+ >
+ {kind === "outline" ? "T" : "P"}
+ </span>
+ {label}
+ </span>
+ );
+ })}
+ </div>
+ </div>
<div className="flex justify-end gap-2">
<button
- onClick={() => setEditingMessageId(null)}
+ onClick={(e) => {
+ e.stopPropagation();
+ setEditingMessageId(null);
+ }}
className="px-3 py-1 text-xs rounded bg-muted hover:bg-muted/80 text-foreground"
>
{tr("取消", "Cancel")}
</button>
<button
- onClick={() => {
+ onClick={(e) => {
+ e.stopPropagation();
if (editText.trim() && onEditMessage) {
onEditMessage(messageIndex, editText.trim());
setEditingMessageId(null);
@@ -659,24 +726,11 @@ export function ChatMessageDisplay({
if (pptToolPayload && pptToolPayload.slides.length > 0) {
return (
<div key={idx} className="w-full min-w-0 space-y-2">
- <div className="inline-flex items-center rounded-md border border-blue-200 bg-blue-50 px-2 py-1 text-[11px] font-medium text-blue-700">
- {pptToolTypeLabel(pptToolPayload.type)}
- </div>
{pptToolPayload.slides.map((slide, slideIdx) => {
const slideNumber = getSlideNumber(slide, slideIdx);
- const rows = (() => {
- if (pptToolPayload.type === "ppt_delete") {
- return [
- {
- key: "id",
- value: String(slide?.id || tr("未提供", "Missing")),
- },
- ];
- }
- return slidePatchEntries(slide);
- })();
+ const rows = slidePatchEntries(slide);
const cardKey = `${message.id}-ppt-edit-${idx}-${slideIdx}`;
- const expanded = expandedSlideCards[cardKey] ?? true;
+ const expanded = expandedSlideCards[cardKey] ?? false;
return (
<div
key={cardKey}
@@ -784,13 +838,6 @@ export function ChatMessageDisplay({
);
})()}
- {/* Loading Indicator */}
- {isLastAssistantMessage && status === "streaming" && (
- <div className="mt-2 flex items-center gap-2 text-xs text-muted-foreground">
- <Loader2 className="h-3 w-3 animate-spin" />
- <span>{tr("思考中...", "Thinking...")}</span>
- </div>
- )}
</div>
{/* Actions */}
@@ -849,6 +896,17 @@ export function ChatMessageDisplay({
</div>
</div>
</div>
+ {showPendingIndicator && (
+ <div className="flex w-full justify-start animate-message-in mt-3">
+ <div className="max-w-[85%] min-w-0">
+ <div className="flex items-center gap-2 px-3 py-2 text-xs text-muted-foreground bg-muted/40 rounded-2xl rounded-bl-md">
+ <Loader2 className="h-3 w-3 animate-spin" />
+ <span>{tr("思考中...", "Thinking...")}</span>
+ </div>
+ </div>
+ </div>
+ )}
+ </React.Fragment>
);
})}
<div ref={messagesEndRef} />
diff --git a/src/workspaces/ppt/workspace/PptWorkspace.tsx b/src/workspaces/ppt/workspace/PptWorkspace.tsx
index a7a028e..366f2be 100644
--- a/src/workspaces/ppt/workspace/PptWorkspace.tsx
+++ b/src/workspaces/ppt/workspace/PptWorkspace.tsx
@@ -30,6 +30,24 @@ interface PptData {
slides: SlideData[];
}
+const localizeLayoutHint = (layout: string, lang: "zh" | "en") => {
+ const raw = String(layout || "").trim();
+ if (!raw || lang !== "zh") return raw;
+ const key = raw.toLowerCase().replace(/\s+/g, "");
+ const map: Record<string, string> = {
+ "cover": "封面页",
+ "title+bullets": "标题+要点",
+ "title+bullet": "标题+要点",
+ "two-column": "双栏布局",
+ "twocolumn": "双栏布局",
+ "left-text-right-image": "左文右图",
+ "lefttextrightimage": "左文右图",
+ "title-and-content": "标题+内容",
+ "titleandcontent": "标题+内容",
+ };
+ return map[key] || raw;
+};
+
interface PptWorkspaceProps {
data?: PptData;
onAddToChat?: (json: string, name: string) => void;
@@ -525,9 +543,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
}
const toolTypeRaw = String(parsed?.type || "").trim().toLowerCase();
- const toolType = toolTypeRaw === "ppt_delete" || toolTypeRaw === "ppt_crate" || toolTypeRaw === "ppt_create"
- ? toolTypeRaw
- : "ppt_edit";
+ if (toolTypeRaw && toolTypeRaw !== "ppt_edit") return;
const incomingSlides: any[] = Array.isArray(parsed?.slides)
? parsed.slides
@@ -540,136 +556,34 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
const uploadedImages: string[] = Array.isArray(parsed?.uploadedImages) ? parsed.uploadedImages : [];
const existingById = new Map(localSlides.map((s) => [s.id, s] as const));
- const makeUniqueSlideId = (candidate: string, used: Set<string>) => {
- const base = candidate.trim() || `slide-${used.size + 1}`;
- if (!used.has(base)) return base;
- let next = 2;
- while (used.has(`${base}-${next}`)) next += 1;
- return `${base}-${next}`;
- };
-
const toSlideData = (inc: any, fallbackId: string, source?: SlideData): SlideData => ({
id: fallbackId,
title: typeof inc?.title === "string" ? inc.title : (source?.title || tr("幻灯片", "Slide")),
content: Array.isArray(inc?.content) ? inc.content.map((x: any) => String(x)) : (source?.content || []),
description: typeof inc?.description === "string" ? inc.description : source?.description,
note: typeof inc?.note === "string" ? inc.note : source?.note,
- layout: typeof inc?.layout === "string" ? inc.layout : source?.layout,
+ layout: typeof inc?.layout === "string" ? localizeLayoutHint(inc.layout, uiLang as "zh" | "en") : source?.layout,
});
- const getCreateAnchor = (inc: any): { beforeId?: string; afterId?: string; position?: number } => {
- const beforeId = typeof inc?.insertBeforeId === "string"
- ? inc.insertBeforeId
- : typeof inc?.beforeId === "string"
- ? inc.beforeId
- : typeof inc?.between?.beforeId === "string"
- ? inc.between.beforeId
- : undefined;
- const afterId = typeof inc?.insertAfterId === "string"
- ? inc.insertAfterId
- : typeof inc?.afterId === "string"
- ? inc.afterId
- : typeof inc?.between?.afterId === "string"
- ? inc.between.afterId
- : undefined;
- const pos = Number(inc?.position);
- const position = Number.isFinite(pos) ? pos : undefined;
- return { beforeId, afterId, position };
- };
-
let mergedSlides: SlideData[] = localSlides.slice();
let mergedIncomingSlides = incomingSlides.slice();
-
- if (toolType === "ppt_delete") {
- const deleteIds = new Set(
- incomingSlides
- .map((inc) => String(inc?.id || "").trim())
- .filter(Boolean)
- );
- if (deleteIds.size === 0) return;
-
- mergedSlides = localSlides.filter((slide) => !deleteIds.has(slide.id));
- mergedIncomingSlides = [];
-
- setLocalSlides(mergedSlides);
- setSlideMaterials((prev) => {
- const next = { ...prev };
- for (const id of deleteIds) delete next[id];
- return next;
- });
- setGeneratedImages((prev) => {
- const next = { ...prev };
- for (const id of deleteIds) delete next[id];
- return next;
- });
- setImageVersions((prev) => {
- const next = { ...prev };
- for (const id of deleteIds) delete next[id];
- return next;
- });
- setCurrentImageVersionId((prev) => {
- const next = { ...prev };
- for (const id of deleteIds) delete next[id];
- return next;
- });
- setCurrentSlideIndex((prev) => {
- if (mergedSlides.length === 0) return 0;
- return Math.max(0, Math.min(prev, mergedSlides.length - 1));
- });
- return;
- }
-
- if (toolType === "ppt_crate" || toolType === "ppt_create") {
- const used = new Set(localSlides.map((s) => s.id));
- const nextSlides = localSlides.slice();
- const normalizedIncoming: any[] = [];
-
- for (let i = 0; i < incomingSlides.length; i += 1) {
- const inc = incomingSlides[i];
- const requestedId = String(inc?.id || "").trim();
- const newId = makeUniqueSlideId(requestedId || `slide-${nextSlides.length + 1}`, used);
- used.add(newId);
- const slide = toSlideData(inc, newId);
- const { beforeId, afterId, position } = getCreateAnchor(inc);
-
- let insertAt = nextSlides.length;
- if (beforeId) {
- const idx = nextSlides.findIndex((s) => s.id === beforeId);
- if (idx >= 0) insertAt = idx;
- } else if (afterId) {
- const idx = nextSlides.findIndex((s) => s.id === afterId);
- if (idx >= 0) insertAt = idx + 1;
- } else if (position !== undefined) {
- const maybeZeroBased = position >= 0 && position <= nextSlides.length ? position : position - 1;
- insertAt = Math.max(0, Math.min(nextSlides.length, Math.floor(maybeZeroBased)));
- }
-
- nextSlides.splice(insertAt, 0, slide);
- normalizedIncoming.push({ ...inc, id: newId });
+ mergedSlides = (() => {
+ const existing = localSlides.length > 0 ? [...localSlides] : [];
+ const byId = new Map(existing.map((s) => [s.id, s] as const));
+ const order: string[] = existing.map((s) => s.id);
+
+ for (const inc of incomingSlides) {
+ const id = String(inc?.id || "");
+ if (!id) continue;
+ const next: SlideData = toSlideData(inc, id, byId.get(id));
+ byId.set(id, next);
+ if (!order.includes(id)) order.push(id);
}
- mergedSlides = nextSlides;
- mergedIncomingSlides = normalizedIncoming;
- setLocalSlides(mergedSlides);
- } else {
- mergedSlides = (() => {
- const existing = localSlides.length > 0 ? [...localSlides] : [];
- const byId = new Map(existing.map((s) => [s.id, s] as const));
- const order: string[] = existing.map((s) => s.id);
-
- for (const inc of incomingSlides) {
- const id = String(inc?.id || "");
- if (!id) continue;
- const next: SlideData = toSlideData(inc, id, byId.get(id));
- byId.set(id, next);
- if (!order.includes(id)) order.push(id);
- }
-
- return order.map((id) => byId.get(id)!).filter(Boolean);
- })();
- mergedIncomingSlides = incomingSlides;
- setLocalSlides(mergedSlides);
- }
+ return order.map((id) => byId.get(id)!).filter(Boolean);
+ })();
+ mergedIncomingSlides = incomingSlides;
+ setLocalSlides(mergedSlides);
const allowImageEdits = creationStep === "done";
if (!allowImageEdits) return;
@@ -1474,7 +1388,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
content: Array.isArray(it.content) ? it.content.map((x: any) => String(x)) : [],
description: typeof it.description === "string" ? it.description : undefined,
note: typeof it.note === "string" ? it.note : undefined,
- layout: typeof it.layout === "string" ? it.layout : undefined,
+ layout: typeof it.layout === "string" ? localizeLayoutHint(it.layout, uiLang as "zh" | "en") : undefined,
}));
}
} catch {
@@ -1851,7 +1765,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
content: p.content,
description: p.description || "",
note: p.note || "",
- layout: p.layout || "",
+ layout: localizeLayoutHint(p.layout || "", uiLang as "zh" | "en"),
}));
const autoMaterial = buildSlideMaterialsFromAutoLabels(pages, slides, referenceVisualAssets);
setSlideMaterials(autoMaterial.nextMaterials);
@@ -1896,7 +1810,7 @@ export function PptWorkspace({ data, onAddToChat, onPptReadyChange, onPptStageCh
content: p.content,
description: p.description,
note: p.note,
- layout: p.layout
+ layout: localizeLayoutHint(p.layout || "", uiLang as "zh" | "en")
}));
const autoMaterial = buildSlideMaterialsFromAutoLabels(pages, slides, referenceVisualAssets);
setSlideMaterials(autoMaterial.nextMaterials);