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.

refactor(chat): share the chat leaf components and the CAD/PPT chat input

codingFeng101dfd33916f035
diff --git a/package.json b/package.json
index ea7caa7..7a4b42a 100644
--- a/package.json
+++ b/package.json
@@ -34,7 +34,6 @@
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"express": "^5.2.1",
- "framer-motion": "^12.28.1",
"jszip": "^3.10.1",
"lucide-react": "^0.511.0",
"mammoth": "^1.11.0",
diff --git a/src/pages/portal/PortalPage.tsx b/src/pages/portal/PortalPage.tsx
index 38e5856..a2702a6 100644
--- a/src/pages/portal/PortalPage.tsx
+++ b/src/pages/portal/PortalPage.tsx
@@ -1,5 +1,5 @@
import { type Dispatch, type SetStateAction, useEffect, useRef, useState } from "react";
-import { AnimatePresence, motion } from "framer-motion";
+import { AnimatePresence, motion } from "motion/react";
import {
Blocks,
ChartNoAxesCombined,
diff --git a/src/workspaces/flow/next/components/button-with-tooltip.tsx b/src/shared/chat/button-with-tooltip.tsx
similarity index 56%
rename from src/workspaces/flow/next/components/button-with-tooltip.tsx
rename to src/shared/chat/button-with-tooltip.tsx
index 5667b40..f5e204d 100644
--- a/src/workspaces/flow/next/components/button-with-tooltip.tsx
+++ b/src/shared/chat/button-with-tooltip.tsx
@@ -1,11 +1,7 @@
-import type { VariantProps } from "class-variance-authority"
+import type { VariantProps } from "class-variance-authority"
import type React from "react"
import { Button, type buttonVariants } from "@/shared/ui/button"
-import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from "@/shared/ui/tooltip"
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/shared/ui/tooltip"
interface ButtonWithTooltipProps
extends React.ComponentProps<"button">,
@@ -20,8 +16,10 @@ export function ButtonWithTooltip({
children,
...buttonProps
}: ButtonWithTooltipProps) {
+ // The native title doubles as the accessible hint when the tooltip cannot
+ // open — an explicit title wins over the tooltip text.
const title =
- typeof buttonProps.title === "string"
+ typeof buttonProps.title === "string" && buttonProps.title.trim()
? buttonProps.title
: tooltipContent
@@ -33,19 +31,17 @@ export function ButtonWithTooltip({
return (
<Tooltip>
+ {/* A disabled button emits no pointer events, so the trigger needs
+ a wrapper or the tooltip never opens on exactly the buttons
+ whose reason for being disabled the user wants explained. */}
<TooltipTrigger asChild>
{buttonProps.disabled ? (
- <span className="inline-flex cursor-not-allowed">
- {button}
- </span>
+ <span className="inline-flex cursor-not-allowed">{button}</span>
) : (
button
)}
</TooltipTrigger>
- <TooltipContent className="max-w-xs text-wrap">
- {tooltipContent}
- </TooltipContent>
+ <TooltipContent className="max-w-xs text-wrap">{tooltipContent}</TooltipContent>
</Tooltip>
)
}
-
diff --git a/src/workspaces/ppt/chat/ChatInput.tsx b/src/shared/chat/chat-input.tsx
similarity index 97%
rename from src/workspaces/ppt/chat/ChatInput.tsx
rename to src/shared/chat/chat-input.tsx
index cad4045..2625466 100644
--- a/src/workspaces/ppt/chat/ChatInput.tsx
+++ b/src/shared/chat/chat-input.tsx
@@ -1,9 +1,9 @@
-import React, { useRef, useEffect, useMemo, useState, useCallback } from 'react';
+import React, { useRef, useEffect, useMemo, useState, useCallback } from 'react';
import { Send, FileText, ImageIcon, History, Square, Trash2 } from 'lucide-react';
import { cn } from '@/shared/lib/utils';
-import { ButtonWithTooltip } from '@/workspaces/ppt/chat/components/button-with-tooltip';
-import { FilePreviewList } from '@/workspaces/ppt/chat/file-preview-list';
-import { useFileProcessor } from '@/shared/files/use-file-processor';
+import { ButtonWithTooltip } from '@/shared/chat';
+import { FilePreviewList } from '@/shared/chat';
+import { type FileWorkspace, useFileProcessor } from '@/shared/files/use-file-processor';
import { t, useUiLanguage } from "@/shared/i18n";
type RichInputSegment =
@@ -31,6 +31,8 @@ interface ChatInputProps {
onInsertPptTokenHandled?: () => void;
clearKey?: string | number;
uploadMode?: "all" | "imagesOnly" | "filesOnly" | "none";
+ /** Tags extraction telemetry with the workspace the upload came from. */
+ workspaceId?: FileWorkspace;
}
export function ChatInput({
@@ -53,9 +55,11 @@ export function ChatInput({
insertPptToken,
onInsertPptTokenHandled,
clearKey,
- uploadMode = "all"
+ uploadMode = "all",
+ workspaceId = "unknown",
}: ChatInputProps) {
const uiLang = useUiLanguage();
+ const trText = (zhText: string, enText: string) => (uiLang === "zh" ? zhText : enText);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const richRef = useRef<HTMLDivElement>(null);
const richSavedRangeRef = useRef<Range | null>(null);
@@ -64,7 +68,7 @@ export function ChatInput({
const richAppliedRef = useRef<string>("");
const [richHasFocus, setRichHasFocus] = useState(false);
- const { files, handleFileChange, setFiles, pdfData } = useFileProcessor("ppt");
+ const { files, handleFileChange, setFiles, pdfData } = useFileProcessor(workspaceId);
const isRich = !!(richSegments && onRichSegmentsChange);
// Sync controlled files if provided
@@ -410,7 +414,7 @@ export function ChatInput({
<div className="relative">
{showRichPlaceholder && (
<div className="pointer-events-none absolute left-1 top-2 text-[15px] leading-6 text-muted-foreground/60">
- {placeholder || "Type your message..."}
+ {placeholder || trText("请输入消息...", "Type your message...")}
</div>
)}
<div
@@ -518,7 +522,7 @@ export function ChatInput({
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
- placeholder={placeholder || "Type your message..."}
+ placeholder={placeholder || trText("请输入消息...", "Type your message...")}
className={cn(
"w-full resize-none bg-transparent border-none px-1 py-2 focus:ring-0 transition-all outline-none text-[15px] leading-6 max-h-[360px] overflow-y-auto min-h-[48px]"
)}
diff --git a/src/workspaces/cad/chat/file-preview-list.tsx b/src/shared/chat/file-preview-list.tsx
similarity index 100%
rename from src/workspaces/cad/chat/file-preview-list.tsx
rename to src/shared/chat/file-preview-list.tsx
diff --git a/src/workspaces/cad/chat/global-constraints-dialog.tsx b/src/shared/chat/global-constraints-dialog.tsx
similarity index 60%
rename from src/workspaces/cad/chat/global-constraints-dialog.tsx
rename to src/shared/chat/global-constraints-dialog.tsx
index 91f68a7..2fe1660 100644
--- a/src/workspaces/cad/chat/global-constraints-dialog.tsx
+++ b/src/shared/chat/global-constraints-dialog.tsx
@@ -9,42 +9,51 @@ import {
DialogTitle,
} from "@/shared/ui/dialog"
import { Textarea } from "@/shared/ui/textarea"
-import { t, useUiLanguage } from "@/shared/i18n";
+import { t, useUiLanguage } from "@/shared/i18n"
+/**
+ * Standing instructions the workspace prepends to every request.
+ *
+ * Constraints are scoped per workspace: a CAD drawing convention has no place
+ * in a slide deck. Flow passes an explicit storageKey to keep reading the key
+ * it shipped with, so nobody's saved constraints disappear.
+ */
export const STORAGE_GLOBAL_CONSTRAINTS_KEY = "CanvasAnvil-global-constraints"
+const WORKSPACE_LABELS: Record<string, string> = {
+ flow: "Flow",
+ cad: "CAD",
+ ppt: "PPT",
+}
+
interface GlobalConstraintsDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
- workspaceId?: string // Optional workspace ID to scope constraints
+ /** Scopes the constraints; also names the workspace in the title. */
+ workspaceId?: string
+ /** Overrides the derived key. Only needed for a pre-existing key. */
+ storageKey?: string
}
export function GlobalConstraintsDialog({
open,
onOpenChange,
- workspaceId
+ workspaceId,
+ storageKey: storageKeyOverride,
}: GlobalConstraintsDialogProps) {
const [constraints, setConstraints] = useState("")
- const uiLang = useUiLanguage();
- const workspaceLabel =
- workspaceId === "flow"
- ? "Flow"
- : workspaceId === "cad"
- ? "CAD"
- : workspaceId === "ppt"
- ? "PPT"
- : "General"
-
- // Determine the actual storage key
- const storageKey = workspaceId
- ? `${STORAGE_GLOBAL_CONSTRAINTS_KEY}-${workspaceId}`
- : STORAGE_GLOBAL_CONSTRAINTS_KEY;
+ const uiLang = useUiLanguage()
+
+ const workspaceLabel = (workspaceId && WORKSPACE_LABELS[workspaceId]) || "General"
+ const storageKey =
+ storageKeyOverride ??
+ (workspaceId
+ ? `${STORAGE_GLOBAL_CONSTRAINTS_KEY}-${workspaceId}`
+ : STORAGE_GLOBAL_CONSTRAINTS_KEY)
useEffect(() => {
- if (open) {
- const saved = localStorage.getItem(storageKey) || ""
- setConstraints(saved)
- }
+ if (!open) return
+ setConstraints(localStorage.getItem(storageKey) || "")
}, [open, storageKey])
const handleSave = () => {
@@ -59,9 +68,7 @@ export function GlobalConstraintsDialog({
<DialogTitle>
{t(uiLang, "constraints.title")} ({workspaceLabel})
</DialogTitle>
- <DialogDescription>
- {t(uiLang, "constraints.desc")}
- </DialogDescription>
+ <DialogDescription>{t(uiLang, "constraints.desc")}</DialogDescription>
</DialogHeader>
<div className="grid gap-4 py-4">
<Textarea
@@ -80,4 +87,3 @@ export function GlobalConstraintsDialog({
</Dialog>
)
}
-
diff --git a/src/workspaces/cad/chat/history-dialog.tsx b/src/shared/chat/history-dialog.tsx
similarity index 100%
rename from src/workspaces/cad/chat/history-dialog.tsx
rename to src/shared/chat/history-dialog.tsx
diff --git a/src/shared/chat/index.ts b/src/shared/chat/index.ts
new file mode 100644
index 0000000..04b87fd
--- /dev/null
+++ b/src/shared/chat/index.ts
@@ -0,0 +1,8 @@
+export * from "@/shared/chat/shimmer";
+export * from "@/shared/chat/reasoning";
+export * from "@/shared/chat/button-with-tooltip";
+export * from "@/shared/chat/reset-warning-modal";
+export * from "@/shared/chat/global-constraints-dialog";
+export * from "@/shared/chat/file-preview-list";
+export * from "@/shared/chat/history-dialog";
+export * from "@/shared/chat/chat-input";
diff --git a/src/workspaces/cad/chat/components/reasoning.tsx b/src/shared/chat/reasoning.tsx
similarity index 99%
rename from src/workspaces/cad/chat/components/reasoning.tsx
rename to src/shared/chat/reasoning.tsx
index 92c49b7..a8b9f67 100644
--- a/src/workspaces/cad/chat/components/reasoning.tsx
+++ b/src/shared/chat/reasoning.tsx
@@ -9,7 +9,7 @@ import {
} from "@/shared/ui/collapsible"
import { useUiLanguage } from "@/shared/i18n"
import { cn } from "@/shared/lib/utils"
-import { Shimmer } from "./shimmer"
+import { Shimmer } from "@/shared/chat/shimmer"
type ReasoningContextValue = {
isStreaming: boolean
diff --git a/src/shared/chat/reset-warning-modal.tsx b/src/shared/chat/reset-warning-modal.tsx
new file mode 100644
index 0000000..5b00da7
--- /dev/null
+++ b/src/shared/chat/reset-warning-modal.tsx
@@ -0,0 +1,63 @@
+import { Button } from "@/shared/ui/button"
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/shared/ui/dialog"
+import { t, useUiLanguage } from "@/shared/i18n"
+
+/**
+ * Confirmation before a destructive clear.
+ *
+ * Labels are overridable because what gets cleared differs per workspace —
+ * Flow drops the diagram along with the conversation, the others only the
+ * conversation — and the wording has to say so.
+ */
+export interface ResetWarningLabels {
+ title?: string
+ description?: string
+ cancel?: string
+ confirm?: string
+}
+
+interface ResetWarningModalProps {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ onClear: () => void
+ labels?: ResetWarningLabels
+}
+
+export function ResetWarningModal({
+ open,
+ onOpenChange,
+ onClear,
+ labels,
+}: ResetWarningModalProps) {
+ const uiLang = useUiLanguage()
+ const title = labels?.title ?? t(uiLang, "reset.title")
+ const description = labels?.description ?? t(uiLang, "reset.desc")
+ const cancel = labels?.cancel ?? t(uiLang, "common.cancel")
+ const confirm = labels?.confirm ?? t(uiLang, "common.clear")
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{title}</DialogTitle>
+ <DialogDescription>{description}</DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button variant="outline" onClick={() => onOpenChange(false)} title={cancel}>
+ {cancel}
+ </Button>
+ <Button variant="destructive" onClick={onClear} title={confirm}>
+ {confirm}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/src/workspaces/flow/next/components/ai-elements/shimmer.tsx b/src/shared/chat/shimmer.tsx
similarity index 98%
rename from src/workspaces/flow/next/components/ai-elements/shimmer.tsx
rename to src/shared/chat/shimmer.tsx
index 0e1122a..95460ba 100644
--- a/src/workspaces/flow/next/components/ai-elements/shimmer.tsx
+++ b/src/shared/chat/shimmer.tsx
@@ -1,5 +1,3 @@
-"use client"
-
import { motion } from "motion/react"
import {
type CSSProperties,
@@ -62,4 +60,3 @@ const ShimmerComponent = ({
}
export const Shimmer = memo(ShimmerComponent)
-
diff --git a/src/workspaces/cad/chat/ChatInput.tsx b/src/workspaces/cad/chat/ChatInput.tsx
deleted file mode 100644
index 4280b8e..0000000
--- a/src/workspaces/cad/chat/ChatInput.tsx
+++ /dev/null
@@ -1,640 +0,0 @@
-import React, { useRef, useEffect, useMemo, useState, useCallback } from 'react';
-import { Send, FileText, ImageIcon, History, Square, Trash2 } from 'lucide-react';
-import { cn } from '@/shared/lib/utils';
-import { ButtonWithTooltip } from '@/workspaces/cad/chat/components/button-with-tooltip';
-import { FilePreviewList } from '@/workspaces/cad/chat/file-preview-list';
-import { useFileProcessor } from '@/shared/files/use-file-processor';
-import { t, useUiLanguage } from "@/shared/i18n";
-
-type RichInputSegment =
- | { type: "text"; text: string }
- | { type: "ppt"; slideId: string; label: string; tag: string };
-
-interface ChatInputProps {
- input: string;
- setInput: (value: string) => void;
- onSubmit: () => void;
- isLoading: boolean;
- onStop?: () => void;
- onClearChat?: () => void;
- onToggleHistory?: () => void;
- historyDisabled?: boolean;
- onFilesChange?: (files: File[]) => void;
- files?: File[]; // Controlled files
- placeholder?: string;
- topChips?: React.ReactNode;
- bottomChips?: React.ReactNode;
- focusKey?: string | number;
- richSegments?: RichInputSegment[];
- onRichSegmentsChange?: (segments: RichInputSegment[]) => void;
- insertPptToken?: { key: number; slideId: string; label: string; tag: string } | null;
- onInsertPptTokenHandled?: () => void;
- clearKey?: string | number;
- uploadMode?: "all" | "imagesOnly" | "filesOnly" | "none";
-}
-
-export function ChatInput({
- input,
- setInput,
- onSubmit,
- isLoading,
- onStop,
- onClearChat,
- onToggleHistory,
- historyDisabled = false,
- onFilesChange,
- files: controlledFiles,
- placeholder,
- topChips,
- bottomChips,
- focusKey,
- richSegments,
- onRichSegmentsChange,
- insertPptToken,
- onInsertPptTokenHandled,
- clearKey,
- uploadMode = "all"
-}: ChatInputProps) {
- const uiLang = useUiLanguage();
- const trText = (zhText: string, enText: string) => (uiLang === "zh" ? zhText : enText);
- const textareaRef = useRef<HTMLTextAreaElement>(null);
- const richRef = useRef<HTMLDivElement>(null);
- const richSavedRangeRef = useRef<Range | null>(null);
- const fileInputRef = useRef<HTMLInputElement>(null);
- const imageInputRef = useRef<HTMLInputElement>(null);
- const richAppliedRef = useRef<string>("");
- const [richHasFocus, setRichHasFocus] = useState(false);
-
- const { files, handleFileChange, setFiles, pdfData } = useFileProcessor("cad");
- const isRich = !!(richSegments && onRichSegmentsChange);
-
- // Sync controlled files if provided
- useEffect(() => {
- if (controlledFiles) {
- setFiles(controlledFiles);
- }
- }, [controlledFiles, setFiles]);
-
- // Notify parent when files change
- useEffect(() => {
- onFilesChange?.(files);
- }, [files, onFilesChange]);
-
- const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
- if (e.key === 'Enter' && !e.shiftKey) {
- e.preventDefault();
- if (isLoading) onStop?.();
- else onSubmit();
- }
- };
-
- const autoResizeTextarea = useCallback(() => {
- if (isRich) return;
- const el = textareaRef.current;
- if (!el) return;
- el.style.height = 'auto';
- el.style.height = `${Math.min(el.scrollHeight, 200)}px`;
- }, [isRich]);
-
- useEffect(() => {
- autoResizeTextarea();
- }, [input, isRich, placeholder, autoResizeTextarea]);
-
- useEffect(() => {
- if (isRich) return;
- const el = textareaRef.current;
- if (!el) return;
-
- let raf = 0;
- const schedule = () => {
- if (raf) cancelAnimationFrame(raf);
- raf = requestAnimationFrame(() => {
- raf = 0;
- autoResizeTextarea();
- });
- };
-
- schedule();
-
- if (typeof ResizeObserver !== "undefined") {
- const ro = new ResizeObserver(() => schedule());
- ro.observe(el);
- ro.observe(el.parentElement ?? el);
- return () => {
- if (raf) cancelAnimationFrame(raf);
- ro.disconnect();
- };
- }
-
- window.addEventListener("resize", schedule);
- return () => {
- if (raf) cancelAnimationFrame(raf);
- window.removeEventListener("resize", schedule);
- };
- }, [isRich, autoResizeTextarea]);
-
- useEffect(() => {
- if (focusKey === undefined) return;
- if (isRich) richRef.current?.focus();
- else textareaRef.current?.focus();
- }, [focusKey]);
-
- useEffect(() => {
- if (clearKey === undefined) return;
- if (!isRich) return;
- const root = richRef.current;
- if (!root) return;
- richSavedRangeRef.current = null;
- root.innerHTML = "";
- root.appendChild(document.createTextNode(""));
- richAppliedRef.current = "";
- onRichSegmentsChange?.([{ type: "text", text: "" }]);
- }, [clearKey, isRich]);
-
- const serializeSegments = (segments: RichInputSegment[]) => {
- return segments
- .map((s) => (s.type === "text" ? `t:${s.text}` : `p:${s.slideId}:${s.tag}`))
- .join("|");
- };
-
- const buildLabelSpan = (segment: Extract<RichInputSegment, { type: "ppt" }>) => {
- const el = document.createElement("span");
- el.setAttribute("data-token", "ppt");
- el.setAttribute("data-slide-id", segment.slideId);
- el.setAttribute("data-label", segment.label);
- el.setAttribute("data-tag", segment.tag);
- el.setAttribute("contenteditable", "false");
- el.className = "inline-flex items-center gap-1.5 rounded-full border border-red-200 bg-red-50 px-2 py-0.5 text-xs font-medium text-red-700 dark:border-red-400/30 dark:bg-red-950/40 dark:text-red-200 align-middle";
- const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
- svg.setAttribute("viewBox", "0 0 24 24");
- svg.setAttribute("fill", "none");
- svg.setAttribute("stroke", "currentColor");
- svg.setAttribute("stroke-width", "2");
- svg.setAttribute("stroke-linecap", "round");
- svg.setAttribute("stroke-linejoin", "round");
- svg.setAttribute("aria-hidden", "true");
- svg.setAttribute("class", "h-3.5 w-3.5 text-red-600 dark:text-red-200");
- const path1 = document.createElementNS("http://www.w3.org/2000/svg", "path");
- // Draw a "P" icon
- path1.setAttribute("d", "M19 7a5 5 0 0 0-5-5H7a1 1 0 0 0-1 1v18a1 1 0 0 0 1 1h1a1 1 0 0 0 1-1v-8h5a5 5 0 0 0 5-5z");
- // Actually a simpler P stroke might be better for 24x24
- // P shape: M8 20V4h6a4 4 0 0 1 0 8H8
- path1.setAttribute("d", "M8 20V4h6a4 4 0 0 1 0 8H8");
-
- svg.appendChild(path1);
- const text = document.createElement("span");
- text.textContent = segment.label;
- el.appendChild(svg);
- el.appendChild(text);
- return el;
- };
-
- const setRichContentFromSegments = (segments: RichInputSegment[]) => {
- const root = richRef.current;
- if (!root) return;
- root.innerHTML = "";
- for (const seg of segments) {
- if (seg.type === "text") {
- const parts = String(seg.text || "").split("\n");
- for (let i = 0; i < parts.length; i += 1) {
- if (parts[i]) root.appendChild(document.createTextNode(parts[i]));
- if (i < parts.length - 1) root.appendChild(document.createElement("br"));
- }
- continue;
- }
- root.appendChild(buildLabelSpan(seg));
- root.appendChild(document.createTextNode(" "));
- }
- if (!root.lastChild) root.appendChild(document.createTextNode(""));
- };
-
- const parseRichSegmentsFromDom = (): RichInputSegment[] => {
- const root = richRef.current;
- if (!root) return [{ type: "text", text: "" }];
-
- const out: RichInputSegment[] = [];
- const pushText = (t: string) => {
- if (!t) return;
- const last = out[out.length - 1];
- if (last?.type === "text") last.text += t;
- else out.push({ type: "text", text: t });
- };
-
- for (const node of Array.from(root.childNodes)) {
- if (node.nodeType === Node.TEXT_NODE) {
- pushText(node.textContent || "");
- continue;
- }
- if (node.nodeType !== Node.ELEMENT_NODE) continue;
- const el = node as HTMLElement;
- if (el.tagName === "BR") {
- pushText("\n");
- continue;
- }
- const token = el.getAttribute("data-token");
- if (token === "ppt") {
- const slideId = el.getAttribute("data-slide-id") || "";
- const label = el.getAttribute("data-label") || el.textContent || "";
- const tag = el.getAttribute("data-tag") || "";
- if (slideId && tag) out.push({ type: "ppt", slideId, label, tag });
- continue;
- }
- pushText(el.textContent || "");
- }
-
- if (out.length === 0) return [{ type: "text", text: "" }];
- return out;
- };
-
- const syncRichToParent = () => {
- if (!isRich) return;
- const next = parseRichSegmentsFromDom();
- const key = serializeSegments(next);
- if (key === richAppliedRef.current) return;
- richAppliedRef.current = key;
- onRichSegmentsChange?.(next);
- };
-
- useEffect(() => {
- if (!isRich) return;
- const segments = richSegments || [{ type: "text", text: "" }];
- const key = serializeSegments(segments);
- if (key === richAppliedRef.current) return;
- richAppliedRef.current = key;
- if (richHasFocus) return;
- setRichContentFromSegments(segments);
- }, [isRich, richSegments, richHasFocus]);
-
- const insertPptTokenAtCursor = (slideId: string, label: string, tag: string) => {
- const root = richRef.current;
- if (!root) return;
- root.focus();
- const sel = window.getSelection();
- let range: Range | null = sel && sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
- if (!range || !root.contains(range.startContainer)) {
- range = richSavedRangeRef.current;
- }
- if (!range || !root.contains(range.startContainer)) {
- range = document.createRange();
- range.selectNodeContents(root);
- range.collapse(false);
- }
- const span = buildLabelSpan({ type: "ppt", slideId, label, tag });
- const space = document.createTextNode(" ");
- range.insertNode(space);
- range.insertNode(span);
- range.setStartAfter(space);
- range.collapse(true);
- if (sel) {
- sel.removeAllRanges();
- sel.addRange(range);
- }
- richSavedRangeRef.current = range;
- syncRichToParent();
- };
-
- useEffect(() => {
- if (!isRich) return;
- if (!insertPptToken) return;
- insertPptTokenAtCursor(insertPptToken.slideId, insertPptToken.label, insertPptToken.tag);
- onInsertPptTokenHandled?.();
- }, [isRich, insertPptToken?.key]);
-
- const richPlainText = useMemo(() => {
- const segs = richSegments || [];
- return segs
- .map((s) => (s.type === "text" ? s.text : s.label))
- .join("")
- .replace(/[ \t]+\n/g, "\n");
- }, [richSegments]);
-
- 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;
- const pastedFiles: File[] = [];
-
- for (let i = 0; i < items.length; i++) {
- if (items[i].kind === 'file') {
- const file = items[i].getAsFile();
- if (file) pastedFiles.push(file);
- }
- }
-
- if (pastedFiles.length > 0) {
- const filtered = filterByUploadMode(pastedFiles);
- if (filtered.length === 0) return;
- e.preventDefault();
- handleFileChange([...files, ...filtered]);
- }
- };
-
- const handleDrop = (e: React.DragEvent) => {
- e.preventDefault();
- if (uploadMode === "none") return;
- const droppedFiles = Array.from(e.dataTransfer.files);
- const filtered = filterByUploadMode(droppedFiles);
- if (filtered.length > 0) {
- handleFileChange([...files, ...filtered]);
- }
- };
-
- const handleImageUpload = () => imageInputRef.current?.click();
- const handleFileUpload = () => fileInputRef.current?.click();
-
- const onFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
- if (e.target.files?.length) {
- const incoming = Array.from(e.target.files);
- const filtered = filterByUploadMode(incoming);
- if (filtered.length > 0) handleFileChange([...files, ...filtered]);
- e.target.value = ''; // Reset
- }
- };
-
- const removeFile = (fileToRemove: File) => {
- setFiles(files.filter(f => f !== fileToRemove));
- };
-
- return (
- <div
- className="relative rounded-2xl border border-border bg-background shadow-sm focus-within:ring-2 focus-within:ring-primary/20 focus-within:border-primary/50 transition-all duration-200"
- onDragOver={(e) => e.preventDefault()}
- onDrop={handleDrop}
- >
- {(uploadMode === "all" || uploadMode === "imagesOnly") && (
- <input
- type="file"
- multiple
- accept="image/*"
- className="hidden"
- ref={imageInputRef}
- onChange={onFileInputChange}
- />
- )}
- {(uploadMode === "all" || uploadMode === "filesOnly") && (
- <input
- type="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}
- />
- )}
-
- {files.length > 0 && (
- <div className="px-3 pt-3">
- <FilePreviewList
- files={files}
- onRemoveFile={removeFile}
- pdfData={pdfData}
- />
- </div>
- )}
-
- {topChips && (
- <div className="px-3 pt-3">
- {topChips}
- </div>
- )}
-
- <div className="px-3 pt-2">
- {isRich ? (
- <div className="relative">
- {showRichPlaceholder && (
- <div className="pointer-events-none absolute left-1 top-2 text-[15px] leading-6 text-muted-foreground/60">
- {placeholder || trText("请输入消息...", "Type your message...")}
- </div>
- )}
- <div
- ref={richRef}
- contentEditable
- suppressContentEditableWarning
- onKeyDown={(e) => {
- if (e.key === "Enter" && !e.shiftKey) {
- e.preventDefault();
- if (isLoading) onStop?.();
- else onSubmit();
- return;
- }
- if (e.key === "Backspace" || e.key === "Delete") {
- const root = richRef.current;
- if (!root) return;
- const sel = window.getSelection();
- if (!sel || sel.rangeCount === 0) return;
- const r = sel.getRangeAt(0);
- if (!root.contains(r.startContainer) || !r.collapsed) return;
- const container = r.startContainer;
- const offset = r.startOffset;
-
- const tryRemoveToken = (el: Element | null) => {
- if (!el) return false;
- const token = (el as HTMLElement).getAttribute("data-token");
- if (token !== "ppt") return false;
- el.remove();
- syncRichToParent();
- return true;
- };
-
- if (container.nodeType === Node.TEXT_NODE) {
- if (e.key === "Backspace" && offset === 0) {
- const prev = (container as Text).previousSibling;
- if (prev && prev.nodeType === Node.ELEMENT_NODE) {
- if (tryRemoveToken(prev as Element)) {
- e.preventDefault();
- return;
- }
- }
- }
- if (e.key === "Delete" && offset === (container as Text).data.length) {
- const next = (container as Text).nextSibling;
- if (next && next.nodeType === Node.ELEMENT_NODE) {
- if (tryRemoveToken(next as Element)) {
- e.preventDefault();
- return;
- }
- }
- }
- } else if (container.nodeType === Node.ELEMENT_NODE) {
- const el = container as Element;
- const child = el.childNodes[offset + (e.key === "Backspace" ? -1 : 0)];
- if (child && child.nodeType === Node.ELEMENT_NODE) {
- if (tryRemoveToken(child as Element)) {
- e.preventDefault();
- return;
- }
- }
- }
- }
- }}
- onPaste={handlePaste as any}
- onFocus={() => setRichHasFocus(true)}
- onBlur={() => {
- setRichHasFocus(false);
- const sel = window.getSelection();
- if (sel && sel.rangeCount > 0) {
- const r = sel.getRangeAt(0);
- if (richRef.current?.contains(r.startContainer)) {
- richSavedRangeRef.current = r;
- }
- }
- syncRichToParent();
- }}
- onInput={() => syncRichToParent()}
- onKeyUp={() => {
- const sel = window.getSelection();
- if (sel && sel.rangeCount > 0) {
- const r = sel.getRangeAt(0);
- if (richRef.current?.contains(r.startContainer)) {
- richSavedRangeRef.current = r;
- }
- }
- }}
- onMouseUp={() => {
- const sel = window.getSelection();
- if (sel && sel.rangeCount > 0) {
- const r = sel.getRangeAt(0);
- if (richRef.current?.contains(r.startContainer)) {
- richSavedRangeRef.current = r;
- }
- }
- }}
- className={cn(
- "w-full bg-transparent border-none px-1 py-2 focus:ring-0 transition-all outline-none text-[15px] leading-6 max-h-[360px] overflow-y-auto min-h-[48px] whitespace-pre-wrap break-words"
- )}
- />
- </div>
- ) : (
- <textarea
- ref={textareaRef}
- value={input}
- onChange={(e) => setInput(e.target.value)}
- onKeyDown={handleKeyDown}
- onPaste={handlePaste}
- placeholder={placeholder || trText("请输入消息...", "Type your message...")}
- className={cn(
- "w-full resize-none bg-transparent border-none px-1 py-2 focus:ring-0 transition-all outline-none text-[15px] leading-6 max-h-[360px] overflow-y-auto min-h-[48px]"
- )}
- rows={1}
- />
- )}
- </div>
-
- {bottomChips && (
- <div className="px-3 pb-2">
- {bottomChips}
- </div>
- )}
-
- <div className="flex items-center justify-between px-3 py-2 border-t border-border/50">
- <div className="flex items-center gap-1">
- {onClearChat && (
- <ButtonWithTooltip
- tooltipContent={t(uiLang, "chat.clearChatTitle")}
- variant="ghost"
- size="sm"
- onClick={onClearChat}
- className="h-8 w-8 p-0 text-muted-foreground hover:text-destructive hover:bg-destructive/10"
- >
- <Trash2 className="h-4 w-4" />
- </ButtonWithTooltip>
- )}
- </div>
-
- <div className="flex items-center gap-1">
- {onToggleHistory && (
- <ButtonWithTooltip
- tooltipContent={t(uiLang, "chat.historyTitle")}
- variant="ghost"
- size="sm"
- onClick={onToggleHistory}
- disabled={historyDisabled}
- className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"
- >
- <History className="h-4 w-4" />
- </ButtonWithTooltip>
- )}
-
- {(uploadMode === "all" || uploadMode === "imagesOnly") && (
- <ButtonWithTooltip
- tooltipContent={t(uiLang, "chat.uploadImage")}
- variant="ghost"
- size="sm"
- onClick={handleImageUpload}
- className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"
- >
- <ImageIcon className="h-4 w-4" />
- </ButtonWithTooltip>
- )}
-
- {(uploadMode === "all" || uploadMode === "filesOnly") && (
- <ButtonWithTooltip
- tooltipContent={t(uiLang, "chat.uploadFile")}
- variant="ghost"
- size="sm"
- onClick={handleFileUpload}
- className="h-8 w-8 p-0 text-muted-foreground hover:text-foreground"
- >
- <FileText className="h-4 w-4" />
- </ButtonWithTooltip>
- )}
-
- <div className="w-px h-5 bg-border mx-1" />
-
- {(() => {
- const hasText = isRich ? richPlainText.trim().length > 0 : input.trim().length > 0;
- const hasFiles = files.length > 0;
- if (isLoading) {
- return (
- <ButtonWithTooltip
- tooltipContent={t(uiLang, "chat.stop")}
- variant="default"
- size="sm"
- onClick={(e) => {
- e.preventDefault();
- onStop?.();
- }}
- disabled={!onStop}
- className="h-8 w-8 p-0 rounded-xl shadow-sm"
- aria-label={t(uiLang, "chat.stop")}
- >
- <Square className="h-3.5 w-3.5 fill-current" />
- </ButtonWithTooltip>
- );
- }
- return (
- <ButtonWithTooltip
- type="button"
- onClick={onSubmit}
- tooltipContent={t(uiLang, "chat.send")}
- disabled={!hasText && !hasFiles}
- variant="default"
- size="sm"
- className={cn(
- "h-8 w-8 p-0 rounded-xl shadow-sm",
- (!hasText && !hasFiles) ? "opacity-60" : ""
- )}
- aria-label={t(uiLang, "chat.send")}
- >
- <Send className="h-4 w-4" />
- </ButtonWithTooltip>
- );
- })()}
- </div>
- </div>
- </div>
- );
-}
-
-
diff --git a/src/workspaces/cad/chat/ChatMessageDisplay.tsx b/src/workspaces/cad/chat/ChatMessageDisplay.tsx
index 78c3260..f537188 100644
--- a/src/workspaces/cad/chat/ChatMessageDisplay.tsx
+++ b/src/workspaces/cad/chat/ChatMessageDisplay.tsx
@@ -19,7 +19,7 @@ import {
} from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkGfm from 'remark-gfm';
-import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/workspaces/cad/chat/components/reasoning";
+import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/shared/chat";
import { ScrollArea } from "@/shared/ui/scroll-area";
import { CodeBlock } from "@/workspaces/cad/chat/code-block";
import { useUiLanguage } from "@/shared/i18n";
diff --git a/src/workspaces/cad/chat/ChatPanel.tsx b/src/workspaces/cad/chat/ChatPanel.tsx
index e642444..b7c0530 100644
--- a/src/workspaces/cad/chat/ChatPanel.tsx
+++ b/src/workspaces/cad/chat/ChatPanel.tsx
@@ -3,12 +3,12 @@ import { PanelRightClose, PanelRightOpen } from 'lucide-react';
import { cn } from '@/shared/lib/utils';
import { streamChatMessage, generateChatMessage, ChatMessage, getAIConfig } from '@/ai/client';
import { DRAWIO_SYSTEM_PROMPT } from '@/lib/system-prompts';
-import { ButtonWithTooltip } from '@/workspaces/cad/chat/components/button-with-tooltip';
-import { ChatInput } from '@/workspaces/cad/chat/ChatInput';
+import { ButtonWithTooltip } from '@/shared/chat';
+import { ChatInput } from '@/shared/chat';
import { ChatMessageDisplay, UIMessage } from '@/workspaces/cad/chat/ChatMessageDisplay';
-import { STORAGE_GLOBAL_CONSTRAINTS_KEY } from '@/workspaces/cad/chat/global-constraints-dialog';
-import { HistoryDialog, HistoryItem } from '@/workspaces/cad/chat/history-dialog';
-import { ResetWarningModal } from '@/workspaces/cad/chat/reset-warning-modal';
+import { STORAGE_GLOBAL_CONSTRAINTS_KEY } from '@/shared/chat';
+import { HistoryDialog, HistoryItem } from '@/shared/chat';
+import { ResetWarningModal } from '@/shared/chat';
import { useFileProcessor } from '@/shared/files/use-file-processor';
import {
buildCadAnalysisMessages,
@@ -290,7 +290,7 @@ export function ChatPanel({
});
const [input, setInput] = useState('');
- const [pptInputSegments, setPptInputSegments] = useState<Array<{ type: "text"; text: string } | { type: "ppt"; slideId: string; label: string; tag: string }>>([
+ const [pptInputSegments, setPptInputSegments] = useState<Array<{ type: "text"; text: string } | { type: "ppt"; slideId: string; label: string; tag: string; tokenKind: "outline" | "slide_image" }>>([
{ type: "text", text: "" }
]);
const [isLoading, setIsLoading] = useState(false);
@@ -307,7 +307,7 @@ export function ChatPanel({
const [pptInputFocusTick, setPptInputFocusTick] = useState(0);
const prevPptDraftCountRef = useRef(0);
const prevPptDraftIdsRef = useRef<Set<string>>(new Set());
- const [pptInsertToken, setPptInsertToken] = useState<{ key: number; slideId: string; label: string; tag: string } | null>(null);
+ const [pptInsertToken, setPptInsertToken] = useState<{ key: number; slideId: string; label: string; tag: string; tokenKind: "outline" | "slide_image" } | null>(null);
const pptInsertQueueRef = useRef<Array<{ slideId: string; title: string; label: string }>>([]);
const pptInsertBusyRef = useRef(false);
const [pptClearTick, setPptClearTick] = useState(0);
@@ -336,7 +336,9 @@ export function ChatPanel({
if (!next) return;
pptInsertBusyRef.current = true;
const tag = getPptTag(next.slideId, next.title);
- setPptInsertToken({ key: Date.now() + Math.random(), slideId: next.slideId, label: next.label, tag });
+ // This queue only runs when workspaceId === "ppt"; CAD never reaches it.
+ // The PPT fork of this panel is the one that actually drives it.
+ setPptInsertToken({ key: Date.now() + Math.random(), slideId: next.slideId, label: next.label, tag, tokenKind: "slide_image" });
};
const enqueuePptToken = (slideId: string, title: string) => {
@@ -1082,7 +1084,7 @@ export function ChatPanel({
const referencedPptSlideIds = isPpt
? new Set(
pptInputSegments
- .filter((s): s is { type: "ppt"; slideId: string; label: string; tag: string } => s.type === "ppt")
+ .filter((s): s is { type: "ppt"; slideId: string; label: string; tag: string; tokenKind: "outline" | "slide_image" } => s.type === "ppt")
.map((s) => s.slideId)
)
: new Set<string>();
@@ -2979,6 +2981,7 @@ export function ChatPanel({
{/* Input */}
<div className="p-4 border-t border-border/50 bg-card/50">
<ChatInput
+ workspaceId={workspaceId === "cad" || workspaceId === "ppt" ? workspaceId : "unknown"}
input={input}
setInput={setInput}
onSubmit={handleSend}
diff --git a/src/workspaces/cad/chat/components/button-with-tooltip.tsx b/src/workspaces/cad/chat/components/button-with-tooltip.tsx
deleted file mode 100644
index 0acd1c4..0000000
--- a/src/workspaces/cad/chat/components/button-with-tooltip.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import type { VariantProps } from "class-variance-authority"
-import type React from "react"
-import { Button, type buttonVariants } from "@/shared/ui/button"
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/shared/ui/tooltip"
-
-interface ButtonWithTooltipProps
- extends React.ComponentProps<"button">,
- VariantProps<typeof buttonVariants> {
- tooltipContent: string
- children: React.ReactNode
- asChild?: boolean
-}
-
-export function ButtonWithTooltip({
- tooltipContent,
- children,
- ...buttonProps
-}: ButtonWithTooltipProps) {
- const mergedTitle =
- typeof buttonProps.title === "string" && buttonProps.title.trim()
- ? buttonProps.title
- : tooltipContent;
- return (
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button {...buttonProps} title={mergedTitle}>{children}</Button>
- </TooltipTrigger>
- <TooltipContent className="max-w-xs text-wrap">
- {tooltipContent}
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- )
-}
diff --git a/src/workspaces/cad/chat/components/shimmer.tsx b/src/workspaces/cad/chat/components/shimmer.tsx
deleted file mode 100644
index 8651161..0000000
--- a/src/workspaces/cad/chat/components/shimmer.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import { motion } from "framer-motion"
-import {
- type CSSProperties,
- type ElementType,
- type JSX,
- memo,
- useMemo,
-} from "react"
-import { cn } from "@/shared/lib/utils"
-
-export type TextShimmerProps = {
- children: string
- as?: ElementType
- className?: string
- duration?: number
- spread?: number
-}
-
-const ShimmerComponent = ({
- children,
- as: Component = "p",
- className,
- duration = 2,
- spread = 2,
-}: TextShimmerProps) => {
- const MotionComponent = motion.create(
- Component as keyof JSX.IntrinsicElements,
- )
-
- const dynamicSpread = useMemo(
- () => (children?.length ?? 0) * spread,
- [children, spread],
- )
-
- return (
- <MotionComponent
- animate={{ backgroundPosition: "0% center" }}
- className={cn(
- "relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent",
- "[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",
- className,
- )}
- initial={{ backgroundPosition: "100% center" }}
- style={
- {
- "--spread": `${dynamicSpread}px`,
- backgroundImage:
- "var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))",
- } as CSSProperties
- }
- transition={{
- repeat: Number.POSITIVE_INFINITY,
- duration,
- ease: "linear",
- }}
- >
- {children}
- </MotionComponent>
- )
-}
-
-export const Shimmer = memo(ShimmerComponent)
diff --git a/src/workspaces/cad/chat/reset-warning-modal.tsx b/src/workspaces/cad/chat/reset-warning-modal.tsx
deleted file mode 100644
index 529c276..0000000
--- a/src/workspaces/cad/chat/reset-warning-modal.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import React from 'react';
-import { Button } from "@/shared/ui/button"
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/shared/ui/dialog"
-import { t, useUiLanguage } from "@/shared/i18n";
-
-interface ResetWarningModalProps {
- open: boolean
- onOpenChange: (open: boolean) => void
- onClear: () => void
-}
-
-export function ResetWarningModal({
- open,
- onOpenChange,
- onClear,
-}: ResetWarningModalProps) {
- const uiLang = useUiLanguage();
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>{t(uiLang, "reset.title")}</DialogTitle>
- <DialogDescription>
- {t(uiLang, "reset.desc")}
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <Button variant="outline" onClick={() => onOpenChange(false)} title={t(uiLang, "common.cancel")}>
- {t(uiLang, "common.cancel")}
- </Button>
- <Button variant="destructive" onClick={onClear} title={t(uiLang, "common.clear")}>
- {t(uiLang, "common.clear")}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- )
-}
diff --git a/src/workspaces/flow/next/components/ai-elements/reasoning.tsx b/src/workspaces/flow/next/components/ai-elements/reasoning.tsx
deleted file mode 100644
index 11e8af1..0000000
--- a/src/workspaces/flow/next/components/ai-elements/reasoning.tsx
+++ /dev/null
@@ -1,184 +0,0 @@
-"use client"
-
-import { useControllableState } from "@radix-ui/react-use-controllable-state"
-import { BrainIcon, ChevronDownIcon } from "lucide-react"
-import type { ComponentProps, ReactNode } from "react"
-import { createContext, memo, useContext, useEffect, useState } from "react"
-import {
- Collapsible,
- CollapsibleContent,
- CollapsibleTrigger,
-} from "@/shared/ui/collapsible"
-import { cn } from "@/shared/lib/utils"
-import { Shimmer } from "./shimmer"
-
-type ReasoningContextValue = {
- isStreaming: boolean
- isOpen: boolean
- setIsOpen: (open: boolean) => void
- duration: number | undefined
-}
-
-const ReasoningContext = createContext<ReasoningContextValue | null>(null)
-
-export const useReasoning = () => {
- const context = useContext(ReasoningContext)
- if (!context) {
- throw new Error("Reasoning components must be used within Reasoning")
- }
- return context
-}
-
-export type ReasoningProps = ComponentProps<typeof Collapsible> & {
- isStreaming?: boolean
- open?: boolean
- defaultOpen?: boolean
- onOpenChange?: (open: boolean) => void
- duration?: number
-}
-
-const AUTO_CLOSE_DELAY = 1000
-const MS_IN_S = 1000
-
-export const Reasoning = memo(
- ({
- className,
- isStreaming = false,
- open,
- defaultOpen = true,
- onOpenChange,
- duration: durationProp,
- children,
- ...props
- }: ReasoningProps) => {
- const [isOpen, setIsOpen] = useControllableState({
- prop: open,
- defaultProp: defaultOpen,
- onChange: onOpenChange,
- })
- const [duration, setDuration] = useControllableState({
- prop: durationProp,
- defaultProp: undefined,
- })
-
- const [hasAutoClosed, setHasAutoClosed] = useState(false)
- const [startTime, setStartTime] = useState<number | null>(null)
-
- useEffect(() => {
- if (isStreaming) {
- if (startTime === null) {
- setStartTime(Date.now())
- }
- } else if (startTime !== null) {
- setDuration(Math.ceil((Date.now() - startTime) / MS_IN_S))
- setStartTime(null)
- }
- }, [isStreaming, startTime, setDuration])
-
- useEffect(() => {
- if (defaultOpen && !isStreaming && isOpen && !hasAutoClosed) {
- const timer = setTimeout(() => {
- setIsOpen(false)
- setHasAutoClosed(true)
- }, AUTO_CLOSE_DELAY)
-
- return () => clearTimeout(timer)
- }
- }, [isStreaming, isOpen, defaultOpen, setIsOpen, hasAutoClosed])
-
- const handleOpenChange = (newOpen: boolean) => {
- setIsOpen(newOpen)
- }
-
- return (
- <ReasoningContext.Provider
- value={{ isStreaming, isOpen, setIsOpen, duration }}
- >
- <Collapsible
- className={cn("not-prose mb-4", className)}
- onOpenChange={handleOpenChange}
- open={isOpen}
- {...props}
- >
- {children}
- </Collapsible>
- </ReasoningContext.Provider>
- )
- },
-)
-
-export type ReasoningTriggerProps = ComponentProps<
- typeof CollapsibleTrigger
-> & {
- getThinkingMessage?: (isStreaming: boolean, duration?: number) => ReactNode
-}
-
-const defaultGetThinkingMessage = (isStreaming: boolean, duration?: number) => {
- if (isStreaming || duration === 0) {
- return <Shimmer duration={1}>Thinking...</Shimmer>
- }
- if (duration === undefined) {
- return <p>Thought for a few seconds</p>
- }
- return <p>Thought for {duration} seconds</p>
-}
-
-export const ReasoningTrigger = memo(
- ({
- className,
- children,
- getThinkingMessage = defaultGetThinkingMessage,
- ...props
- }: ReasoningTriggerProps) => {
- const { isStreaming, isOpen, duration } = useReasoning()
-
- return (
- <CollapsibleTrigger
- className={cn(
- "flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",
- className,
- )}
- {...props}
- >
- {children ?? (
- <>
- <BrainIcon className="size-4" />
- {getThinkingMessage(isStreaming, duration)}
- <ChevronDownIcon
- className={cn(
- "size-4 transition-transform",
- isOpen ? "rotate-180" : "rotate-0",
- )}
- />
- </>
- )}
- </CollapsibleTrigger>
- )
- },
-)
-
-export type ReasoningContentProps = ComponentProps<
- typeof CollapsibleContent
-> & {
- children: string
-}
-
-export const ReasoningContent = memo(
- ({ className, children, ...props }: ReasoningContentProps) => (
- <CollapsibleContent
- className={cn(
- "mt-4 text-sm",
- "data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",
- className,
- )}
- {...props}
- >
- <div className="whitespace-pre-wrap">{children}</div>
- </CollapsibleContent>
- ),
-)
-
-Reasoning.displayName = "Reasoning"
-ReasoningTrigger.displayName = "ReasoningTrigger"
-ReasoningContent.displayName = "ReasoningContent"
-
diff --git a/src/workspaces/flow/next/components/chat-input.tsx b/src/workspaces/flow/next/components/chat-input.tsx
index 6bf0cd1..1be1ac8 100644
--- a/src/workspaces/flow/next/components/chat-input.tsx
+++ b/src/workspaces/flow/next/components/chat-input.tsx
@@ -13,16 +13,17 @@ import {
import type React from "react"
import { useCallback, useEffect, useRef, useState } from "react"
import { toast } from "sonner"
-import { ButtonWithTooltip } from "@/workspaces/flow/next/components/button-with-tooltip"
+import { ButtonWithTooltip } from "@/shared/chat"
import { ErrorToast } from "@/workspaces/flow/next/components/error-toast"
-import { GlobalConstraintsDialog } from "@/workspaces/flow/next/components/global-constraints-dialog"
+import { GlobalConstraintsDialog } from "@/shared/chat"
+import { FLOW_GLOBAL_CONSTRAINTS_KEY } from "@/workspaces/flow/next/lib/flow-storage-keys"
import { HistoryDialog } from "@/workspaces/flow/next/components/history-dialog"
-import { ResetWarningModal } from "@/workspaces/flow/next/components/reset-warning-modal"
+import { ResetWarningModal } from "@/shared/chat"
import { Textarea } from "@/shared/ui/textarea"
import { useDiagram } from "@/workspaces/flow/next/contexts/diagram-context"
import { useFlowT } from "@/workspaces/flow/next/lib/translations"
import { isPdfFile, isTextFile } from "@/shared/files"
-import { FilePreviewList } from "./file-preview-list"
+import { FilePreviewList } from "@/shared/chat"
const MAX_IMAGE_SIZE = 2 * 1024 * 1024 // 2MB
const MAX_FILES = 5
@@ -396,11 +397,19 @@ export function ChatInput({
open={showClearDialog}
onOpenChange={setShowClearDialog}
onClear={handleClear}
+ labels={{
+ title: t("reset.title"),
+ description: t("reset.desc"),
+ cancel: t("reset.cancel"),
+ confirm: t("reset.confirm"),
+ }}
/>
<GlobalConstraintsDialog
open={showConstraintsDialog}
onOpenChange={setShowConstraintsDialog}
+ workspaceId="flow"
+ storageKey={FLOW_GLOBAL_CONSTRAINTS_KEY}
/>
<HistoryDialog
diff --git a/src/workspaces/flow/next/components/chat-message-display.tsx b/src/workspaces/flow/next/components/chat-message-display.tsx
index be5c74a..d554cd5 100644
--- a/src/workspaces/flow/next/components/chat-message-display.tsx
+++ b/src/workspaces/flow/next/components/chat-message-display.tsx
@@ -24,7 +24,7 @@ import {
Reasoning,
ReasoningContent,
ReasoningTrigger,
-} from "@/workspaces/flow/next/components/ai-elements/reasoning"
+} from "@/shared/chat"
import { ScrollArea } from "@/shared/ui/scroll-area"
import { useFlowT } from "@/workspaces/flow/next/lib/translations"
import {
diff --git a/src/workspaces/flow/next/components/chat-panel.tsx b/src/workspaces/flow/next/components/chat-panel.tsx
index 18119e9..10537b7 100644
--- a/src/workspaces/flow/next/components/chat-panel.tsx
+++ b/src/workspaces/flow/next/components/chat-panel.tsx
@@ -8,9 +8,9 @@ import {
import type React from "react"
import { useCallback, useEffect, useRef, useState } from "react"
import { Toaster, toast } from "sonner"
-import { ButtonWithTooltip } from "@/workspaces/flow/next/components/button-with-tooltip"
+import { ButtonWithTooltip } from "@/shared/chat"
import { ChatInput } from "@/workspaces/flow/next/components/chat-input"
-import { STORAGE_GLOBAL_CONSTRAINTS_KEY } from "@/workspaces/flow/next/components/global-constraints-dialog"
+import { FLOW_GLOBAL_CONSTRAINTS_KEY } from "@/workspaces/flow/next/lib/flow-storage-keys"
import { useDiagram } from "@/workspaces/flow/next/contexts/diagram-context"
import { useFlowT } from "@/workspaces/flow/next/lib/translations"
import { getAIConfig } from "@/workspaces/flow/next/lib/ai-config"
@@ -975,7 +975,7 @@ Please fix the XML issues. Ensure cell_id values exist in the current XML and th
const { accessCode, ai } = getAIConfig()
const modelToUse = String(ai.textModel || defaultModel || "").trim()
const imageModelToUse = String(ai.imageModel || "").trim()
- const globalConstraints = localStorage.getItem(STORAGE_GLOBAL_CONSTRAINTS_KEY) || ""
+ const globalConstraints = localStorage.getItem(FLOW_GLOBAL_CONSTRAINTS_KEY) || ""
// Safe parts access
const safeParts = Array.isArray(parts) ? parts : []
diff --git a/src/workspaces/flow/next/components/file-preview-list.tsx b/src/workspaces/flow/next/components/file-preview-list.tsx
deleted file mode 100644
index b07987c..0000000
--- a/src/workspaces/flow/next/components/file-preview-list.tsx
+++ /dev/null
@@ -1,188 +0,0 @@
-"use client"
-
-import { FileCode, FileText, Loader2, X } from "lucide-react"
-import Image from "@/workspaces/flow/next/shims/next-image"
-import { useEffect, useRef, useState } from "react"
-import { isPdfFile, isTextFile } from "@/shared/files"
-
-function formatCharCount(count: number): string {
- if (count >= 1000) {
- return `${(count / 1000).toFixed(1)}k`
- }
- return String(count)
-}
-
-interface FilePreviewListProps {
- files: File[]
- onRemoveFile: (fileToRemove: File) => void
- pdfData?: Map<
- File,
- { text: string; charCount: number; isExtracting: boolean }
- >
-}
-
-export function FilePreviewList({
- files,
- onRemoveFile,
- pdfData = new Map(),
-}: FilePreviewListProps) {
- const [selectedImage, setSelectedImage] = useState<string | null>(null)
- const [imageUrls, setImageUrls] = useState<Map<File, string>>(new Map())
- const imageUrlsRef = useRef<Map<File, string>>(new Map())
-
- // Create and cleanup object URLs when files change
- useEffect(() => {
- const currentUrls = imageUrlsRef.current
- const newUrls = new Map<File, string>()
-
- files.forEach((file) => {
- if (file.type.startsWith("image/")) {
- // Reuse existing URL if file is already tracked
- const existingUrl = currentUrls.get(file)
- if (existingUrl) {
- newUrls.set(file, existingUrl)
- } else {
- newUrls.set(file, URL.createObjectURL(file))
- }
- }
- })
-
- // Revoke URLs for files that are no longer in the list
- currentUrls.forEach((url, file) => {
- if (!newUrls.has(file)) {
- URL.revokeObjectURL(url)
- }
- })
-
- imageUrlsRef.current = newUrls
- setImageUrls(newUrls)
- }, [files])
-
- // Cleanup all URLs on unmount only
- useEffect(() => {
- return () => {
- imageUrlsRef.current.forEach((url) => {
- URL.revokeObjectURL(url)
- })
- // Clear the ref so StrictMode remount creates fresh URLs
- imageUrlsRef.current = new Map()
- }
- }, [])
-
- // Clear selected image if its URL was revoked
- useEffect(() => {
- if (
- selectedImage &&
- !Array.from(imageUrls.values()).includes(selectedImage)
- ) {
- setSelectedImage(null)
- }
- }, [imageUrls, selectedImage])
-
- 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) => {
- const imageUrl = imageUrls.get(file) || null
- const pdfInfo = pdfData.get(file)
- return (
- <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/") && imageUrl
- ? "cursor-pointer"
- : ""
- }`}
- onClick={() =>
- file.type.startsWith("image/") &&
- imageUrl &&
- setSelectedImage(imageUrl)
- }
- >
- {file.type.startsWith("image/") && imageUrl ? (
- <Image
- src={imageUrl}
- alt={file.name}
- width={80}
- height={80}
- className="object-cover w-full h-full"
- unoptimized
- />
- ) : 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>
- <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>
-
- {/* Image Modal/Lightbox */}
- {selectedImage && (
- <div
- className="fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4"
- onClick={() => setSelectedImage(null)}
- >
- <button
- className="absolute top-4 right-4 z-10 bg-white rounded-full p-2 hover:bg-gray-200 transition-colors"
- onClick={() => setSelectedImage(null)}
- aria-label="Close"
- >
- <X className="h-6 w-6" />
- </button>
- <div className="relative w-auto h-auto max-w-[90vw] max-h-[90vh]">
- <Image
- src={selectedImage}
- alt="Full size preview of uploaded diagram or image"
- width={1200}
- height={900}
- className="object-contain max-w-full max-h-[90vh] w-auto h-auto"
- onClick={(e) => e.stopPropagation()}
- unoptimized
- />
- </div>
- </div>
- )}
- </>
- )
-}
-
diff --git a/src/workspaces/flow/next/components/global-constraints-dialog.tsx b/src/workspaces/flow/next/components/global-constraints-dialog.tsx
deleted file mode 100644
index 7d6dc8e..0000000
--- a/src/workspaces/flow/next/components/global-constraints-dialog.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-"use client"
-
-import { useEffect, useState } from "react"
-import { toast } from "sonner"
-import { Button } from "@/shared/ui/button"
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/shared/ui/dialog"
-import { Textarea } from "@/shared/ui/textarea"
-import { useFlowT } from "@/workspaces/flow/next/lib/translations"
-
-export const STORAGE_GLOBAL_CONSTRAINTS_KEY = "next-ai-draw-io-global-constraints"
-
-interface GlobalConstraintsDialogProps {
- open: boolean
- onOpenChange: (open: boolean) => void
-}
-
-export function GlobalConstraintsDialog({
- open,
- onOpenChange,
-}: GlobalConstraintsDialogProps) {
- const t = useFlowT()
- const [constraints, setConstraints] = useState("")
-
- useEffect(() => {
- if (open) {
- const saved = localStorage.getItem(STORAGE_GLOBAL_CONSTRAINTS_KEY) || ""
- setConstraints(saved)
- }
- }, [open])
-
- const handleSave = () => {
- localStorage.setItem(STORAGE_GLOBAL_CONSTRAINTS_KEY, constraints)
- toast.success(t("common.saved"), {
- position: "top-center",
- duration: 2000,
- })
- onOpenChange(false)
- }
-
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-[500px]">
- <DialogHeader>
- <DialogTitle>{t("global_constraints.title")}</DialogTitle>
- <DialogDescription>
- {t("global_constraints.description")}
- </DialogDescription>
- </DialogHeader>
- <div className="grid gap-4 py-4">
- <Textarea
- value={constraints}
- onChange={(e) => setConstraints(e.target.value)}
- placeholder={t("global_constraints.placeholder")}
- className="min-h-[200px]"
- />
- </div>
- <DialogFooter>
- <Button onClick={handleSave}>
- {t("common.save")}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- )
-}
-
diff --git a/src/workspaces/flow/next/components/reset-warning-modal.tsx b/src/workspaces/flow/next/components/reset-warning-modal.tsx
deleted file mode 100644
index bc4b388..0000000
--- a/src/workspaces/flow/next/components/reset-warning-modal.tsx
+++ /dev/null
@@ -1,51 +0,0 @@
-"use client"
-
-import { Button } from "@/shared/ui/button"
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/shared/ui/dialog"
-import { useFlowT } from "@/workspaces/flow/next/lib/translations"
-
-interface ResetWarningModalProps {
- open: boolean
- onOpenChange: (open: boolean) => void
- onClear: () => void
-}
-
-export function ResetWarningModal({
- open,
- onOpenChange,
- onClear,
-}: ResetWarningModalProps) {
- const t = useFlowT()
-
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>{t("reset.title")}</DialogTitle>
- <DialogDescription>
- {t("reset.desc")}
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <Button
- variant="outline"
- onClick={() => onOpenChange(false)}
- >
- {t("reset.cancel")}
- </Button>
- <Button variant="destructive" onClick={onClear}>
- {t("reset.confirm")}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- )
-}
-
diff --git a/src/workspaces/flow/next/lib/flow-storage-keys.ts b/src/workspaces/flow/next/lib/flow-storage-keys.ts
new file mode 100644
index 0000000..69225b4
--- /dev/null
+++ b/src/workspaces/flow/next/lib/flow-storage-keys.ts
@@ -0,0 +1,5 @@
+/**
+ * localStorage keys the Flow workspace shipped with. They keep their original
+ * names so existing users do not silently lose what they saved.
+ */
+export const FLOW_GLOBAL_CONSTRAINTS_KEY = "next-ai-draw-io-global-constraints"
diff --git a/src/workspaces/ppt/PptWorkspaceShell.tsx b/src/workspaces/ppt/PptWorkspaceShell.tsx
index 3cd0d87..4df6b6b 100644
--- a/src/workspaces/ppt/PptWorkspaceShell.tsx
+++ b/src/workspaces/ppt/PptWorkspaceShell.tsx
@@ -15,7 +15,7 @@ import { PPT_STATE_KEY, pptStore } from "@/workspaces/ppt/storage";
import type { ChatMessage } from "@/ai/client";
import { PptWorkspace } from "@/workspaces/ppt/workspace/PptWorkspace";
import { ChatPanel as PptChatPanel } from "@/workspaces/ppt/chat/ChatPanel";
-import type { HistoryItem } from "@/workspaces/ppt/chat/history-dialog";
+import type { HistoryItem } from "@/shared/chat";
type Attachment = {
id: string;
diff --git a/src/workspaces/ppt/chat/ChatMessageDisplay.tsx b/src/workspaces/ppt/chat/ChatMessageDisplay.tsx
index 5022d38..2846ae6 100644
--- a/src/workspaces/ppt/chat/ChatMessageDisplay.tsx
+++ b/src/workspaces/ppt/chat/ChatMessageDisplay.tsx
@@ -17,7 +17,7 @@ import {
} from "lucide-react";
import ReactMarkdown from "react-markdown";
import remarkGfm from 'remark-gfm';
-import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/workspaces/ppt/chat/components/reasoning";
+import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/shared/chat";
import { ScrollArea } from "@/shared/ui/scroll-area";
import { CodeBlock } from "@/workspaces/ppt/chat/code-block";
import { useUiLanguage } from "@/shared/i18n";
diff --git a/src/workspaces/ppt/chat/ChatPanel.tsx b/src/workspaces/ppt/chat/ChatPanel.tsx
index 3191183..4df893a 100644
--- a/src/workspaces/ppt/chat/ChatPanel.tsx
+++ b/src/workspaces/ppt/chat/ChatPanel.tsx
@@ -3,12 +3,12 @@ import { PanelRightClose, PanelRightOpen } from 'lucide-react';
import { cn } from '@/shared/lib/utils';
import { streamChatMessage, generateChatMessage, generatePptProxyChatMessage, ChatMessage, getAIConfig } from '@/ai/client';
import { DRAWIO_SYSTEM_PROMPT } from '@/lib/system-prompts';
-import { ButtonWithTooltip } from '@/workspaces/ppt/chat/components/button-with-tooltip';
-import { ChatInput } from '@/workspaces/ppt/chat/ChatInput';
+import { ButtonWithTooltip } from '@/shared/chat';
+import { ChatInput } from '@/shared/chat';
import { ChatMessageDisplay, UIMessage } from '@/workspaces/ppt/chat/ChatMessageDisplay';
-import { STORAGE_GLOBAL_CONSTRAINTS_KEY } from '@/workspaces/ppt/chat/global-constraints-dialog';
-import { HistoryDialog, HistoryItem } from '@/workspaces/ppt/chat/history-dialog';
-import { ResetWarningModal } from '@/workspaces/ppt/chat/reset-warning-modal';
+import { STORAGE_GLOBAL_CONSTRAINTS_KEY } from '@/shared/chat';
+import { HistoryDialog, HistoryItem } from '@/shared/chat';
+import { ResetWarningModal } from '@/shared/chat';
import { useFileProcessor } from '@/shared/files/use-file-processor';
import { buildCadBomMessages, buildCadImagesMasterMessages, buildCadImagesSheetMessages, buildCadTasksSystemContent } from '@/lib/cad-tasks';
import { CAD_PLAN_AGENT_PROMPT } from '@/lib/cad-agents';
@@ -1683,6 +1683,7 @@ export function ChatPanel({
{/* Input */}
<div className="p-4 border-t border-border/50 bg-card/50">
<ChatInput
+ workspaceId={workspaceId === "cad" || workspaceId === "ppt" ? workspaceId : "unknown"}
input={input}
setInput={setInput}
onSubmit={handleSend}
diff --git a/src/workspaces/ppt/chat/components/button-with-tooltip.tsx b/src/workspaces/ppt/chat/components/button-with-tooltip.tsx
deleted file mode 100644
index d99cf2c..0000000
--- a/src/workspaces/ppt/chat/components/button-with-tooltip.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import type { VariantProps } from "class-variance-authority"
-import type React from "react"
-import { Button, type buttonVariants } from "@/shared/ui/button"
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@/shared/ui/tooltip"
-
-interface ButtonWithTooltipProps
- extends React.ComponentProps<"button">,
- VariantProps<typeof buttonVariants> {
- tooltipContent: string
- children: React.ReactNode
- asChild?: boolean
-}
-
-export function ButtonWithTooltip({
- tooltipContent,
- children,
- ...buttonProps
-}: ButtonWithTooltipProps) {
- return (
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button {...buttonProps}>{children}</Button>
- </TooltipTrigger>
- <TooltipContent className="max-w-xs text-wrap">
- {tooltipContent}
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- )
-}
diff --git a/src/workspaces/ppt/chat/components/reasoning.tsx b/src/workspaces/ppt/chat/components/reasoning.tsx
deleted file mode 100644
index 27be22c..0000000
--- a/src/workspaces/ppt/chat/components/reasoning.tsx
+++ /dev/null
@@ -1,181 +0,0 @@
-import { useControllableState } from "@radix-ui/react-use-controllable-state"
-import { BrainIcon, ChevronDownIcon } from "lucide-react"
-import type { ComponentProps, ReactNode } from "react"
-import { createContext, memo, useContext, useEffect, useState } from "react"
-import {
- Collapsible,
- CollapsibleContent,
- CollapsibleTrigger,
-} from "@/shared/ui/collapsible"
-import { cn } from "@/shared/lib/utils"
-import { Shimmer } from "./shimmer"
-
-type ReasoningContextValue = {
- isStreaming: boolean
- isOpen: boolean
- setIsOpen: (open: boolean) => void
- duration: number | undefined
-}
-
-const ReasoningContext = createContext<ReasoningContextValue | null>(null)
-
-export const useReasoning = () => {
- const context = useContext(ReasoningContext)
- if (!context) {
- throw new Error("Reasoning components must be used within Reasoning")
- }
- return context
-}
-
-export type ReasoningProps = ComponentProps<typeof Collapsible> & {
- isStreaming?: boolean
- open?: boolean
- defaultOpen?: boolean
- onOpenChange?: (open: boolean) => void
- duration?: number
-}
-
-const AUTO_CLOSE_DELAY = 1000
-const MS_IN_S = 1000
-
-export const Reasoning = memo(
- ({
- className,
- isStreaming = false,
- open,
- defaultOpen = true,
- onOpenChange,
- duration: durationProp,
- children,
- ...props
- }: ReasoningProps) => {
- const [isOpen, setIsOpen] = useControllableState({
- prop: open,
- defaultProp: defaultOpen,
- onChange: onOpenChange,
- })
- const [duration, setDuration] = useControllableState({
- prop: durationProp,
- defaultProp: undefined,
- })
-
- const [hasAutoClosed, setHasAutoClosed] = useState(false)
- const [startTime, setStartTime] = useState<number | null>(null)
-
- useEffect(() => {
- if (isStreaming) {
- if (startTime === null) {
- setStartTime(Date.now())
- }
- } else if (startTime !== null) {
- setDuration(Math.ceil((Date.now() - startTime) / MS_IN_S))
- setStartTime(null)
- }
- }, [isStreaming, startTime, setDuration])
-
- useEffect(() => {
- if (defaultOpen && !isStreaming && isOpen && !hasAutoClosed) {
- const timer = setTimeout(() => {
- setIsOpen(false)
- setHasAutoClosed(true)
- }, AUTO_CLOSE_DELAY)
-
- return () => clearTimeout(timer)
- }
- }, [isStreaming, isOpen, defaultOpen, setIsOpen, hasAutoClosed])
-
- const handleOpenChange = (newOpen: boolean) => {
- setIsOpen(newOpen)
- }
-
- return (
- <ReasoningContext.Provider
- value={{ isStreaming, isOpen, setIsOpen, duration }}
- >
- <Collapsible
- className={cn("not-prose mb-4", className)}
- onOpenChange={handleOpenChange}
- open={isOpen}
- {...props}
- >
- {children}
- </Collapsible>
- </ReasoningContext.Provider>
- )
- },
-)
-
-export type ReasoningTriggerProps = ComponentProps<
- typeof CollapsibleTrigger
-> & {
- getThinkingMessage?: (isStreaming: boolean, duration?: number) => ReactNode
-}
-
-const defaultGetThinkingMessage = (isStreaming: boolean, duration?: number) => {
- if (isStreaming || duration === 0) {
- return <Shimmer duration={1}>Thinking...</Shimmer>
- }
- if (duration === undefined) {
- return <p>Thought for a few seconds</p>
- }
- return <p>Thought for {duration} seconds</p>
-}
-
-export const ReasoningTrigger = memo(
- ({
- className,
- children,
- getThinkingMessage = defaultGetThinkingMessage,
- ...props
- }: ReasoningTriggerProps) => {
- const { isStreaming, isOpen, duration } = useReasoning()
-
- return (
- <CollapsibleTrigger
- className={cn(
- "flex w-full items-center gap-2 text-muted-foreground text-sm transition-colors hover:text-foreground",
- className,
- )}
- {...props}
- >
- {children ?? (
- <>
- <BrainIcon className="size-4" />
- {getThinkingMessage(isStreaming, duration)}
- <ChevronDownIcon
- className={cn(
- "size-4 transition-transform",
- isOpen ? "rotate-180" : "rotate-0",
- )}
- />
- </>
- )}
- </CollapsibleTrigger>
- )
- },
-)
-
-export type ReasoningContentProps = ComponentProps<
- typeof CollapsibleContent
-> & {
- children: string
-}
-
-export const ReasoningContent = memo(
- ({ className, children, ...props }: ReasoningContentProps) => (
- <CollapsibleContent
- className={cn(
- "mt-4 text-sm",
- "data-[state=closed]:fade-out-0 data-[state=closed]:slide-out-to-top-2 data-[state=open]:slide-in-from-top-2 text-muted-foreground outline-none data-[state=closed]:animate-out data-[state=open]:animate-in",
- className,
- )}
- {...props}
- >
- <div className="whitespace-pre-wrap">{children}</div>
- </CollapsibleContent>
- ),
-)
-
-Reasoning.displayName = "Reasoning"
-ReasoningTrigger.displayName = "ReasoningTrigger"
-ReasoningContent.displayName = "ReasoningContent"
diff --git a/src/workspaces/ppt/chat/components/shimmer.tsx b/src/workspaces/ppt/chat/components/shimmer.tsx
deleted file mode 100644
index 8651161..0000000
--- a/src/workspaces/ppt/chat/components/shimmer.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-import { motion } from "framer-motion"
-import {
- type CSSProperties,
- type ElementType,
- type JSX,
- memo,
- useMemo,
-} from "react"
-import { cn } from "@/shared/lib/utils"
-
-export type TextShimmerProps = {
- children: string
- as?: ElementType
- className?: string
- duration?: number
- spread?: number
-}
-
-const ShimmerComponent = ({
- children,
- as: Component = "p",
- className,
- duration = 2,
- spread = 2,
-}: TextShimmerProps) => {
- const MotionComponent = motion.create(
- Component as keyof JSX.IntrinsicElements,
- )
-
- const dynamicSpread = useMemo(
- () => (children?.length ?? 0) * spread,
- [children, spread],
- )
-
- return (
- <MotionComponent
- animate={{ backgroundPosition: "0% center" }}
- className={cn(
- "relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent",
- "[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",
- className,
- )}
- initial={{ backgroundPosition: "100% center" }}
- style={
- {
- "--spread": `${dynamicSpread}px`,
- backgroundImage:
- "var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))",
- } as CSSProperties
- }
- transition={{
- repeat: Number.POSITIVE_INFINITY,
- duration,
- ease: "linear",
- }}
- >
- {children}
- </MotionComponent>
- )
-}
-
-export const Shimmer = memo(ShimmerComponent)
diff --git a/src/workspaces/ppt/chat/file-preview-list.tsx b/src/workspaces/ppt/chat/file-preview-list.tsx
deleted file mode 100644
index b437992..0000000
--- a/src/workspaces/ppt/chat/file-preview-list.tsx
+++ /dev/null
@@ -1,179 +0,0 @@
-"use client"
-
-import { FileCode, FileText, Loader2, X } from "lucide-react"
-import { useEffect, useRef, useState } from "react"
-import { isPdfFile, isTextFile } from "@/shared/files"
-import { type FileData } from "@/shared/files/use-file-processor"
-
-function formatCharCount(count: number): string {
- if (count >= 1000) {
- return `${(count / 1000).toFixed(1)}k`
- }
- return String(count)
-}
-
-interface FilePreviewListProps {
- files: File[]
- onRemoveFile: (fileToRemove: File) => void
- pdfData?: Map<File, FileData>
-}
-
-export function FilePreviewList({
- files,
- onRemoveFile,
- pdfData = new Map(),
-}: FilePreviewListProps) {
- const [selectedImage, setSelectedImage] = useState<string | null>(null)
- const [imageUrls, setImageUrls] = useState<Map<File, string>>(new Map())
- const imageUrlsRef = useRef<Map<File, string>>(new Map())
-
- // Create and cleanup object URLs when files change
- useEffect(() => {
- const currentUrls = imageUrlsRef.current
- const newUrls = new Map<File, string>()
-
- files.forEach((file) => {
- if (file.type.startsWith("image/")) {
- // Reuse existing URL if file is already tracked
- const existingUrl = currentUrls.get(file)
- if (existingUrl) {
- newUrls.set(file, existingUrl)
- } else {
- newUrls.set(file, URL.createObjectURL(file))
- }
- }
- })
-
- // Revoke URLs for files that are no longer in the list
- currentUrls.forEach((url, file) => {
- if (!newUrls.has(file)) {
- URL.revokeObjectURL(url)
- }
- })
-
- imageUrlsRef.current = newUrls
- setImageUrls(newUrls)
- }, [files])
-
- // Cleanup all URLs on unmount only
- useEffect(() => {
- return () => {
- imageUrlsRef.current.forEach((url) => {
- URL.revokeObjectURL(url)
- })
- // Clear the ref so StrictMode remount creates fresh URLs
- imageUrlsRef.current = new Map()
- }
- }, [])
-
- // Clear selected image if its URL was revoked
- useEffect(() => {
- if (
- selectedImage &&
- !Array.from(imageUrls.values()).includes(selectedImage)
- ) {
- setSelectedImage(null)
- }
- }, [imageUrls, selectedImage])
-
- 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) => {
- const imageUrl = imageUrls.get(file) || null
- const 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="group">
- <div
- className="flex items-center gap-2.5 w-[260px] max-w-full border rounded-lg overflow-hidden bg-background/70 px-3 py-2"
- >
- <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>
- </div>
- )
- })}
- </div>
-
- {/* Image Modal/Lightbox */}
- {selectedImage && (
- <div
- className="fixed inset-0 z-50 bg-black/80 flex items-center justify-center p-4"
- onClick={() => setSelectedImage(null)}
- >
- <button
- className="absolute top-4 right-4 z-10 bg-white rounded-full p-2 hover:bg-gray-200 transition-colors"
- onClick={() => setSelectedImage(null)}
- aria-label="Close"
- >
- <X className="h-6 w-6" />
- </button>
- <div className="relative w-auto h-auto max-w-[90vw] max-h-[90vh]">
- <img
- src={selectedImage}
- alt="Full size preview of uploaded diagram or image"
- className="object-contain max-w-full max-h-[90vh] w-auto h-auto"
- onClick={(e) => e.stopPropagation()}
- />
- </div>
- </div>
- )}
- </>
- )
-}
diff --git a/src/workspaces/ppt/chat/global-constraints-dialog.tsx b/src/workspaces/ppt/chat/global-constraints-dialog.tsx
deleted file mode 100644
index 0312bd4..0000000
--- a/src/workspaces/ppt/chat/global-constraints-dialog.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-import { useEffect, useState } from "react"
-import { Button } from "@/shared/ui/button"
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/shared/ui/dialog"
-import { Textarea } from "@/shared/ui/textarea"
-import { t, useUiLanguage } from "@/shared/i18n";
-
-export const STORAGE_GLOBAL_CONSTRAINTS_KEY = "CanvasAnvil-global-constraints"
-
-interface GlobalConstraintsDialogProps {
- open: boolean
- onOpenChange: (open: boolean) => void
- workspaceId?: string // Optional workspace ID to scope constraints
-}
-
-export function GlobalConstraintsDialog({
- open,
- onOpenChange,
- workspaceId
-}: GlobalConstraintsDialogProps) {
- const [constraints, setConstraints] = useState("")
- const uiLang = useUiLanguage();
- const workspaceLabel =
- workspaceId === "flow"
- ? "Flow"
- : workspaceId === "cad"
- ? "CAD"
- : workspaceId === "ppt"
- ? "PPT"
- : "General"
-
- // Determine the actual storage key
- const storageKey = workspaceId
- ? `${STORAGE_GLOBAL_CONSTRAINTS_KEY}-${workspaceId}`
- : STORAGE_GLOBAL_CONSTRAINTS_KEY;
-
- useEffect(() => {
- if (open) {
- const saved = localStorage.getItem(storageKey) || ""
- setConstraints(saved)
- }
- }, [open, storageKey])
-
- const handleSave = () => {
- localStorage.setItem(storageKey, constraints)
- onOpenChange(false)
- }
-
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent className="sm:max-w-[500px]">
- <DialogHeader>
- <DialogTitle>
- {t(uiLang, "constraints.title")} ({workspaceLabel})
- </DialogTitle>
- <DialogDescription>
- {t(uiLang, "constraints.desc")}
- </DialogDescription>
- </DialogHeader>
- <div className="grid gap-4 py-4">
- <Textarea
- value={constraints}
- onChange={(e) => setConstraints(e.target.value)}
- placeholder={t(uiLang, "constraints.placeholder")}
- className="min-h-[200px]"
- />
- </div>
- <DialogFooter>
- <Button onClick={handleSave}>
- {t(uiLang, "common.save")}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- )
-}
-
diff --git a/src/workspaces/ppt/chat/history-dialog.tsx b/src/workspaces/ppt/chat/history-dialog.tsx
deleted file mode 100644
index e03c94a..0000000
--- a/src/workspaces/ppt/chat/history-dialog.tsx
+++ /dev/null
@@ -1,111 +0,0 @@
-import React from 'react';
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
-} from "@/shared/ui/dialog"
-import { Button } from '@/shared/ui/button';
-import { Clock, RotateCcw, FileCode, Trash2 } from 'lucide-react';
-import { ScrollArea } from '@/shared/ui/scroll-area';
-import { t, useUiLanguage } from "@/shared/i18n";
-
-export interface HistoryItem {
- id: string;
- timestamp: number;
- content: string; // XML or code
- type: 'xml' | 'python' | 'json' | 'svg';
- summary?: string;
-}
-
-interface HistoryDialogProps {
- showHistory: boolean;
- onToggleHistory: (show: boolean) => void;
- history: HistoryItem[];
- onRestore: (item: HistoryItem) => void;
- onClear?: () => void;
-}
-
-export function HistoryDialog({
- showHistory,
- onToggleHistory,
- history,
- onRestore,
- onClear,
-}: HistoryDialogProps) {
- const uiLang = useUiLanguage();
- const formatDate = (ts: number) => {
- return new Date(ts).toLocaleString();
- };
-
- return (
- <Dialog open={showHistory} onOpenChange={onToggleHistory}>
- <DialogContent className="max-w-md max-h-[80vh] flex flex-col">
- <DialogHeader>
- <div className="flex items-center justify-between gap-3">
- <DialogTitle className="flex items-center gap-2">
- <Clock className="w-5 h-5 text-muted-foreground" />
- {t(uiLang, "history.title")}
- </DialogTitle>
- {history.length > 0 && onClear && (
- <Button
- size="sm"
- variant="ghost"
- onClick={onClear}
- className="gap-1 text-xs"
- >
- <Trash2 className="w-3.5 h-3.5" />
- {t(uiLang, "history.clear")}
- </Button>
- )}
- </div>
- </DialogHeader>
-
- <div className="flex-1 overflow-hidden mt-2">
- {history.length === 0 ? (
- <div className="text-center p-8 text-muted-foreground text-sm flex flex-col items-center gap-2">
- <Clock className="w-8 h-8 opacity-20" />
- <p>{t(uiLang, "history.empty")}</p>
- </div>
- ) : (
- <ScrollArea className="h-[400px] pr-4">
- <div className="space-y-3">
- {[...history].reverse().map((item, index) => (
- <div key={item.id} className="p-3 rounded-lg border border-border/50 bg-muted/20 hover:bg-muted/40 transition-colors flex items-center justify-between group">
- <div className="flex flex-col gap-1 overflow-hidden">
- <div className="flex items-center gap-2 text-sm font-medium">
- <span className="w-6 h-6 rounded-full bg-blue-100 dark:bg-blue-900/30 text-blue-600 flex items-center justify-center text-xs">
- {history.length - index}
- </span>
- <span>{formatDate(item.timestamp)}</span>
- </div>
- <div className="text-xs text-muted-foreground truncate pl-8 flex items-center gap-1">
- <FileCode className="w-3 h-3" />
- <span>{item.type.toUpperCase()}</span>
- <span>•</span>
- <span>{t(uiLang, "history.chars", { n: item.content.length })}</span>
- </div>
- </div>
-
- <Button
- size="sm"
- variant="ghost"
- onClick={() => {
- onRestore(item);
- onToggleHistory(false);
- }}
- className="opacity-0 group-hover:opacity-100 transition-opacity gap-1 text-xs"
- >
- <RotateCcw className="w-3 h-3" />
- {t(uiLang, "history.restore")}
- </Button>
- </div>
- ))}
- </div>
- </ScrollArea>
- )}
- </div>
- </DialogContent>
- </Dialog>
- )
-}
diff --git a/src/workspaces/ppt/chat/reset-warning-modal.tsx b/src/workspaces/ppt/chat/reset-warning-modal.tsx
deleted file mode 100644
index 67dc47b..0000000
--- a/src/workspaces/ppt/chat/reset-warning-modal.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import React from 'react';
-import { Button } from "@/shared/ui/button"
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from "@/shared/ui/dialog"
-import { t, useUiLanguage } from "@/shared/i18n";
-
-interface ResetWarningModalProps {
- open: boolean
- onOpenChange: (open: boolean) => void
- onClear: () => void
-}
-
-export function ResetWarningModal({
- open,
- onOpenChange,
- onClear,
-}: ResetWarningModalProps) {
- const uiLang = useUiLanguage();
- return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>{t(uiLang, "reset.title")}</DialogTitle>
- <DialogDescription>
- {t(uiLang, "reset.desc")}
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <Button variant="outline" onClick={() => onOpenChange(false)}>
- {t(uiLang, "common.cancel")}
- </Button>
- <Button variant="destructive" onClick={onClear}>
- {t(uiLang, "common.clear")}
- </Button>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- )
-}
diff --git a/src/workspaces/ppt/workspace/PptWorkspace.tsx b/src/workspaces/ppt/workspace/PptWorkspace.tsx
index 95f5484..5d856e6 100644
--- a/src/workspaces/ppt/workspace/PptWorkspace.tsx
+++ b/src/workspaces/ppt/workspace/PptWorkspace.tsx
@@ -1,5 +1,5 @@
import React, { useState, useEffect, useLayoutEffect, useRef } from 'react';
-import { motion } from "framer-motion";
+import { motion } from "motion/react";
import { generateImage, generateChatMessage } from '@/ai/client';
import { pptService, PptPage, type PptElement, type PptTextBlock, type SlideEditRoutingItem, resolveTextBlockFontSize, PPT_REFERENCE_SLIDE_HEIGHT, PPT_REFERENCE_SLIDE_WIDTH, textBlocksToPptElements } from '@/lib/ppt-service';
import { getTemplateGenerationPrompt } from '@/lib/ppt-prompts';