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(shared): one UI kit, one storage layer, one file pipeline, one i18n

codingFeng101d9d665778ab4
diff --git a/package.json b/package.json
index e471442..ea7caa7 100644
--- a/package.json
+++ b/package.json
@@ -35,6 +35,7 @@
"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",
"motion": "^12.28.1",
diff --git a/src/App.tsx b/src/App.tsx
index 024db17..15d67ea 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -1,13 +1,11 @@
import React, { useState } from "react";
import { Toaster } from "sonner";
import { FileCode, Layers, Presentation } from "lucide-react";
-import { Button } from "@/components/ui/button";
+import { Button } from "@/shared/ui/button";
import { SettingsDialog } from "@/components/SettingsDialog";
import { LandingPage } from "@/pages/LandingPage";
-import { cn } from "@/lib/utils";
-import { t } from "@/lib/i18n";
-import { getUiLanguage, type UiLanguage } from "@/lib/ui-language";
-import { useUiLanguage } from "@/lib/use-ui-language";
+import { cn } from "@/shared/lib/utils";
+import { getUiLanguage, t, useUiLanguage, type UiLanguage } from "@/shared/i18n";
import { FlowWorkspaceShell } from "@/workspaces/flow/FlowWorkspaceShell";
import { CadWorkspaceShell } from "@/workspaces/cad/CadWorkspaceShell";
import { PptWorkspaceShell } from "@/workspaces/ppt/PptWorkspaceShell";
diff --git a/src/ai/client.ts b/src/ai/client.ts
index 9f885a8..48c718b 100644
--- a/src/ai/client.ts
+++ b/src/ai/client.ts
@@ -1,5 +1,4 @@
-import { t } from "@/lib/i18n";
-import { getUiLanguage } from "@/lib/ui-language";
+import { getUiLanguage, t } from "@/shared/i18n";
import { getAIConfig, getImageChannel, getTextChannel } from "@/ai/config";
import { applyUiLanguagePolicy } from "@/ai/language-policy";
import { createLimiter } from "@/ai/limiter";
diff --git a/src/ai/language-policy.ts b/src/ai/language-policy.ts
index bac7289..876cf42 100644
--- a/src/ai/language-policy.ts
+++ b/src/ai/language-policy.ts
@@ -1,4 +1,4 @@
-import { getUiLanguage } from "@/lib/ui-language";
+import { getUiLanguage } from "@/shared/i18n";
import type { ChatMessage } from "@/ai/types";
/**
diff --git a/src/components/SettingsDialog.tsx b/src/components/SettingsDialog.tsx
index 90ee9b5..d502e68 100644
--- a/src/components/SettingsDialog.tsx
+++ b/src/components/SettingsDialog.tsx
@@ -4,9 +4,8 @@ import { ExternalLink, Eye, EyeOff, Loader2, Save, Settings, X } from "lucide-re
import { toast } from "sonner";
import { getAIConfig, normalizeAIConfig, saveAIConfig } from "@/ai/config";
import type { AIConfig } from "@/ai/types";
-import { Button } from "@/components/ui/button";
-import { getUiLanguage, setUiLanguage, type UiLanguage } from "@/lib/ui-language";
-import { t } from "@/lib/i18n";
+import { Button } from "@/shared/ui/button";
+import { getUiLanguage, setUiLanguage, t, type UiLanguage } from "@/shared/i18n";
/**
* Model settings.
diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsx
deleted file mode 100644
index 0ba4277..0000000
--- a/src/components/ui/button.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-import * as React from "react"
-import { Slot } from "@radix-ui/react-slot"
-import { cva, type VariantProps } from "class-variance-authority"
-
-import { cn } from "@/lib/utils"
-
-const buttonVariants = cva(
- "inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",
- {
- variants: {
- variant: {
- default: "bg-primary text-primary-foreground hover:bg-primary/90",
- destructive:
- "bg-destructive text-destructive-foreground hover:bg-destructive/90",
- outline:
- "border border-input bg-background hover:bg-accent hover:text-accent-foreground",
- secondary:
- "bg-secondary text-secondary-foreground hover:bg-secondary/80",
- ghost: "hover:bg-accent hover:text-accent-foreground",
- link: "text-primary underline-offset-4 hover:underline",
- },
- size: {
- default: "h-10 px-4 py-2",
- sm: "h-9 rounded-md px-3",
- lg: "h-11 rounded-md px-8",
- icon: "h-10 w-10",
- },
- },
- defaultVariants: {
- variant: "default",
- size: "default",
- },
- }
-)
-
-export interface ButtonProps
- extends React.ButtonHTMLAttributes<HTMLButtonElement>,
- VariantProps<typeof buttonVariants> {
- asChild?: boolean
-}
-
-const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
- ({ className, variant, size, asChild = false, ...props }, ref) => {
- const Comp = asChild ? Slot : "button"
- return (
- <Comp
- className={cn(buttonVariants({ variant, size, className }))}
- ref={ref}
- {...props}
- />
- )
- }
-)
-Button.displayName = "Button"
-
-export { Button, buttonVariants }
diff --git a/src/features/ppt-editor/components/PptEditorBridge.tsx b/src/features/ppt-editor/components/PptEditorBridge.tsx
index 0c8f83f..3d7d438 100644
--- a/src/features/ppt-editor/components/PptEditorBridge.tsx
+++ b/src/features/ppt-editor/components/PptEditorBridge.tsx
@@ -1,7 +1,7 @@
import type React from "react";
import { AudioLines, PlayCircle, Sigma } from "lucide-react";
import { PPT_REFERENCE_SLIDE_HEIGHT, PPT_REFERENCE_SLIDE_WIDTH } from "@/lib/ppt-service";
-import { cn } from "@/lib/utils";
+import { cn } from "@/shared/lib/utils";
import { buildEditorShapePath } from "@/features/ppt-editor/shape-config";
import type {
EditorAudioElement,
diff --git a/src/features/ppt-editor/components/PptReviewBridge.tsx b/src/features/ppt-editor/components/PptReviewBridge.tsx
index bb120f3..e699626 100644
--- a/src/features/ppt-editor/components/PptReviewBridge.tsx
+++ b/src/features/ppt-editor/components/PptReviewBridge.tsx
@@ -1,7 +1,7 @@
import type React from "react";
import { FileSearch, FileText, Loader2, Play, Trash2 } from "lucide-react";
-import { Button } from "@/workspaces/ppt/ui/button";
-import { Textarea } from "@/workspaces/ppt/ui/textarea";
+import { Button } from "@/shared/ui/button";
+import { Textarea } from "@/shared/ui/textarea";
import type { PptTextBlock } from "@/lib/ppt-service";
export type ReviewDraftRect = {
diff --git a/src/lib/cad-persistence.ts b/src/lib/cad-persistence.ts
deleted file mode 100644
index 29d1456..0000000
--- a/src/lib/cad-persistence.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-const CAD_DB_NAME = "CanvasAnvilCadWorkspaceDB";
-const CAD_STORE_NAME = "workspace";
-const CAD_DB_VERSION = 1;
-
-function openCadWorkspaceDb(): Promise<IDBDatabase | null> {
- if (typeof indexedDB === "undefined") return Promise.resolve(null);
-
- return new Promise((resolve, reject) => {
- const request = indexedDB.open(CAD_DB_NAME, CAD_DB_VERSION);
-
- request.onupgradeneeded = () => {
- const db = request.result;
- if (!db.objectStoreNames.contains(CAD_STORE_NAME)) {
- db.createObjectStore(CAD_STORE_NAME);
- }
- };
-
- request.onsuccess = () => resolve(request.result);
- request.onerror = () => reject(request.error);
- });
-}
-
-export async function readPersistedCadWorkspaceItem<T = unknown>(key: string): Promise<T | null> {
- const db = await openCadWorkspaceDb();
- if (!db) return null;
-
- return await new Promise<T | null>((resolve, reject) => {
- const tx = db.transaction(CAD_STORE_NAME, "readonly");
- const store = tx.objectStore(CAD_STORE_NAME);
- const request = store.get(key);
-
- request.onsuccess = () => resolve((request.result as T | undefined) ?? null);
- request.onerror = () => reject(request.error);
- tx.oncomplete = () => db.close();
- tx.onabort = () => reject(tx.error);
- tx.onerror = () => reject(tx.error);
- });
-}
-
-export async function savePersistedCadWorkspaceItem<T>(key: string, value: T): Promise<void> {
- const db = await openCadWorkspaceDb();
- if (!db) return;
-
- await new Promise<void>((resolve, reject) => {
- const tx = db.transaction(CAD_STORE_NAME, "readwrite");
- const store = tx.objectStore(CAD_STORE_NAME);
- store.put(value, key);
-
- tx.oncomplete = () => {
- db.close();
- resolve();
- };
- tx.onabort = () => reject(tx.error);
- tx.onerror = () => reject(tx.error);
- });
-}
-
-export async function clearPersistedCadWorkspaceItem(key: string): Promise<void> {
- const db = await openCadWorkspaceDb();
- if (!db) return;
-
- await new Promise<void>((resolve, reject) => {
- const tx = db.transaction(CAD_STORE_NAME, "readwrite");
- const store = tx.objectStore(CAD_STORE_NAME);
- store.delete(key);
-
- tx.oncomplete = () => {
- db.close();
- resolve();
- };
- tx.onabort = () => reject(tx.error);
- tx.onerror = () => reject(tx.error);
- });
-}
diff --git a/src/lib/cad-render-titles.ts b/src/lib/cad-render-titles.ts
index bd0c056..ea48ac1 100644
--- a/src/lib/cad-render-titles.ts
+++ b/src/lib/cad-render-titles.ts
@@ -1,4 +1,4 @@
-import type { UiLanguage } from "@/lib/ui-language";
+import type { UiLanguage } from "@/shared/i18n";
export const CAD_RENDER_SLOT_TITLES = [
{ zh: "装修平面布置图", en: "Renovation Plan Layout" },
diff --git a/src/lib/canvas-persistence.ts b/src/lib/canvas-persistence.ts
deleted file mode 100644
index b22dc4f..0000000
--- a/src/lib/canvas-persistence.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-const CANVAS_DB_NAME = "CanvasAnvilCanvasWorkspaceDB";
-const CANVAS_STORE_NAME = "workspace";
-const CANVAS_DB_VERSION = 1;
-
-function openCanvasWorkspaceDb(): Promise<IDBDatabase | null> {
- if (typeof indexedDB === "undefined") return Promise.resolve(null);
-
- return new Promise((resolve, reject) => {
- const request = indexedDB.open(CANVAS_DB_NAME, CANVAS_DB_VERSION);
-
- request.onupgradeneeded = () => {
- const db = request.result;
- if (!db.objectStoreNames.contains(CANVAS_STORE_NAME)) {
- db.createObjectStore(CANVAS_STORE_NAME);
- }
- };
-
- request.onsuccess = () => resolve(request.result);
- request.onerror = () => reject(request.error);
- });
-}
-
-export async function readPersistedCanvasWorkspaceItem<T = unknown>(key: string): Promise<T | null> {
- const db = await openCanvasWorkspaceDb();
- if (!db) return null;
-
- return await new Promise<T | null>((resolve, reject) => {
- const tx = db.transaction(CANVAS_STORE_NAME, "readonly");
- const store = tx.objectStore(CANVAS_STORE_NAME);
- const request = store.get(key);
-
- request.onsuccess = () => resolve((request.result as T | undefined) ?? null);
- request.onerror = () => reject(request.error);
- tx.oncomplete = () => db.close();
- tx.onabort = () => reject(tx.error);
- tx.onerror = () => reject(tx.error);
- });
-}
-
-export async function savePersistedCanvasWorkspaceItem<T>(key: string, value: T): Promise<void> {
- const db = await openCanvasWorkspaceDb();
- if (!db) return;
-
- await new Promise<void>((resolve, reject) => {
- const tx = db.transaction(CANVAS_STORE_NAME, "readwrite");
- const store = tx.objectStore(CANVAS_STORE_NAME);
- store.put(value, key);
-
- tx.oncomplete = () => {
- db.close();
- resolve();
- };
- tx.onabort = () => reject(tx.error);
- tx.onerror = () => reject(tx.error);
- });
-}
-
-export async function clearPersistedCanvasWorkspaceItem(key: string): Promise<void> {
- const db = await openCanvasWorkspaceDb();
- if (!db) return;
-
- await new Promise<void>((resolve, reject) => {
- const tx = db.transaction(CANVAS_STORE_NAME, "readwrite");
- const store = tx.objectStore(CANVAS_STORE_NAME);
- store.delete(key);
-
- tx.oncomplete = () => {
- db.close();
- resolve();
- };
- tx.onabort = () => reject(tx.error);
- tx.onerror = () => reject(tx.error);
- });
-}
diff --git a/src/lib/pdf-utils.ts b/src/lib/pdf-utils.ts
deleted file mode 100644
index 66e1a23..0000000
--- a/src/lib/pdf-utils.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { extractText, getDocumentProxy } from "unpdf"
-
-// Maximum characters allowed for extracted text (configurable via env)
-const DEFAULT_MAX_EXTRACTED_CHARS = 150000 // 150k chars
-export const MAX_EXTRACTED_CHARS = DEFAULT_MAX_EXTRACTED_CHARS
-
-// Text file extensions we support
-const TEXT_EXTENSIONS = [
- ".txt", ".md", ".markdown", ".json", ".csv", ".xml", ".html", ".css", ".js", ".ts",
- ".jsx", ".tsx", ".py", ".java", ".c", ".cpp", ".h", ".go", ".rs", ".yaml", ".yml",
- ".toml", ".ini", ".log", ".sh", ".bash", ".zsh"
-]
-
-/**
- * Extract text content from a PDF file
- * Uses unpdf library for client-side extraction
- */
-export async function extractPdfText(file: File): Promise<string> {
- const buffer = await file.arrayBuffer()
- const pdf = await getDocumentProxy(new Uint8Array(buffer))
- const { text } = await extractText(pdf, { mergePages: true })
- return text as string
-}
-
-export async function getPdfPageCountFromUrl(url: string): Promise<number> {
- const res = await fetch(url)
- const buffer = await res.arrayBuffer()
- const pdf = await getDocumentProxy(new Uint8Array(buffer))
- return (pdf as any).numPages ?? 0
-}
-
-export async function getPdfDocumentFromUrl(url: string): Promise<any> {
- const res = await fetch(url)
- const buffer = await res.arrayBuffer()
- return await getDocumentProxy(new Uint8Array(buffer))
-}
-
-export async function renderPdfPageToCanvas(opts: { pdf: any; pageNumber: number; canvas: HTMLCanvasElement; targetWidth: number }): Promise<void> {
- const page = await opts.pdf.getPage(opts.pageNumber)
- const viewportAtScale1 = page.getViewport({ scale: 1 })
- const scale = opts.targetWidth / viewportAtScale1.width
- const viewport = page.getViewport({ scale })
-
- const dpr = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1
- opts.canvas.width = Math.floor(viewport.width * dpr)
- opts.canvas.height = Math.floor(viewport.height * dpr)
- opts.canvas.style.width = `${Math.floor(viewport.width)}px`
- opts.canvas.style.height = `${Math.floor(viewport.height)}px`
- const ctx = opts.canvas.getContext("2d")
- if (!ctx) return
- ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
- await page.render({ canvasContext: ctx, viewport }).promise
-}
-
-/**
- * Check if a file is a PDF
- */
-export function isPdfFile(file: File): boolean {
- return file.type === "application/pdf" || file.name.endsWith(".pdf")
-}
-
-/**
- * Check if a file is a text file
- */
-export function isTextFile(file: File): boolean {
- const name = file.name.toLowerCase()
- return (
- file.type.startsWith("text/") ||
- file.type === "application/json" ||
- TEXT_EXTENSIONS.some((ext) => name.endsWith(ext))
- )
-}
-
-/**
- * Extract text content from a text file
- */
-export async function extractTextFileContent(file: File): Promise<string> {
- return await file.text()
-}
diff --git a/src/lib/ppt-persistence.ts b/src/lib/ppt-persistence.ts
deleted file mode 100644
index 3b5f45d..0000000
--- a/src/lib/ppt-persistence.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-const PPT_DB_NAME = "CanvasAnvilPptWorkspaceDB";
-const PPT_STORE_NAME = "workspace";
-const PPT_STATE_KEY = "primary";
-const PPT_TEMPLATE_LIBRARY_KEY = "template-library";
-const PPT_DB_VERSION = 1;
-
-function openPptWorkspaceDb(): Promise<IDBDatabase | null> {
- if (typeof indexedDB === "undefined") return Promise.resolve(null);
-
- return new Promise((resolve, reject) => {
- const request = indexedDB.open(PPT_DB_NAME, PPT_DB_VERSION);
-
- request.onupgradeneeded = () => {
- const db = request.result;
- if (!db.objectStoreNames.contains(PPT_STORE_NAME)) {
- db.createObjectStore(PPT_STORE_NAME);
- }
- };
-
- request.onsuccess = () => resolve(request.result);
- request.onerror = () => reject(request.error);
- });
-}
-
-async function readPersistedPptStateByKey<T = unknown>(key: string): Promise<T | null> {
- const db = await openPptWorkspaceDb();
- if (!db) return null;
-
- return await new Promise<T | null>((resolve, reject) => {
- const tx = db.transaction(PPT_STORE_NAME, "readonly");
- const store = tx.objectStore(PPT_STORE_NAME);
- const request = store.get(key);
-
- request.onsuccess = () => resolve((request.result as T | undefined) ?? null);
- request.onerror = () => reject(request.error);
- tx.oncomplete = () => db.close();
- tx.onabort = () => reject(tx.error);
- tx.onerror = () => reject(tx.error);
- });
-}
-
-async function savePersistedPptStateByKey<T>(key: string, state: T): Promise<void> {
- const db = await openPptWorkspaceDb();
- if (!db) return;
-
- await new Promise<void>((resolve, reject) => {
- const tx = db.transaction(PPT_STORE_NAME, "readwrite");
- const store = tx.objectStore(PPT_STORE_NAME);
- store.put(state, key);
-
- tx.oncomplete = () => {
- db.close();
- resolve();
- };
- tx.onabort = () => reject(tx.error);
- tx.onerror = () => reject(tx.error);
- });
-}
-
-async function clearPersistedPptStateByKey(key: string): Promise<void> {
- const db = await openPptWorkspaceDb();
- if (!db) return;
-
- await new Promise<void>((resolve, reject) => {
- const tx = db.transaction(PPT_STORE_NAME, "readwrite");
- const store = tx.objectStore(PPT_STORE_NAME);
- store.delete(key);
-
- tx.oncomplete = () => {
- db.close();
- resolve();
- };
- tx.onabort = () => reject(tx.error);
- tx.onerror = () => reject(tx.error);
- });
-}
-
-export async function readPersistedPptWorkspaceState<T = unknown>(): Promise<T | null> {
- return await readPersistedPptStateByKey<T>(PPT_STATE_KEY);
-}
-
-export async function savePersistedPptWorkspaceState<T>(state: T): Promise<void> {
- await savePersistedPptStateByKey(PPT_STATE_KEY, state);
-}
-
-export async function clearPersistedPptWorkspaceState(): Promise<void> {
- await clearPersistedPptStateByKey(PPT_STATE_KEY);
-}
-
-export async function readPersistedPptTemplateLibraryState<T = unknown>(): Promise<T | null> {
- return await readPersistedPptStateByKey<T>(PPT_TEMPLATE_LIBRARY_KEY);
-}
-
-export async function savePersistedPptTemplateLibraryState<T>(state: T): Promise<void> {
- await savePersistedPptStateByKey(PPT_TEMPLATE_LIBRARY_KEY, state);
-}
diff --git a/src/lib/use-file-processor.ts b/src/lib/use-file-processor.ts
deleted file mode 100644
index 897f9fb..0000000
--- a/src/lib/use-file-processor.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { useState } from "react"
-import { extractPdfText, extractTextFileContent, isPdfFile, isTextFile, MAX_EXTRACTED_CHARS } from "@/lib/pdf-utils"
-
-export interface FileData {
- text: string
- charCount: number
- isExtracting: boolean
-}
-
-/**
- * Hook for processing file uploads, especially PDFs and text files.
- * Handles text extraction, character limit validation, and cleanup.
- */
-export function useFileProcessor() {
- const [files, setFiles] = useState<File[]>([])
- const [pdfData, setPdfData] = useState<Map<File, FileData>>(new Map())
-
- const handleFileChange = async (newFiles: File[]) => {
- setFiles(newFiles)
-
- // Extract text immediately for new PDF/text files
- for (const file of newFiles) {
- const needsExtraction =
- (isPdfFile(file) || isTextFile(file)) && !pdfData.has(file)
- if (needsExtraction) {
- // Mark as extracting
- setPdfData((prev) => {
- const next = new Map(prev)
- next.set(file, {
- text: "",
- charCount: 0,
- isExtracting: true,
- })
- return next
- })
-
- // Extract text asynchronously
- try {
- let text: string
- if (isPdfFile(file)) {
- text = await extractPdfText(file)
- } else {
- text = await extractTextFileContent(file)
- }
-
- // Check character limit
- if (text.length > MAX_EXTRACTED_CHARS) {
- const limitK = MAX_EXTRACTED_CHARS / 1000
- console.warn(`${file.name}: Content exceeds ${limitK}k character limit`)
- // We could remove it, but let's just keep it truncated or full but warn
- // For simplicity in this demo, we keep it but maybe we should truncate?
- // Let's keep it.
- }
-
- setPdfData((prev) => {
- const next = new Map(prev)
- next.set(file, {
- text,
- charCount: text.length,
- isExtracting: false,
- })
- return next
- })
- } catch (error) {
- console.error("Failed to extract text:", error)
- setPdfData((prev) => {
- const next = new Map(prev)
- next.delete(file)
- return next
- })
- }
- }
- }
-
- // Clean up pdfData for removed files
- setPdfData((prev) => {
- const next = new Map(prev)
- for (const key of prev.keys()) {
- if (!newFiles.includes(key)) {
- next.delete(key)
- }
- }
- return next
- })
- }
-
- return {
- files,
- pdfData,
- handleFileChange,
- setFiles,
- }
-}
diff --git a/src/lib/use-ui-language.ts b/src/lib/use-ui-language.ts
deleted file mode 100644
index 0de5747..0000000
--- a/src/lib/use-ui-language.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { useEffect, useState } from "react";
-import { getUiLanguage, type UiLanguage } from "@/lib/ui-language";
-
-export function useUiLanguage() {
- const [uiLang, setUiLang] = useState<UiLanguage>(() => getUiLanguage());
-
- useEffect(() => {
- const onLang = () => setUiLang(getUiLanguage());
- window.addEventListener("ui-language-changed", onLang as any);
- return () => window.removeEventListener("ui-language-changed", onLang as any);
- }, []);
-
- return uiLang;
-}
-
diff --git a/src/pages/portal/PortalPage.tsx b/src/pages/portal/PortalPage.tsx
index b30def8..38e5856 100644
--- a/src/pages/portal/PortalPage.tsx
+++ b/src/pages/portal/PortalPage.tsx
@@ -20,10 +20,9 @@ import {
Wand2,
X,
} from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { cn } from "@/lib/utils";
-import { getUiLanguage, setUiLanguage, type UiLanguage } from "@/lib/ui-language";
-import { useUiLanguage } from "@/lib/use-ui-language";
+import { Button } from "@/shared/ui/button";
+import { cn } from "@/shared/lib/utils";
+import { getUiLanguage, setUiLanguage, useUiLanguage, type UiLanguage } from "@/shared/i18n";
import { portalCanvasItems, type PortalCanvasItem, type PortalWorkspace } from "./data";
type PortalPageProps = {
diff --git a/src/shared/files/binary.ts b/src/shared/files/binary.ts
new file mode 100644
index 0000000..5ff492f
--- /dev/null
+++ b/src/shared/files/binary.ts
@@ -0,0 +1,66 @@
+import { getDocumentProxy } from "unpdf"
+
+/** Byte-level helpers shared by the archive and visual-asset extractors. */
+
+export const bytesToBase64 = (bytes: Uint8Array) => {
+ let binary = ""
+ const chunk = 0x8000
+ for (let i = 0; i < bytes.length; i += chunk) {
+ binary += String.fromCharCode(...bytes.subarray(i, i + chunk))
+ }
+ return btoa(binary)
+}
+
+export const getMimeByExt = (name: string) => {
+ const n = String(name || "").toLowerCase()
+ if (n.endsWith(".png")) return "image/png"
+ if (n.endsWith(".jpg") || n.endsWith(".jpeg")) return "image/jpeg"
+ if (n.endsWith(".webp")) return "image/webp"
+ if (n.endsWith(".gif")) return "image/gif"
+ if (n.endsWith(".bmp")) return "image/bmp"
+ if (n.endsWith(".svg")) return "image/svg+xml"
+ return "image/png"
+}
+
+export const latexAssetBytesToDataUrl = async (name: string, bytes: Uint8Array) => {
+ const n = String(name || "").toLowerCase()
+ if (n.endsWith(".pdf")) {
+ try {
+ const pdf = await getDocumentProxy(bytes)
+ const page = await (pdf as any).getPage(1)
+ const viewport1 = page.getViewport({ scale: 1 })
+ const scale = 1400 / Math.max(1, viewport1.width)
+ const viewport = page.getViewport({ scale })
+ const canvas = document.createElement("canvas")
+ canvas.width = Math.max(1, Math.floor(viewport.width))
+ canvas.height = Math.max(1, Math.floor(viewport.height))
+ const ctx = canvas.getContext("2d")
+ if (!ctx) return ""
+ await page.render({ canvasContext: ctx, viewport }).promise
+ return canvas.toDataURL("image/png")
+ } catch {
+ return ""
+ }
+ }
+ const mime = getMimeByExt(name)
+ return `data:${mime};base64,${bytesToBase64(bytes)}`
+}
+
+export const decodeXmlText = (raw: string) => {
+ const s = String(raw || "")
+ return s
+ .replace(/&lt;/g, "<")
+ .replace(/&gt;/g, ">")
+ .replace(/&quot;/g, '"')
+ .replace(/&apos;/g, "'")
+ .replace(/&amp;/g, "&")
+ .replace(/&#(\d+);/g, (_, n) => {
+ const code = Number(n)
+ if (!Number.isFinite(code)) return ""
+ try {
+ return String.fromCharCode(code)
+ } catch {
+ return ""
+ }
+ })
+}
diff --git a/src/shared/files/detect.ts b/src/shared/files/detect.ts
new file mode 100644
index 0000000..933b719
--- /dev/null
+++ b/src/shared/files/detect.ts
@@ -0,0 +1,96 @@
+/** File-type detection and the shared extraction size limit. */
+
+// Maximum characters allowed for extracted text (configurable via env)
+const DEFAULT_MAX_EXTRACTED_CHARS = 150000 // 150k chars
+const viteMaxExtractedChars =
+ typeof import.meta !== "undefined" &&
+ import.meta.env &&
+ typeof import.meta.env.VITE_MAX_EXTRACTED_CHARS !== "undefined"
+ ? Number(import.meta.env.VITE_MAX_EXTRACTED_CHARS)
+ : NaN
+export const MAX_EXTRACTED_CHARS =
+ (Number.isFinite(viteMaxExtractedChars) ? viteMaxExtractedChars : NaN) ||
+ DEFAULT_MAX_EXTRACTED_CHARS
+
+// Text file extensions we support
+const TEXT_EXTENSIONS = [
+ ".txt",
+ ".md",
+ ".markdown",
+ ".json",
+ ".csv",
+ ".xml",
+ ".html",
+ ".css",
+ ".js",
+ ".ts",
+ ".jsx",
+ ".tsx",
+ ".py",
+ ".java",
+ ".c",
+ ".cpp",
+ ".h",
+ ".go",
+ ".rs",
+ ".yaml",
+ ".yml",
+ ".toml",
+ ".ini",
+ ".log",
+ ".sh",
+ ".bash",
+ ".zsh",
+ ".tex",
+]
+
+/**
+ * Extract text content from a PDF file
+ * Uses unpdf library for client-side extraction
+
+ */
+export function isPdfFile(file: File): boolean {
+ return file.type === "application/pdf" || file.name.endsWith(".pdf")
+}
+
+/**
+ * Check if a file is a Word document (.docx).
+ */
+export function isWordFile(file: File): boolean {
+ const name = file.name.toLowerCase()
+ return (
+ file.type ===
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
+ name.endsWith(".docx")
+ )
+}
+
+/**
+ * Check if a file is a text file
+ */
+export function isTextFile(file: File): boolean {
+ const name = file.name.toLowerCase()
+ return (
+ file.type.startsWith("text/") ||
+ file.type === "application/json" ||
+ TEXT_EXTENSIONS.some((ext) => name.endsWith(ext))
+ )
+}
+
+export function isZipFile(file: File): boolean {
+ const name = file.name.toLowerCase()
+ const type = String(file.type || "").toLowerCase()
+ if (name.endsWith(".zip")) return true
+ return (
+ type === "application/zip" ||
+ type === "application/x-zip-compressed" ||
+ type === "application/octet-stream"
+ )
+}
+
+export function isTarGzFile(file: File): boolean {
+ const name = file.name.toLowerCase()
+ const type = String(file.type || "").toLowerCase()
+ if (name.endsWith(".tgz") || name.endsWith(".tar.gz")) return true
+ return type === "application/gzip" || type === "application/x-gzip"
+}
diff --git a/src/shared/files/extract-text.ts b/src/shared/files/extract-text.ts
new file mode 100644
index 0000000..c801ec5
--- /dev/null
+++ b/src/shared/files/extract-text.ts
@@ -0,0 +1,22 @@
+import { extractText, getDocumentProxy } from "unpdf"
+import * as mammoth from "mammoth"
+
+/** Plain-text extraction for the formats the chat panels accept directly. */
+
+/** Extracts a PDF's text in the browser via unpdf, with pages merged. */
+export async function extractPdfText(file: File): Promise<string> {
+ const buffer = await file.arrayBuffer()
+ const pdf = await getDocumentProxy(new Uint8Array(buffer))
+ const { text } = await extractText(pdf, { mergePages: true })
+ return text as string
+}
+
+export async function extractTextFileContent(file: File): Promise<string> {
+ return await file.text()
+}
+
+export async function extractWordText(file: File): Promise<string> {
+ const arrayBuffer = await file.arrayBuffer()
+ const result = await mammoth.extractRawText({ arrayBuffer })
+ return String(result.value || "")
+}
diff --git a/src/shared/files/index.ts b/src/shared/files/index.ts
new file mode 100644
index 0000000..7cd1ff5
--- /dev/null
+++ b/src/shared/files/index.ts
@@ -0,0 +1,7 @@
+export * from "@/shared/files/types";
+export * from "@/shared/files/detect";
+export * from "@/shared/files/extract-text";
+export * from "@/shared/files/pdf-render";
+export * from "@/shared/files/latex-archives";
+export * from "@/shared/files/visual-assets";
+export * from "@/shared/files/use-file-processor";
diff --git a/src/shared/files/latex-archives.ts b/src/shared/files/latex-archives.ts
new file mode 100644
index 0000000..66417dd
--- /dev/null
+++ b/src/shared/files/latex-archives.ts
@@ -0,0 +1,461 @@
+import JSZip from "jszip"
+import { ungzip } from "pako"
+import { latexAssetBytesToDataUrl } from "@/shared/files/binary"
+import type { ExtractedVisualAsset } from "@/shared/files/types"
+
+/**
+ * LaTeX sources arrive as .zip or .tar.gz uploads. Both are walked the same
+ * way: find the main .tex, follow \input/\include to build the full source,
+ * then pull out the text and the \includegraphics figures it references.
+ */
+
+const stripLatexToText = (raw: string) => {
+ const s = String(raw || "")
+ .replace(/\r/g, "")
+ .replace(/(^|[^\\])%.*$/gm, "$1")
+ .replace(/\\(begin|end)\{[^}]*\}/g, " ")
+ .replace(/\\[a-zA-Z@]+(\[[^\]]*\])?(\{[^}]*\})?/g, " ")
+ .replace(/\{|\}/g, " ")
+ .replace(/\s+/g, " ")
+ .trim()
+ return s
+}
+
+type ArchiveEntry = { name: string; bytes: Uint8Array }
+type LatexGraphicRef = { includePath: string; sourceTexPath: string; caption: string; searchDirs: string[] }
+
+const parseTarEntries = (tarBytes: Uint8Array): ArchiveEntry[] => {
+ const out: ArchiveEntry[] = []
+ const block = 512
+ let offset = 0
+ while (offset + block <= tarBytes.length) {
+ const header = tarBytes.subarray(offset, offset + block)
+ const isZero = header.every((b) => b === 0)
+ if (isZero) break
+
+ const nameRaw = new TextDecoder("utf-8").decode(header.subarray(0, 100))
+ const prefixRaw = new TextDecoder("utf-8").decode(header.subarray(345, 500))
+ const base = nameRaw.replace(/\0.*$/, "").trim()
+ const prefix = prefixRaw.replace(/\0.*$/, "").trim()
+ const name = `${prefix ? `${prefix}/` : ""}${base}`
+ const sizeRaw = new TextDecoder("utf-8")
+ .decode(header.subarray(124, 136))
+ .replace(/\0.*$/, "")
+ .trim()
+ const size = parseInt(sizeRaw || "0", 8) || 0
+ const typeflag = String.fromCharCode(header[156] || 48)
+
+ const dataStart = offset + block
+ const dataEnd = dataStart + size
+ if (size > 0 && dataEnd <= tarBytes.length && typeflag !== "5") {
+ out.push({ name, bytes: tarBytes.subarray(dataStart, dataEnd) })
+ }
+ const padded = Math.ceil(size / block) * block
+ offset = dataStart + padded
+ }
+ return out
+}
+
+const pickMainTexEntry = (zip: JSZip) => {
+ const texEntries = Object.values(zip.files).filter((f) => !f.dir && /\.tex$/i.test(String(f.name || "")))
+ if (texEntries.length === 0) return null
+ const preferredNames = ["main.tex", "paper.tex", "manuscript.tex", "document.tex"]
+ for (const name of preferredNames) {
+ const hit = texEntries.find((e) => String(e.name || "").toLowerCase().endsWith(name))
+ if (hit) return hit
+ }
+ const score = (entryName: string) => {
+ const n = String(entryName || "").toLowerCase()
+ const depth = n.split("/").length
+ const base = n.split("/").pop() || n
+ let s = 0
+ if (base.includes("main")) s += 6
+ if (base.includes("paper")) s += 4
+ if (base.includes("manuscript")) s += 3
+ if (base.includes("camera")) s += 2
+ if (n.includes("arxiv")) s += 1
+ // Prefer shallower and shorter names.
+ s += Math.max(0, 6 - depth)
+ s += Math.max(0, 140 - n.length) / 50
+ return s
+ }
+ return (
+ texEntries
+ .slice()
+ .sort((a, b) => score(String(b.name || "")) - score(String(a.name || "")))[0] || texEntries[0]
+ )
+}
+
+const pickMainTexFromEntries = (entries: ArchiveEntry[]) => {
+ const texEntries = entries.filter((e) => /\.tex$/i.test(String(e.name || "")))
+ if (texEntries.length === 0) return null
+ const preferredNames = ["main.tex", "paper.tex", "manuscript.tex", "document.tex"]
+ for (const name of preferredNames) {
+ const hit = texEntries.find((e) => String(e.name || "").toLowerCase().endsWith(name))
+ if (hit) return hit
+ }
+ const score = (entryName: string) => {
+ const n = String(entryName || "").toLowerCase()
+ const depth = n.split("/").length
+ const base = n.split("/").pop() || n
+ let s = 0
+ if (base.includes("main")) s += 6
+ if (base.includes("paper")) s += 4
+ if (base.includes("manuscript")) s += 3
+ if (base.includes("camera")) s += 2
+ if (n.includes("arxiv")) s += 1
+ s += Math.max(0, 6 - depth)
+ s += Math.max(0, 140 - n.length) / 50
+ return s
+ }
+ return texEntries.slice().sort((a, b) => score(String(b.name || "")) - score(String(a.name || "")))[0] || texEntries[0]
+}
+
+const normalizePathLike = (value: string) =>
+ String(value || "")
+ .replace(/\\/g, "/")
+ .replace(/^\.\//, "")
+ .replace(/\/{2,}/g, "/")
+ .trim()
+
+const extractGraphicPathDirs = (tex: string, sourceTexPath: string) => {
+ const dirs: string[] = []
+ const baseDir = dirnameOf(sourceTexPath)
+ const gpRe = /\\graphicspath\s*\{([\s\S]*?)\}/g
+ let gm: RegExpExecArray | null
+ while ((gm = gpRe.exec(tex))) {
+ const body = String(gm[1] || "")
+ const dirRe = /\{([^}]+)\}/g
+ let dm: RegExpExecArray | null
+ while ((dm = dirRe.exec(body))) {
+ const d = normalizePathLike(String(dm[1] || "").trim().replace(/^["']|["']$/g, ""))
+ if (!d) continue
+ dirs.push(joinPathLike(baseDir, d))
+ }
+ }
+ return Array.from(new Set(dirs))
+}
+
+const dirnameOf = (path: string) => {
+ const n = normalizePathLike(path)
+ const idx = n.lastIndexOf("/")
+ if (idx < 0) return ""
+ return n.slice(0, idx)
+}
+
+const joinPathLike = (baseDir: string, rel: string) => {
+ const parts = `${baseDir ? `${baseDir}/` : ""}${rel}`.split("/")
+ const out: string[] = []
+ for (const part of parts) {
+ if (!part || part === ".") continue
+ if (part === "..") {
+ out.pop()
+ continue
+ }
+ out.push(part)
+ }
+ return out.join("/")
+}
+
+const resolveTexPathInMap = (baseTexPath: string, target: string, texMap: Map<string, string>) => {
+ const rel = normalizePathLike(target).replace(/^["']|["']$/g, "")
+ if (!rel) return null
+ const hasExt = /\.[a-z0-9]+$/i.test(rel)
+ const candidates = hasExt ? [rel] : [rel, `${rel}.tex`]
+ const baseDir = dirnameOf(baseTexPath)
+
+ for (const c of candidates) {
+ const joined = normalizePathLike(joinPathLike(baseDir, c))
+ if (texMap.has(joined)) return joined
+ const suffix = `/${joined}`
+ const bySuffix = Array.from(texMap.keys()).find((k) => k.endsWith(suffix) || k === joined)
+ if (bySuffix) return bySuffix
+ }
+ return null
+}
+
+const buildTexMapFromZip = async (zip: JSZip) => {
+ const texEntries = Object.values(zip.files).filter((f) => !f.dir && /\.tex$/i.test(String(f.name || "")))
+ const map = new Map<string, string>()
+ for (const entry of texEntries) {
+ const key = normalizePathLike(String(entry.name || ""))
+ const value = await entry.async("string")
+ map.set(key, value)
+ }
+ return map
+}
+
+const buildTexMapFromEntries = (entries: ArchiveEntry[]) => {
+ const map = new Map<string, string>()
+ for (const entry of entries) {
+ if (!/\.tex$/i.test(String(entry.name || ""))) continue
+ const key = normalizePathLike(String(entry.name || ""))
+ const value = new TextDecoder("utf-8").decode(entry.bytes)
+ map.set(key, value)
+ }
+ return map
+}
+
+const collectLatexGraphicsFromMap = (rootTexPath: string, texMap: Map<string, string>) => {
+ const visited = new Set<string>()
+ const graphics: LatexGraphicRef[] = []
+ const textChunks: string[] = []
+
+ const walk = (texPath: string, depth: number) => {
+ if (depth > 20) return
+ const key = normalizePathLike(texPath)
+ if (!key || visited.has(key)) return
+ const tex = texMap.get(key)
+ if (typeof tex !== "string") return
+ visited.add(key)
+ textChunks.push(tex)
+
+ const searchDirs = extractGraphicPathDirs(tex, key)
+ const includeRe = /\\includegraphics\s*(?:\[[\s\S]*?\])?\s*\{([^}]+)\}/g
+ let gm: RegExpExecArray | null
+ while ((gm = includeRe.exec(tex))) {
+ const includePath = String(gm[1] || "").trim()
+ if (!includePath) continue
+ graphics.push({
+ includePath,
+ sourceTexPath: key,
+ caption: extractLatexCaptionNear(tex, gm.index),
+ searchDirs,
+ })
+ }
+
+ const subRe = /\\(?:input|include)\s*\{([^}]+)\}/g
+ let sm: RegExpExecArray | null
+ while ((sm = subRe.exec(tex))) {
+ const target = String(sm[1] || "").trim()
+ const resolved = resolveTexPathInMap(key, target, texMap)
+ if (!resolved) continue
+ walk(resolved, depth + 1)
+ }
+ }
+
+ walk(rootTexPath, 0)
+ return { graphics, mergedText: textChunks.join("\n\n") }
+}
+
+const resolveZipEntryForGraphic = (zip: JSZip, graphicPath: string) => {
+ const raw = String(graphicPath || "").trim().replace(/^["']|["']$/g, "")
+ if (!raw) return null
+ const normalized = raw.replace(/\\/g, "/").replace(/^\.?\//, "")
+ const lower = normalized.toLowerCase()
+ const hasExt = /\.[a-z0-9]+$/i.test(lower)
+ const tryExts = hasExt ? [""] : [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".svg"]
+
+ const candidates: string[] = []
+ for (const ext of tryExts) candidates.push(lower + ext)
+
+ const entries = Object.values(zip.files).filter((f) => !f.dir)
+ for (const want of candidates) {
+ const exact = entries.find((e) => String(e.name || "").toLowerCase() === want)
+ if (exact) return exact
+ }
+ for (const want of candidates) {
+ const hit = entries.find((e) => {
+ const n = String(e.name || "").toLowerCase()
+ return n.endsWith(`/${want}`) || n.endsWith(want)
+ })
+ if (hit) return hit
+ }
+ return null
+}
+
+const resolveZipEntryForGraphicFromTex = (zip: JSZip, sourceTexPath: string, graphicPath: string, searchDirs: string[] = []) => {
+ const raw = String(graphicPath || "").trim().replace(/^["']|["']$/g, "")
+ if (!raw) return null
+ const rel = normalizePathLike(raw).replace(/^\.?\//, "")
+ const baseDir = dirnameOf(sourceTexPath)
+ const withBase = joinPathLike(baseDir, rel)
+ const hasExt = /\.[a-z0-9]+$/i.test(rel)
+ const tryExts = hasExt ? [""] : [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".svg", ".pdf"]
+ const candidates = [withBase, rel, ...searchDirs.map((d) => joinPathLike(d, rel))]
+ .flatMap((p) => tryExts.map((ext) => normalizePathLike(`${p}${ext}`)))
+ .filter(Boolean)
+
+ const entries = Object.values(zip.files).filter((f) => !f.dir)
+ for (const want of candidates) {
+ const exact = entries.find((e) => normalizePathLike(String(e.name || "")).toLowerCase() === want.toLowerCase())
+ if (exact) return exact
+ const suffix = `/${want.toLowerCase()}`
+ const bySuffix = entries.find((e) => normalizePathLike(String(e.name || "")).toLowerCase().endsWith(suffix))
+ if (bySuffix) return bySuffix
+ }
+ return null
+}
+
+const resolveArchiveEntryForGraphic = (entries: ArchiveEntry[], graphicPath: string) => {
+ const raw = String(graphicPath || "").trim().replace(/^["']|["']$/g, "")
+ if (!raw) return null
+ const normalized = raw.replace(/\\/g, "/").replace(/^\.?\//, "")
+ const lower = normalized.toLowerCase()
+ const hasExt = /\.[a-z0-9]+$/i.test(lower)
+ const tryExts = hasExt ? [""] : [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".svg"]
+
+ const candidates: string[] = []
+ for (const ext of tryExts) candidates.push(lower + ext)
+
+ for (const want of candidates) {
+ const exact = entries.find((e) => String(e.name || "").toLowerCase() === want)
+ if (exact) return exact
+ }
+ for (const want of candidates) {
+ const hit = entries.find((e) => {
+ const n = String(e.name || "").toLowerCase()
+ return n.endsWith(`/${want}`) || n.endsWith(want)
+ })
+ if (hit) return hit
+ }
+ return null
+}
+
+const resolveArchiveEntryForGraphicFromTex = (entries: ArchiveEntry[], sourceTexPath: string, graphicPath: string, searchDirs: string[] = []) => {
+ const raw = String(graphicPath || "").trim().replace(/^["']|["']$/g, "")
+ if (!raw) return null
+ const rel = normalizePathLike(raw).replace(/^\.?\//, "")
+ const baseDir = dirnameOf(sourceTexPath)
+ const withBase = joinPathLike(baseDir, rel)
+ const hasExt = /\.[a-z0-9]+$/i.test(rel)
+ const tryExts = hasExt ? [""] : [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".svg", ".pdf"]
+ const candidates = [withBase, rel, ...searchDirs.map((d) => joinPathLike(d, rel))]
+ .flatMap((p) => tryExts.map((ext) => normalizePathLike(`${p}${ext}`)))
+ .filter(Boolean)
+
+ for (const want of candidates) {
+ const exact = entries.find((e) => normalizePathLike(String(e.name || "")).toLowerCase() === want.toLowerCase())
+ if (exact) return exact
+ const suffix = `/${want.toLowerCase()}`
+ const bySuffix = entries.find((e) => normalizePathLike(String(e.name || "")).toLowerCase().endsWith(suffix))
+ if (bySuffix) return bySuffix
+ }
+ return null
+}
+
+const extractLatexCaptionNear = (tex: string, matchIndex: number) => {
+ const windowStart = Math.max(0, matchIndex - 1200)
+ const windowEnd = Math.min(tex.length, matchIndex + 2400)
+ const window = tex.slice(windowStart, windowEnd)
+ const cap = window.match(/\\caption(?:\[[^\]]*\])?\{([\s\S]*?)\}/)
+ if (cap && cap[1]) return stripLatexToText(cap[1]).slice(0, 220)
+ return ""
+}
+
+export async function extractLatexZipText(file: File): Promise<string> {
+ const buffer = await file.arrayBuffer()
+ const zip = await JSZip.loadAsync(buffer)
+ const main = pickMainTexEntry(zip)
+ if (!main) throw new Error("No .tex file found in zip")
+ const texMap = await buildTexMapFromZip(zip)
+ const root = normalizePathLike(String(main.name || ""))
+ const { mergedText } = collectLatexGraphicsFromMap(root, texMap)
+ return stripLatexToText(mergedText || (await main.async("string")))
+}
+
+export async function extractLatexZipVisualAssets(
+ file: File,
+ options?: { maxAssets?: number }
+): Promise<ExtractedVisualAsset[]> {
+ const maxAssets = Math.max(1, options?.maxAssets ?? 12)
+ const buffer = await file.arrayBuffer()
+ const zip = await JSZip.loadAsync(buffer)
+ const main = pickMainTexEntry(zip)
+ if (!main) return []
+ const texMap = await buildTexMapFromZip(zip)
+ const root = normalizePathLike(String(main.name || ""))
+ let { graphics } = collectLatexGraphicsFromMap(root, texMap)
+ if (graphics.length === 0) {
+ for (const texPath of texMap.keys()) {
+ const hit = collectLatexGraphicsFromMap(texPath, texMap).graphics
+ if (hit.length > 0) {
+ graphics = hit
+ break
+ }
+ }
+ }
+ const assets: ExtractedVisualAsset[] = []
+ let order = 0
+ for (const g of graphics) {
+ if (assets.length >= maxAssets) break
+ const entry =
+ resolveZipEntryForGraphicFromTex(zip, g.sourceTexPath, g.includePath, g.searchDirs) ||
+ resolveZipEntryForGraphic(zip, g.includePath)
+ if (!entry) continue
+ const bytes = await entry.async("uint8array")
+ const dataUrl = await latexAssetBytesToDataUrl(entry.name, bytes)
+ if (!dataUrl.startsWith("data:image")) continue
+ order += 1
+ const caption = String(g.caption || "").trim()
+ const hint = caption ? `LaTeX caption: ${caption}` : `LaTeX includegraphics: ${g.includePath}`
+ assets.push({
+ id: `latex-${file.name}-${order}`,
+ sourceFileName: file.name,
+ sourceType: "latex",
+ order,
+ dataUrl,
+ textHint: hint.slice(0, 800),
+ })
+ }
+ return assets
+}
+
+export async function extractLatexTarGzText(file: File): Promise<string> {
+ const buffer = await file.arrayBuffer()
+ const tarBytes = ungzip(new Uint8Array(buffer))
+ const entries = parseTarEntries(tarBytes)
+ const main = pickMainTexFromEntries(entries)
+ if (!main) throw new Error("No .tex file found in tar.gz")
+ const texMap = buildTexMapFromEntries(entries)
+ const root = normalizePathLike(String(main.name || ""))
+ const { mergedText } = collectLatexGraphicsFromMap(root, texMap)
+ return stripLatexToText(mergedText || new TextDecoder("utf-8").decode(main.bytes))
+}
+
+export async function extractLatexTarGzVisualAssets(
+ file: File,
+ options?: { maxAssets?: number }
+): Promise<ExtractedVisualAsset[]> {
+ const maxAssets = Math.max(1, options?.maxAssets ?? 12)
+ const buffer = await file.arrayBuffer()
+ const tarBytes = ungzip(new Uint8Array(buffer))
+ const entries = parseTarEntries(tarBytes)
+ const main = pickMainTexFromEntries(entries)
+ if (!main) return []
+ const texMap = buildTexMapFromEntries(entries)
+ const root = normalizePathLike(String(main.name || ""))
+ let { graphics } = collectLatexGraphicsFromMap(root, texMap)
+ if (graphics.length === 0) {
+ for (const texPath of texMap.keys()) {
+ const hit = collectLatexGraphicsFromMap(texPath, texMap).graphics
+ if (hit.length > 0) {
+ graphics = hit
+ break
+ }
+ }
+ }
+ const assets: ExtractedVisualAsset[] = []
+ let order = 0
+ for (const g of graphics) {
+ if (assets.length >= maxAssets) break
+ const entry =
+ resolveArchiveEntryForGraphicFromTex(entries, g.sourceTexPath, g.includePath, g.searchDirs) ||
+ resolveArchiveEntryForGraphic(entries, g.includePath)
+ if (!entry) continue
+ const dataUrl = await latexAssetBytesToDataUrl(entry.name, entry.bytes)
+ if (!dataUrl.startsWith("data:image")) continue
+ order += 1
+ const caption = String(g.caption || "").trim()
+ const hint = caption ? `LaTeX caption: ${caption}` : `LaTeX includegraphics: ${g.includePath}`
+ assets.push({
+ id: `latex-tgz-${file.name}-${order}`,
+ sourceFileName: file.name,
+ sourceType: "latex",
+ order,
+ dataUrl,
+ textHint: hint.slice(0, 800),
+ })
+ }
+ return assets
+}
diff --git a/src/shared/files/pdf-render.ts b/src/shared/files/pdf-render.ts
new file mode 100644
index 0000000..94722c9
--- /dev/null
+++ b/src/shared/files/pdf-render.ts
@@ -0,0 +1,41 @@
+import { getDocumentProxy } from "unpdf"
+
+/**
+ * Rasterising a PDF page for on-screen previews — file-preview thumbnails and
+ * the PPT workspace's page picker. Text extraction lives in extract-text.ts.
+ */
+
+export async function getPdfDocumentFromUrl(url: string): Promise<any> {
+ const res = await fetch(url)
+ const buffer = await res.arrayBuffer()
+ return await getDocumentProxy(new Uint8Array(buffer))
+}
+
+export async function getPdfPageCountFromUrl(url: string): Promise<number> {
+ const pdf = await getPdfDocumentFromUrl(url)
+ return (pdf as any).numPages ?? 0
+}
+
+/** Draws one page at `targetWidth` CSS pixels, scaled up for the device ratio. */
+export async function renderPdfPageToCanvas(opts: {
+ pdf: any
+ pageNumber: number
+ canvas: HTMLCanvasElement
+ targetWidth: number
+}): Promise<void> {
+ const page = await opts.pdf.getPage(opts.pageNumber)
+ const viewportAtScale1 = page.getViewport({ scale: 1 })
+ const scale = opts.targetWidth / viewportAtScale1.width
+ const viewport = page.getViewport({ scale })
+
+ const dpr = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1
+ opts.canvas.width = Math.floor(viewport.width * dpr)
+ opts.canvas.height = Math.floor(viewport.height * dpr)
+ opts.canvas.style.width = `${Math.floor(viewport.width)}px`
+ opts.canvas.style.height = `${Math.floor(viewport.height)}px`
+
+ const ctx = opts.canvas.getContext("2d")
+ if (!ctx) return
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
+ await page.render({ canvasContext: ctx, viewport }).promise
+}
diff --git a/src/shared/files/types.ts b/src/shared/files/types.ts
new file mode 100644
index 0000000..b209302
--- /dev/null
+++ b/src/shared/files/types.ts
@@ -0,0 +1,19 @@
+/** Shapes shared by the file-extraction modules. */
+
+export interface ExtractedVisualAsset {
+ id: string
+ sourceFileName: string
+ sourceType: "pdf" | "word" | "latex" | "third_party"
+ page?: number
+ order: number
+ dataUrl: string
+ textHint: string
+}
+
+export type VisualCategory =
+ | "framework"
+ | "result_table"
+ | "mechanism"
+ | "key_visual"
+ | "data_structure"
+ | "other"
diff --git a/src/shared/files/use-file-processor.ts b/src/shared/files/use-file-processor.ts
new file mode 100644
index 0000000..6464be7
--- /dev/null
+++ b/src/shared/files/use-file-processor.ts
@@ -0,0 +1,198 @@
+"use client"
+
+import { useState } from "react"
+import { toast } from "sonner"
+import { getAIConfig } from "@/ai/config"
+import {
+ MAX_EXTRACTED_CHARS,
+ isPdfFile,
+ isTarGzFile,
+ isTextFile,
+ isWordFile,
+ isZipFile,
+} from "@/shared/files/detect"
+import { extractPdfText, extractTextFileContent, extractWordText } from "@/shared/files/extract-text"
+import {
+ extractLatexTarGzText,
+ extractLatexTarGzVisualAssets,
+ extractLatexZipText,
+ extractLatexZipVisualAssets,
+} from "@/shared/files/latex-archives"
+import {
+ extractPdfVisualAssets,
+ extractThirdPartyVisualAssets,
+ extractWordVisualAssets,
+} from "@/shared/files/visual-assets"
+import type { ExtractedVisualAsset } from "@/shared/files/types"
+
+/**
+ * Turns dropped files into prompt-ready text plus the figures worth showing a
+ * model. Shared by every workspace's chat input.
+ */
+
+export type FileWorkspace = "flow" | "cad" | "ppt" | "unknown"
+
+export interface FileData {
+ text: string
+ charCount: number
+ isExtracting: boolean
+ visualAssets?: ExtractedVisualAsset[]
+}
+
+const MINERU_API_BASE = "https://mineru.net"
+
+/** Which extractors handle a file, and whether MinerU can improve on them. */
+type ExtractionPlan = {
+ /** Telemetry label; only the formats MinerU understands set one. */
+ kind?: "pdf" | "word"
+ extractText: (file: File) => Promise<string>
+ extractVisuals?: (file: File) => Promise<ExtractedVisualAsset[]>
+}
+
+function planFor(file: File): ExtractionPlan | null {
+ if (isPdfFile(file)) {
+ return { kind: "pdf", extractText: extractPdfText, extractVisuals: extractPdfVisualAssets }
+ }
+ if (isWordFile(file)) {
+ return { kind: "word", extractText: extractWordText, extractVisuals: extractWordVisualAssets }
+ }
+ if (isZipFile(file)) {
+ return { extractText: extractLatexZipText, extractVisuals: extractLatexZipVisualAssets }
+ }
+ if (isTarGzFile(file)) {
+ return { extractText: extractLatexTarGzText, extractVisuals: extractLatexTarGzVisualAssets }
+ }
+ if (isTextFile(file)) {
+ return { extractText: extractTextFileContent }
+ }
+ return null
+}
+
+type ParserSource = "third_party" | "local" | "third_party_fallback_local"
+
+function reportParserSource(params: {
+ workspace: FileWorkspace
+ file: File
+ parserSource: ParserSource
+ detail?: string
+}) {
+ return fetch("/api/log-file-parser", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ workspace: params.workspace,
+ fileName: params.file.name,
+ mimeType: params.file.type || "",
+ fileSize: params.file.size || 0,
+ parserSource: params.parserSource,
+ detail: params.detail || "",
+ }),
+ keepalive: true,
+ }).catch((error) => console.warn("Failed to report file parser source", error))
+}
+
+/**
+ * MinerU reads layout far better than the local extractors, but only for PDF
+ * and Word and only when the user configured a token. Any failure falls back
+ * to local extraction rather than losing the figures entirely.
+ */
+async function extractVisuals(
+ file: File,
+ plan: ExtractionPlan,
+ workspace: FileWorkspace,
+): Promise<ExtractedVisualAsset[]> {
+ if (!plan.extractVisuals) return []
+
+ const apiToken = String(getAIConfig().fileParserApiToken || "").trim()
+ if (!apiToken || !plan.kind) {
+ if (plan.kind) {
+ void reportParserSource({ workspace, file, parserSource: "local", detail: plan.kind })
+ }
+ return await plan.extractVisuals(file)
+ }
+
+ try {
+ const assets = await extractThirdPartyVisualAssets(file, { apiBase: MINERU_API_BASE, apiToken })
+ void reportParserSource({ workspace, file, parserSource: "third_party", detail: plan.kind })
+ return assets
+ } catch (error) {
+ console.error("Third-party parser failed, falling back to local extraction:", error)
+ void reportParserSource({
+ workspace,
+ file,
+ parserSource: "third_party_fallback_local",
+ detail: plan.kind,
+ })
+ return await plan.extractVisuals(file)
+ }
+}
+
+export function useFileProcessor(workspace: FileWorkspace = "unknown") {
+ const [files, setFiles] = useState<File[]>([])
+ const [pdfData, setPdfData] = useState<Map<File, FileData>>(new Map())
+
+ const setFileData = (file: File, data: FileData) =>
+ setPdfData((prev) => new Map(prev).set(file, data))
+
+ const dropFileData = (file: File) =>
+ setPdfData((prev) => {
+ const next = new Map(prev)
+ next.delete(file)
+ return next
+ })
+
+ const handleFileChange = async (newFiles: File[]) => {
+ setFiles(newFiles)
+
+ for (const file of newFiles) {
+ if (pdfData.has(file)) continue
+ const plan = planFor(file)
+ if (!plan) continue
+
+ setFileData(file, { text: "", charCount: 0, isExtracting: true })
+
+ try {
+ const text = await plan.extractText(file)
+
+ // Oversized files are rejected outright: a truncated document
+ // silently produces a wrong answer, which is worse than none.
+ if (text.length > MAX_EXTRACTED_CHARS) {
+ toast.error(
+ `${file.name}: Content exceeds ${MAX_EXTRACTED_CHARS / 1000}k character limit (${(text.length / 1000).toFixed(1)}k chars)`,
+ )
+ dropFileData(file)
+ setFiles((prev) => prev.filter((f) => f !== file))
+ continue
+ }
+
+ setFileData(file, {
+ text,
+ charCount: text.length,
+ isExtracting: false,
+ visualAssets: await extractVisuals(file, plan, workspace),
+ })
+ } catch (error) {
+ console.error("Failed to extract text:", error)
+ toast.error(`Failed to read file: ${file.name}`)
+ dropFileData(file)
+ }
+ }
+
+ // Forget anything the user removed while extraction was running.
+ setPdfData((prev) => {
+ const next = new Map(prev)
+ for (const key of prev.keys()) {
+ if (!newFiles.includes(key)) next.delete(key)
+ }
+ return next
+ })
+ }
+
+ return {
+ files,
+ pdfData,
+ visualAssets: Array.from(pdfData.values()).flatMap((data) => data.visualAssets || []),
+ handleFileChange,
+ setFiles,
+ }
+}
diff --git a/src/workspaces/flow/next/lib/pdf-utils.ts b/src/shared/files/visual-assets.ts
similarity index 60%
rename from src/workspaces/flow/next/lib/pdf-utils.ts
rename to src/shared/files/visual-assets.ts
index c0a8077..c852f6f 100644
--- a/src/workspaces/flow/next/lib/pdf-utils.ts
+++ b/src/shared/files/visual-assets.ts
@@ -1,599 +1,16 @@
-import { extractText, getDocumentProxy } from "unpdf"
-import * as mammoth from "mammoth"
+import { extractText, getDocumentProxy } from "unpdf"
import JSZip from "jszip"
-import { ungzip } from "pako"
-// Maximum characters allowed for extracted text (configurable via env)
-const DEFAULT_MAX_EXTRACTED_CHARS = 150000 // 150k chars
-const viteMaxExtractedChars =
- typeof import.meta !== "undefined" &&
- import.meta.env &&
- typeof import.meta.env.VITE_MAX_EXTRACTED_CHARS !== "undefined"
- ? Number(import.meta.env.VITE_MAX_EXTRACTED_CHARS)
- : NaN
-export const MAX_EXTRACTED_CHARS =
- (Number.isFinite(viteMaxExtractedChars) ? viteMaxExtractedChars : NaN) ||
- DEFAULT_MAX_EXTRACTED_CHARS
-
-// Text file extensions we support
-const TEXT_EXTENSIONS = [
- ".txt",
- ".md",
- ".markdown",
- ".json",
- ".csv",
- ".xml",
- ".html",
- ".css",
- ".js",
- ".ts",
- ".jsx",
- ".tsx",
- ".py",
- ".java",
- ".c",
- ".cpp",
- ".h",
- ".go",
- ".rs",
- ".yaml",
- ".yml",
- ".toml",
- ".ini",
- ".log",
- ".sh",
- ".bash",
- ".zsh",
- ".tex",
-]
-
-/**
- * Extract text content from a PDF file
- * Uses unpdf library for client-side extraction
- */
-export async function extractPdfText(file: File): Promise<string> {
- const buffer = await file.arrayBuffer()
- const pdf = await getDocumentProxy(new Uint8Array(buffer))
- const { text } = await extractText(pdf, { mergePages: true })
- return text as string
-}
-
-/**
- * Check if a file is a PDF
- */
-export function isPdfFile(file: File): boolean {
- return file.type === "application/pdf" || file.name.endsWith(".pdf")
-}
-
-/**
- * Check if a file is a Word document (.docx).
- */
-export function isWordFile(file: File): boolean {
- const name = file.name.toLowerCase()
- return (
- file.type ===
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
- name.endsWith(".docx")
- )
-}
-
-/**
- * Check if a file is a text file
- */
-export function isTextFile(file: File): boolean {
- const name = file.name.toLowerCase()
- return (
- file.type.startsWith("text/") ||
- file.type === "application/json" ||
- TEXT_EXTENSIONS.some((ext) => name.endsWith(ext))
- )
-}
-
-export function isZipFile(file: File): boolean {
- const name = file.name.toLowerCase()
- const type = String(file.type || "").toLowerCase()
- if (name.endsWith(".zip")) return true
- return (
- type === "application/zip" ||
- type === "application/x-zip-compressed" ||
- type === "application/octet-stream"
- )
-}
-
-export function isTarGzFile(file: File): boolean {
- const name = file.name.toLowerCase()
- const type = String(file.type || "").toLowerCase()
- if (name.endsWith(".tgz") || name.endsWith(".tar.gz")) return true
- return type === "application/gzip" || type === "application/x-gzip"
-}
+import { bytesToBase64, decodeXmlText, getMimeByExt } from "@/shared/files/binary"
+import type { ExtractedVisualAsset, VisualCategory } from "@/shared/files/types"
/**
- * Extract text content from a text file
+ * Pulls figures and tables out of PDFs and .docx files so a diagram request
+ * can reference the pictures in an uploaded paper, not just its prose.
*/
-export async function extractTextFileContent(file: File): Promise<string> {
- return await file.text()
-}
-
-/**
- * Extract text content from a .docx file.
- */
-export async function extractWordText(file: File): Promise<string> {
- const arrayBuffer = await file.arrayBuffer()
- const result = await mammoth.extractRawText({ arrayBuffer })
- return String(result.value || "")
-}
-
-const stripLatexToText = (raw: string) => {
- const s = String(raw || "")
- .replace(/\r/g, "")
- .replace(/(^|[^\\])%.*$/gm, "$1")
- .replace(/\\(begin|end)\{[^}]*\}/g, " ")
- .replace(/\\[a-zA-Z@]+(\[[^\]]*\])?(\{[^}]*\})?/g, " ")
- .replace(/\{|\}/g, " ")
- .replace(/\s+/g, " ")
- .trim()
- return s
-}
-
-type ArchiveEntry = { name: string; bytes: Uint8Array }
-type LatexGraphicRef = { includePath: string; sourceTexPath: string; caption: string; searchDirs: string[] }
-
-const parseTarEntries = (tarBytes: Uint8Array): ArchiveEntry[] => {
- const out: ArchiveEntry[] = []
- const block = 512
- let offset = 0
- while (offset + block <= tarBytes.length) {
- const header = tarBytes.subarray(offset, offset + block)
- const isZero = header.every((b) => b === 0)
- if (isZero) break
-
- const nameRaw = new TextDecoder("utf-8").decode(header.subarray(0, 100))
- const prefixRaw = new TextDecoder("utf-8").decode(header.subarray(345, 500))
- const base = nameRaw.replace(/\0.*$/, "").trim()
- const prefix = prefixRaw.replace(/\0.*$/, "").trim()
- const name = `${prefix ? `${prefix}/` : ""}${base}`
- const sizeRaw = new TextDecoder("utf-8")
- .decode(header.subarray(124, 136))
- .replace(/\0.*$/, "")
- .trim()
- const size = parseInt(sizeRaw || "0", 8) || 0
- const typeflag = String.fromCharCode(header[156] || 48)
-
- const dataStart = offset + block
- const dataEnd = dataStart + size
- if (size > 0 && dataEnd <= tarBytes.length && typeflag !== "5") {
- out.push({ name, bytes: tarBytes.subarray(dataStart, dataEnd) })
- }
- const padded = Math.ceil(size / block) * block
- offset = dataStart + padded
- }
- return out
-}
-
-const pickMainTexEntry = (zip: JSZip) => {
- const texEntries = Object.values(zip.files).filter((f) => !f.dir && /\.tex$/i.test(String(f.name || "")))
- if (texEntries.length === 0) return null
- const preferredNames = ["main.tex", "paper.tex", "manuscript.tex", "document.tex"]
- for (const name of preferredNames) {
- const hit = texEntries.find((e) => String(e.name || "").toLowerCase().endsWith(name))
- if (hit) return hit
- }
- const score = (entryName: string) => {
- const n = String(entryName || "").toLowerCase()
- const depth = n.split("/").length
- const base = n.split("/").pop() || n
- let s = 0
- if (base.includes("main")) s += 6
- if (base.includes("paper")) s += 4
- if (base.includes("manuscript")) s += 3
- if (base.includes("camera")) s += 2
- if (n.includes("arxiv")) s += 1
- // Prefer shallower and shorter names.
- s += Math.max(0, 6 - depth)
- s += Math.max(0, 140 - n.length) / 50
- return s
- }
- return (
- texEntries
- .slice()
- .sort((a, b) => score(String(b.name || "")) - score(String(a.name || "")))[0] || texEntries[0]
- )
-}
-
-const pickMainTexFromEntries = (entries: ArchiveEntry[]) => {
- const texEntries = entries.filter((e) => /\.tex$/i.test(String(e.name || "")))
- if (texEntries.length === 0) return null
- const preferredNames = ["main.tex", "paper.tex", "manuscript.tex", "document.tex"]
- for (const name of preferredNames) {
- const hit = texEntries.find((e) => String(e.name || "").toLowerCase().endsWith(name))
- if (hit) return hit
- }
- const score = (entryName: string) => {
- const n = String(entryName || "").toLowerCase()
- const depth = n.split("/").length
- const base = n.split("/").pop() || n
- let s = 0
- if (base.includes("main")) s += 6
- if (base.includes("paper")) s += 4
- if (base.includes("manuscript")) s += 3
- if (base.includes("camera")) s += 2
- if (n.includes("arxiv")) s += 1
- s += Math.max(0, 6 - depth)
- s += Math.max(0, 140 - n.length) / 50
- return s
- }
- return texEntries.slice().sort((a, b) => score(String(b.name || "")) - score(String(a.name || "")))[0] || texEntries[0]
-}
-
-const normalizePathLike = (value: string) =>
- String(value || "")
- .replace(/\\/g, "/")
- .replace(/^\.\//, "")
- .replace(/\/{2,}/g, "/")
- .trim()
-
-const extractGraphicPathDirs = (tex: string, sourceTexPath: string) => {
- const dirs: string[] = []
- const baseDir = dirnameOf(sourceTexPath)
- const gpRe = /\\graphicspath\s*\{([\s\S]*?)\}/g
- let gm: RegExpExecArray | null
- while ((gm = gpRe.exec(tex))) {
- const body = String(gm[1] || "")
- const dirRe = /\{([^}]+)\}/g
- let dm: RegExpExecArray | null
- while ((dm = dirRe.exec(body))) {
- const d = normalizePathLike(String(dm[1] || "").trim().replace(/^["']|["']$/g, ""))
- if (!d) continue
- dirs.push(joinPathLike(baseDir, d))
- }
- }
- return Array.from(new Set(dirs))
-}
-
-const dirnameOf = (path: string) => {
- const n = normalizePathLike(path)
- const idx = n.lastIndexOf("/")
- if (idx < 0) return ""
- return n.slice(0, idx)
-}
-
-const joinPathLike = (baseDir: string, rel: string) => {
- const parts = `${baseDir ? `${baseDir}/` : ""}${rel}`.split("/")
- const out: string[] = []
- for (const part of parts) {
- if (!part || part === ".") continue
- if (part === "..") {
- out.pop()
- continue
- }
- out.push(part)
- }
- return out.join("/")
-}
-
-const resolveTexPathInMap = (baseTexPath: string, target: string, texMap: Map<string, string>) => {
- const rel = normalizePathLike(target).replace(/^["']|["']$/g, "")
- if (!rel) return null
- const hasExt = /\.[a-z0-9]+$/i.test(rel)
- const candidates = hasExt ? [rel] : [rel, `${rel}.tex`]
- const baseDir = dirnameOf(baseTexPath)
-
- for (const c of candidates) {
- const joined = normalizePathLike(joinPathLike(baseDir, c))
- if (texMap.has(joined)) return joined
- const suffix = `/${joined}`
- const bySuffix = Array.from(texMap.keys()).find((k) => k.endsWith(suffix) || k === joined)
- if (bySuffix) return bySuffix
- }
- return null
-}
-
-const buildTexMapFromZip = async (zip: JSZip) => {
- const texEntries = Object.values(zip.files).filter((f) => !f.dir && /\.tex$/i.test(String(f.name || "")))
- const map = new Map<string, string>()
- for (const entry of texEntries) {
- const key = normalizePathLike(String(entry.name || ""))
- const value = await entry.async("string")
- map.set(key, value)
- }
- return map
-}
-
-const buildTexMapFromEntries = (entries: ArchiveEntry[]) => {
- const map = new Map<string, string>()
- for (const entry of entries) {
- if (!/\.tex$/i.test(String(entry.name || ""))) continue
- const key = normalizePathLike(String(entry.name || ""))
- const value = new TextDecoder("utf-8").decode(entry.bytes)
- map.set(key, value)
- }
- return map
-}
-
-const collectLatexGraphicsFromMap = (rootTexPath: string, texMap: Map<string, string>) => {
- const visited = new Set<string>()
- const graphics: LatexGraphicRef[] = []
- const textChunks: string[] = []
-
- const walk = (texPath: string, depth: number) => {
- if (depth > 20) return
- const key = normalizePathLike(texPath)
- if (!key || visited.has(key)) return
- const tex = texMap.get(key)
- if (typeof tex !== "string") return
- visited.add(key)
- textChunks.push(tex)
-
- const searchDirs = extractGraphicPathDirs(tex, key)
- const includeRe = /\\includegraphics\s*(?:\[[\s\S]*?\])?\s*\{([^}]+)\}/g
- let gm: RegExpExecArray | null
- while ((gm = includeRe.exec(tex))) {
- const includePath = String(gm[1] || "").trim()
- if (!includePath) continue
- graphics.push({
- includePath,
- sourceTexPath: key,
- caption: extractLatexCaptionNear(tex, gm.index),
- searchDirs,
- })
- }
-
- const subRe = /\\(?:input|include)\s*\{([^}]+)\}/g
- let sm: RegExpExecArray | null
- while ((sm = subRe.exec(tex))) {
- const target = String(sm[1] || "").trim()
- const resolved = resolveTexPathInMap(key, target, texMap)
- if (!resolved) continue
- walk(resolved, depth + 1)
- }
- }
-
- walk(rootTexPath, 0)
- return { graphics, mergedText: textChunks.join("\n\n") }
-}
-
-const resolveZipEntryForGraphic = (zip: JSZip, graphicPath: string) => {
- const raw = String(graphicPath || "").trim().replace(/^["']|["']$/g, "")
- if (!raw) return null
- const normalized = raw.replace(/\\/g, "/").replace(/^\.?\//, "")
- const lower = normalized.toLowerCase()
- const hasExt = /\.[a-z0-9]+$/i.test(lower)
- const tryExts = hasExt ? [""] : [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".svg"]
-
- const candidates: string[] = []
- for (const ext of tryExts) candidates.push(lower + ext)
-
- const entries = Object.values(zip.files).filter((f) => !f.dir)
- for (const want of candidates) {
- const exact = entries.find((e) => String(e.name || "").toLowerCase() === want)
- if (exact) return exact
- }
- for (const want of candidates) {
- const hit = entries.find((e) => {
- const n = String(e.name || "").toLowerCase()
- return n.endsWith(`/${want}`) || n.endsWith(want)
- })
- if (hit) return hit
- }
- return null
-}
-
-const resolveZipEntryForGraphicFromTex = (zip: JSZip, sourceTexPath: string, graphicPath: string, searchDirs: string[] = []) => {
- const raw = String(graphicPath || "").trim().replace(/^["']|["']$/g, "")
- if (!raw) return null
- const rel = normalizePathLike(raw).replace(/^\.?\//, "")
- const baseDir = dirnameOf(sourceTexPath)
- const withBase = joinPathLike(baseDir, rel)
- const hasExt = /\.[a-z0-9]+$/i.test(rel)
- const tryExts = hasExt ? [""] : [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".svg", ".pdf"]
- const candidates = [withBase, rel, ...searchDirs.map((d) => joinPathLike(d, rel))]
- .flatMap((p) => tryExts.map((ext) => normalizePathLike(`${p}${ext}`)))
- .filter(Boolean)
-
- const entries = Object.values(zip.files).filter((f) => !f.dir)
- for (const want of candidates) {
- const exact = entries.find((e) => normalizePathLike(String(e.name || "")).toLowerCase() === want.toLowerCase())
- if (exact) return exact
- const suffix = `/${want.toLowerCase()}`
- const bySuffix = entries.find((e) => normalizePathLike(String(e.name || "")).toLowerCase().endsWith(suffix))
- if (bySuffix) return bySuffix
- }
- return null
-}
-
-const resolveArchiveEntryForGraphic = (entries: ArchiveEntry[], graphicPath: string) => {
- const raw = String(graphicPath || "").trim().replace(/^["']|["']$/g, "")
- if (!raw) return null
- const normalized = raw.replace(/\\/g, "/").replace(/^\.?\//, "")
- const lower = normalized.toLowerCase()
- const hasExt = /\.[a-z0-9]+$/i.test(lower)
- const tryExts = hasExt ? [""] : [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".svg"]
-
- const candidates: string[] = []
- for (const ext of tryExts) candidates.push(lower + ext)
-
- for (const want of candidates) {
- const exact = entries.find((e) => String(e.name || "").toLowerCase() === want)
- if (exact) return exact
- }
- for (const want of candidates) {
- const hit = entries.find((e) => {
- const n = String(e.name || "").toLowerCase()
- return n.endsWith(`/${want}`) || n.endsWith(want)
- })
- if (hit) return hit
- }
- return null
-}
-
-const resolveArchiveEntryForGraphicFromTex = (entries: ArchiveEntry[], sourceTexPath: string, graphicPath: string, searchDirs: string[] = []) => {
- const raw = String(graphicPath || "").trim().replace(/^["']|["']$/g, "")
- if (!raw) return null
- const rel = normalizePathLike(raw).replace(/^\.?\//, "")
- const baseDir = dirnameOf(sourceTexPath)
- const withBase = joinPathLike(baseDir, rel)
- const hasExt = /\.[a-z0-9]+$/i.test(rel)
- const tryExts = hasExt ? [""] : [".png", ".jpg", ".jpeg", ".webp", ".gif", ".bmp", ".svg", ".pdf"]
- const candidates = [withBase, rel, ...searchDirs.map((d) => joinPathLike(d, rel))]
- .flatMap((p) => tryExts.map((ext) => normalizePathLike(`${p}${ext}`)))
- .filter(Boolean)
-
- for (const want of candidates) {
- const exact = entries.find((e) => normalizePathLike(String(e.name || "")).toLowerCase() === want.toLowerCase())
- if (exact) return exact
- const suffix = `/${want.toLowerCase()}`
- const bySuffix = entries.find((e) => normalizePathLike(String(e.name || "")).toLowerCase().endsWith(suffix))
- if (bySuffix) return bySuffix
- }
- return null
-}
-
-const extractLatexCaptionNear = (tex: string, matchIndex: number) => {
- const windowStart = Math.max(0, matchIndex - 1200)
- const windowEnd = Math.min(tex.length, matchIndex + 2400)
- const window = tex.slice(windowStart, windowEnd)
- const cap = window.match(/\\caption(?:\[[^\]]*\])?\{([\s\S]*?)\}/)
- if (cap && cap[1]) return stripLatexToText(cap[1]).slice(0, 220)
- return ""
-}
-
-export async function extractLatexZipText(file: File): Promise<string> {
- const buffer = await file.arrayBuffer()
- const zip = await JSZip.loadAsync(buffer)
- const main = pickMainTexEntry(zip)
- if (!main) throw new Error("No .tex file found in zip")
- const texMap = await buildTexMapFromZip(zip)
- const root = normalizePathLike(String(main.name || ""))
- const { mergedText } = collectLatexGraphicsFromMap(root, texMap)
- return stripLatexToText(mergedText || (await main.async("string")))
-}
-
-export async function extractLatexZipVisualAssets(
- file: File,
- options?: { maxAssets?: number }
-): Promise<ExtractedVisualAsset[]> {
- const maxAssets = Math.max(1, options?.maxAssets ?? 12)
- const buffer = await file.arrayBuffer()
- const zip = await JSZip.loadAsync(buffer)
- const main = pickMainTexEntry(zip)
- if (!main) return []
- const texMap = await buildTexMapFromZip(zip)
- const root = normalizePathLike(String(main.name || ""))
- let { graphics } = collectLatexGraphicsFromMap(root, texMap)
- if (graphics.length === 0) {
- for (const texPath of texMap.keys()) {
- const hit = collectLatexGraphicsFromMap(texPath, texMap).graphics
- if (hit.length > 0) {
- graphics = hit
- break
- }
- }
- }
- const assets: ExtractedVisualAsset[] = []
- let order = 0
- for (const g of graphics) {
- if (assets.length >= maxAssets) break
- const entry =
- resolveZipEntryForGraphicFromTex(zip, g.sourceTexPath, g.includePath, g.searchDirs) ||
- resolveZipEntryForGraphic(zip, g.includePath)
- if (!entry) continue
- const bytes = await entry.async("uint8array")
- const dataUrl = await latexAssetBytesToDataUrl(entry.name, bytes)
- if (!dataUrl.startsWith("data:image")) continue
- order += 1
- const caption = String(g.caption || "").trim()
- const hint = caption ? `LaTeX caption: ${caption}` : `LaTeX includegraphics: ${g.includePath}`
- assets.push({
- id: `latex-${file.name}-${order}`,
- sourceFileName: file.name,
- sourceType: "latex",
- order,
- dataUrl,
- textHint: hint.slice(0, 800),
- })
- }
- return assets
-}
-
-export async function extractLatexTarGzText(file: File): Promise<string> {
- const buffer = await file.arrayBuffer()
- const tarBytes = ungzip(new Uint8Array(buffer))
- const entries = parseTarEntries(tarBytes)
- const main = pickMainTexFromEntries(entries)
- if (!main) throw new Error("No .tex file found in tar.gz")
- const texMap = buildTexMapFromEntries(entries)
- const root = normalizePathLike(String(main.name || ""))
- const { mergedText } = collectLatexGraphicsFromMap(root, texMap)
- return stripLatexToText(mergedText || new TextDecoder("utf-8").decode(main.bytes))
-}
-
-export async function extractLatexTarGzVisualAssets(
- file: File,
- options?: { maxAssets?: number }
-): Promise<ExtractedVisualAsset[]> {
- const maxAssets = Math.max(1, options?.maxAssets ?? 12)
- const buffer = await file.arrayBuffer()
- const tarBytes = ungzip(new Uint8Array(buffer))
- const entries = parseTarEntries(tarBytes)
- const main = pickMainTexFromEntries(entries)
- if (!main) return []
- const texMap = buildTexMapFromEntries(entries)
- const root = normalizePathLike(String(main.name || ""))
- let { graphics } = collectLatexGraphicsFromMap(root, texMap)
- if (graphics.length === 0) {
- for (const texPath of texMap.keys()) {
- const hit = collectLatexGraphicsFromMap(texPath, texMap).graphics
- if (hit.length > 0) {
- graphics = hit
- break
- }
- }
- }
- const assets: ExtractedVisualAsset[] = []
- let order = 0
- for (const g of graphics) {
- if (assets.length >= maxAssets) break
- const entry =
- resolveArchiveEntryForGraphicFromTex(entries, g.sourceTexPath, g.includePath, g.searchDirs) ||
- resolveArchiveEntryForGraphic(entries, g.includePath)
- if (!entry) continue
- const dataUrl = await latexAssetBytesToDataUrl(entry.name, entry.bytes)
- if (!dataUrl.startsWith("data:image")) continue
- order += 1
- const caption = String(g.caption || "").trim()
- const hint = caption ? `LaTeX caption: ${caption}` : `LaTeX includegraphics: ${g.includePath}`
- assets.push({
- id: `latex-tgz-${file.name}-${order}`,
- sourceFileName: file.name,
- sourceType: "latex",
- order,
- dataUrl,
- textHint: hint.slice(0, 800),
- })
- }
- return assets
-}
-
-export interface ExtractedVisualAsset {
- id: string
- sourceFileName: string
- sourceType: "pdf" | "word" | "latex" | "third_party"
- page?: number
- order: number
- dataUrl: string
- textHint: string
-}
type PdfTextBox = { text: string; x: number; y: number; w: number; h: number }
type RegionBox = { x: number; y: number; w: number; h: number }
type PdfTextLine = { text: string; x: number; y: number; w: number; h: number }
-type VisualCategory =
- | "framework"
- | "result_table"
- | "mechanism"
- | "key_visual"
- | "data_structure"
- | "other"
-
const USEFUL_VISUAL_PATTERNS = [
/(framework|pipeline|workflow|architecture|system diagram|method overview|flowchart|block diagram|methods?|approach|methodology|方法框架|流程图|系统结构|模型架构)/i,
/(table\s*\d+|main results|comparison|baseline|sota|significance|accuracy|f1|auc|results table|主实验|结果对比|对比表|显著性|表\s*\d+)/i,
@@ -642,69 +59,6 @@ const CATEGORY_PATTERNS: Array<{ category: VisualCategory; re: RegExp[] }> = [
]
const clamp = (v: number, min: number, max: number) => Math.max(min, Math.min(max, v))
-const bytesToBase64 = (bytes: Uint8Array) => {
- let binary = ""
- const chunk = 0x8000
- for (let i = 0; i < bytes.length; i += chunk) {
- binary += String.fromCharCode(...bytes.subarray(i, i + chunk))
- }
- return btoa(binary)
-}
-
-const getMimeByExt = (name: string) => {
- const n = String(name || "").toLowerCase()
- if (n.endsWith(".png")) return "image/png"
- if (n.endsWith(".jpg") || n.endsWith(".jpeg")) return "image/jpeg"
- if (n.endsWith(".webp")) return "image/webp"
- if (n.endsWith(".gif")) return "image/gif"
- if (n.endsWith(".bmp")) return "image/bmp"
- if (n.endsWith(".svg")) return "image/svg+xml"
- return "image/png"
-}
-
-const latexAssetBytesToDataUrl = async (name: string, bytes: Uint8Array) => {
- const n = String(name || "").toLowerCase()
- if (n.endsWith(".pdf")) {
- try {
- const pdf = await getDocumentProxy(bytes)
- const page = await (pdf as any).getPage(1)
- const viewport1 = page.getViewport({ scale: 1 })
- const scale = 1400 / Math.max(1, viewport1.width)
- const viewport = page.getViewport({ scale })
- const canvas = document.createElement("canvas")
- canvas.width = Math.max(1, Math.floor(viewport.width))
- canvas.height = Math.max(1, Math.floor(viewport.height))
- const ctx = canvas.getContext("2d")
- if (!ctx) return ""
- await page.render({ canvasContext: ctx, viewport }).promise
- return canvas.toDataURL("image/png")
- } catch {
- return ""
- }
- }
- const mime = getMimeByExt(name)
- return `data:${mime};base64,${bytesToBase64(bytes)}`
-}
-
-const decodeXmlText = (raw: string) => {
- const s = String(raw || "")
- return s
- .replace(/&lt;/g, "<")
- .replace(/&gt;/g, ">")
- .replace(/&quot;/g, '"')
- .replace(/&apos;/g, "'")
- .replace(/&amp;/g, "&")
- .replace(/&#(\d+);/g, (_, n) => {
- const code = Number(n)
- if (!Number.isFinite(code)) return ""
- try {
- return String.fromCharCode(code)
- } catch {
- return ""
- }
- })
-}
-
const renderPdfPageCanvas = async (page: any, targetWidth = 980) => {
const viewportAtScale1 = page.getViewport({ scale: 1 })
const scale = targetWidth / Math.max(1, viewportAtScale1.width)
@@ -1518,5 +872,3 @@ export async function extractThirdPartyVisualAssets(
textHint: typeof x.textHint === "string" ? x.textHint : "",
}))
}
-
-
diff --git a/src/shared/i18n/index.ts b/src/shared/i18n/index.ts
new file mode 100644
index 0000000..1e2bcac
--- /dev/null
+++ b/src/shared/i18n/index.ts
@@ -0,0 +1,3 @@
+export * from "@/shared/i18n/language";
+export * from "@/shared/i18n/translator";
+export * from "@/shared/i18n/messages";
diff --git a/src/lib/ui-language.ts b/src/shared/i18n/language.ts
similarity index 63%
rename from src/lib/ui-language.ts
rename to src/shared/i18n/language.ts
index de63fa8..1e5e092 100644
--- a/src/lib/ui-language.ts
+++ b/src/shared/i18n/language.ts
@@ -1,3 +1,10 @@
+import { useEffect, useState } from "react";
+
+/**
+ * The interface language, stored once and broadcast on change so every
+ * component -- context-wrapped or not -- can react without prop drilling.
+ */
+
export type UiLanguage = "zh" | "en";
const UI_LANG_STORAGE_KEY = "CanvasAnvil-ui-lang-v1";
@@ -34,3 +41,15 @@ export function resolveResponseLanguage(args: { userText: string; uiLang: UiLang
return detectLanguageFromText(args.userText) || args.uiLang;
}
+/** Subscribes to the change event above; use inside components. */
+export function useUiLanguage() {
+ const [uiLang, setUiLang] = useState<UiLanguage>(() => getUiLanguage());
+
+ useEffect(() => {
+ const onLang = () => setUiLang(getUiLanguage());
+ window.addEventListener("ui-language-changed", onLang as any);
+ return () => window.removeEventListener("ui-language-changed", onLang as any);
+ }, []);
+
+ return uiLang;
+}
diff --git a/src/lib/i18n.ts b/src/shared/i18n/messages.ts
similarity index 61%
rename from src/lib/i18n.ts
rename to src/shared/i18n/messages.ts
index c87c908..a14415d 100644
--- a/src/lib/i18n.ts
+++ b/src/shared/i18n/messages.ts
@@ -1,14 +1,11 @@
-import { getUiLanguage, type UiLanguage } from "@/lib/ui-language";
+import { createTranslator, type Dict } from "@/shared/i18n/translator";
-type Dict = Record<string, { zh: string; en: string }>;
-
-const dict: Dict = {
+/** Strings for the app shell and the CAD / PPT workspaces. */
+const messages = {
"app.refresh": { zh: "刷新页面", en: "Refresh" },
"app.tryContinue": { zh: "尝试继续", en: "Try to continue" },
- "chat.hello": { zh: "你好!我是你的 AI 助手。请告诉我你的需求。", en: "Hi! I'm your AI assistant. Tell me what you need." },
"chat.newChat": { zh: "你好!新对话已开始。请告诉我你的需求。", en: "Hi! New chat started. Tell me what you need." },
- "chat.cleared": { zh: "你好!对话记录已清空。", en: "Hi! Chat history has been cleared." },
"common.cancel": { zh: "取消", en: "Cancel" },
"common.save": { zh: "保存", en: "Save" },
@@ -20,8 +17,6 @@ const dict: Dict = {
"settings.language.zh": { zh: "中文", en: "Chinese" },
"settings.language.en": { zh: "英文", en: "English" },
"settings.buttonTitle": { zh: "设置", en: "Settings" },
- "settings.chatModel": { zh: "对话模型 (Chat Model)", en: "Chat Model" },
- "settings.imageModel": { zh: "绘图模型 (Image Model)", en: "Image Model" },
"reset.title": { zh: "清空对话", en: "Clear Chat" },
"reset.desc": {
@@ -29,8 +24,6 @@ const dict: Dict = {
en: "Clearing chat will also clear the current workspace content. This action cannot be undone. The PPT workspace will return to the start page.",
},
- "workspace.flow.title": { zh: "流程图助手", en: "Flow Assistant" },
- "workspace.flow.placeholder": { zh: "描述流程…", en: "Describe the flow…" },
"workspace.cad.title": { zh: "CAD 助手", en: "CAD Assistant" },
"workspace.cad.placeholder": { zh: "描述 CAD…", en: "Describe the CAD…" },
"workspace.ppt.title": { zh: "PPT 助手", en: "PPT Assistant" },
@@ -41,10 +34,7 @@ const dict: Dict = {
"chat.send": { zh: "发送", en: "Send" },
"chat.uploadFile": { zh: "上传文件", en: "Upload file" },
"chat.uploadImage": { zh: "上传图片", en: "Upload image" },
- "chat.rules": { zh: "规则", en: "Rules" },
"chat.expand": { zh: "展开聊天", en: "Expand chat" },
- "chat.globalConstraints": { zh: "全局约束", en: "Global constraints" },
- "chat.newChatTitle": { zh: "新开对话", en: "New chat" },
"chat.historyTitle": { zh: "版本历史", en: "History" },
"chat.clearChatTitle": { zh: "清空对话", en: "Clear chat" },
"chat.collapseLocked": { zh: "PPT 生成完成前不能收起聊天", en: "Chat cannot be collapsed while PPT is generating" },
@@ -54,11 +44,6 @@ const dict: Dict = {
"nav.cad": { zh: "室内设计", en: "CAD" },
"nav.ppt": { zh: "PPT演示", en: "PPT" },
- "flow.addToChat": { zh: "添加到对话", en: "Add to chat" },
- "flow.addToChat.tooltip": { zh: "将当前图表添加到对话", en: "Add current diagram to chat" },
- "flow.saving": { zh: "保存中...", en: "Saving..." },
- "flow.updatingChat": { zh: "更新对话中...", en: "Updating chat..." },
- "flow.editorTitle": { zh: "流程图编辑器", en: "Flowchart Editor" },
"history.title": { zh: "版本历史", en: "Version History" },
"history.clear": { zh: "清空", en: "Clear" },
@@ -70,25 +55,8 @@ const dict: Dict = {
"constraints.desc": { zh: "设置适用于当前工作区的全局系统提示词。", en: "Set global system instructions for the current workspace." },
"constraints.placeholder": { zh: "例如:始终使用中文回答,代码注释必须详细...", en: "e.g. Always respond in English. Code comments must be detailed..." },
- "saveDialog.title": { zh: "保存图表", en: "Save Diagram" },
- "saveDialog.filename": { zh: "文件名", en: "Filename" },
- "saveDialog.format": { zh: "格式", en: "Format" },
- "saveDialog.chooseFormat": { zh: "选择格式", en: "Choose format" },
"error.missingApiKey": { zh: "请先在设置中配置 API Key", en: "Please configure an API key in Settings first." },
-};
-
-export function t(lang: UiLanguage, key: string, vars?: Record<string, string | number>) {
- const entry = dict[key];
- const template = entry ? entry[lang] : key;
- if (!vars) return template;
- let out = template;
- for (const [k, v] of Object.entries(vars)) {
- out = out.split(`{{${k}}}`).join(String(v));
- }
- return out;
-}
+} satisfies Dict;
-export function tAuto(key: string, vars?: Record<string, string | number>) {
- return t(getUiLanguage(), key, vars);
-}
+export const { t, translate: tAuto, useT } = createTranslator(messages);
diff --git a/src/shared/i18n/translator.ts b/src/shared/i18n/translator.ts
new file mode 100644
index 0000000..fd5e5d8
--- /dev/null
+++ b/src/shared/i18n/translator.ts
@@ -0,0 +1,41 @@
+import { getUiLanguage, useUiLanguage, type UiLanguage } from "@/shared/i18n/language";
+
+/**
+ * One translation mechanism, many dictionaries.
+ *
+ * The app shell and each workspace own their own strings — the same key means
+ * different things in different places ("history.title" is "Version History"
+ * in the shell and "Diagram History" in Flow) — but they all look those
+ * strings up the same way and follow the same language setting.
+ */
+
+export type Dict = Record<string, Record<UiLanguage, string>>;
+
+/** Substitutes `{{name}}` placeholders; an unknown key falls back to itself. */
+function format(template: string, vars?: Record<string, string | number>) {
+ if (!vars) return template;
+ let out = template;
+ for (const [name, value] of Object.entries(vars)) {
+ out = out.split(`{{${name}}}`).join(String(value));
+ }
+ return out;
+}
+
+export function createTranslator<D extends Dict>(dict: D) {
+ type Key = Extract<keyof D, string>;
+
+ /** Explicit language — for code outside React, or where the language is already known. */
+ const t = (lang: UiLanguage, key: Key, vars?: Record<string, string | number>) =>
+ format(dict[key]?.[lang] ?? key, vars);
+
+ /** Current language, read from storage. */
+ const translate = (key: Key, vars?: Record<string, string | number>) => t(getUiLanguage(), key, vars);
+
+ /** Current language, re-rendering when the user switches it. */
+ const useT = () => {
+ const lang = useUiLanguage();
+ return (key: Key, vars?: Record<string, string | number>) => t(lang, key, vars);
+ };
+
+ return { t, translate, useT };
+}
diff --git a/src/lib/utils.ts b/src/shared/lib/utils.ts
similarity index 100%
rename from src/lib/utils.ts
rename to src/shared/lib/utils.ts
diff --git a/src/shared/storage/indexed-db-store.ts b/src/shared/storage/indexed-db-store.ts
new file mode 100644
index 0000000..52c923f
--- /dev/null
+++ b/src/shared/storage/indexed-db-store.ts
@@ -0,0 +1,78 @@
+/**
+ * A tiny key/value store on top of IndexedDB.
+ *
+ * Workspaces persist things too big for localStorage — generated images,
+ * slide decks, render bundles. Each workspace gets its own database so
+ * clearing one never touches another; the shape is otherwise identical, which
+ * is why this is a factory rather than a module per workspace.
+ */
+
+const STORE_NAME = "workspace";
+const DB_VERSION = 1;
+
+export interface WorkspaceStore {
+ read<T = unknown>(key: string): Promise<T | null>;
+ save<T>(key: string, value: T): Promise<void>;
+ clear(key: string): Promise<void>;
+}
+
+export function createWorkspaceStore(databaseName: string): WorkspaceStore {
+ /** Resolves to null where IndexedDB is unavailable, so callers degrade to no persistence. */
+ function open(): Promise<IDBDatabase | null> {
+ if (typeof indexedDB === "undefined") return Promise.resolve(null);
+
+ return new Promise((resolve, reject) => {
+ const request = indexedDB.open(databaseName, DB_VERSION);
+ request.onupgradeneeded = () => {
+ const db = request.result;
+ if (!db.objectStoreNames.contains(STORE_NAME)) {
+ db.createObjectStore(STORE_NAME);
+ }
+ };
+ request.onsuccess = () => resolve(request.result);
+ request.onerror = () => reject(request.error);
+ });
+ }
+
+ /** Runs one transaction and closes the connection, whatever the outcome. */
+ async function transact<T>(
+ mode: IDBTransactionMode,
+ run: (store: IDBObjectStore, resolve: (value: T) => void) => void,
+ ): Promise<T | null> {
+ const db = await open();
+ if (!db) return null;
+
+ return await new Promise<T | null>((resolve, reject) => {
+ const tx = db.transaction(STORE_NAME, mode);
+ let result: T | null = null;
+ run(tx.objectStore(STORE_NAME), (value) => {
+ result = value;
+ });
+ tx.oncomplete = () => {
+ db.close();
+ resolve(result);
+ };
+ tx.onabort = () => reject(tx.error);
+ tx.onerror = () => reject(tx.error);
+ });
+ }
+
+ return {
+ async read<T = unknown>(key: string) {
+ return await transact<T>("readonly", (store, resolve) => {
+ const request = store.get(key);
+ request.onsuccess = () => resolve((request.result as T | undefined) ?? null);
+ });
+ },
+ async save<T>(key: string, value: T) {
+ await transact<void>("readwrite", (store) => {
+ store.put(value, key);
+ });
+ },
+ async clear(key: string) {
+ await transact<void>("readwrite", (store) => {
+ store.delete(key);
+ });
+ },
+ };
+}
diff --git a/src/workspaces/ppt/ui/button.tsx b/src/shared/ui/button.tsx
similarity index 98%
rename from src/workspaces/ppt/ui/button.tsx
rename to src/shared/ui/button.tsx
index 5467ec1..4df27c7 100644
--- a/src/workspaces/ppt/ui/button.tsx
+++ b/src/shared/ui/button.tsx
@@ -2,7 +2,7 @@ import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
-import { cn } from "@/lib/utils"
+import { cn } from "@/shared/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
@@ -53,7 +53,6 @@ const Button = React.forwardRef<
/>
)
})
-
Button.displayName = "Button"
export { Button, buttonVariants }
diff --git a/src/workspaces/cad/ui/collapsible.tsx b/src/shared/ui/collapsible.tsx
similarity index 100%
rename from src/workspaces/cad/ui/collapsible.tsx
rename to src/shared/ui/collapsible.tsx
diff --git a/src/workspaces/cad/ui/context-menu.tsx b/src/shared/ui/context-menu.tsx
similarity index 99%
rename from src/workspaces/cad/ui/context-menu.tsx
rename to src/shared/ui/context-menu.tsx
index 3e52999..886acb7 100644
--- a/src/workspaces/cad/ui/context-menu.tsx
+++ b/src/shared/ui/context-menu.tsx
@@ -2,7 +2,7 @@ import * as React from "react"
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
import { Check, ChevronRight, Circle } from "lucide-react"
-import { cn } from "@/lib/utils"
+import { cn } from "@/shared/lib/utils"
const ContextMenu = ContextMenuPrimitive.Root
diff --git a/src/workspaces/cad/ui/dialog.tsx b/src/shared/ui/dialog.tsx
similarity index 98%
rename from src/workspaces/cad/ui/dialog.tsx
rename to src/shared/ui/dialog.tsx
index d8d3b56..306af4b 100644
--- a/src/workspaces/cad/ui/dialog.tsx
+++ b/src/shared/ui/dialog.tsx
@@ -4,8 +4,8 @@ import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
-import { cn } from "@/lib/utils"
-import { useUiLanguage } from "@/lib/use-ui-language"
+import { cn } from "@/shared/lib/utils"
+import { useUiLanguage } from "@/shared/i18n"
function Dialog({
...props
diff --git a/src/workspaces/flow/next/components/ui/input.tsx b/src/shared/ui/input.tsx
similarity index 91%
rename from src/workspaces/flow/next/components/ui/input.tsx
rename to src/shared/ui/input.tsx
index 5d06607..f8d3e05 100644
--- a/src/workspaces/flow/next/components/ui/input.tsx
+++ b/src/shared/ui/input.tsx
@@ -1,6 +1,6 @@
-import * as React from "react"
+import * as React from "react"
-import { cn } from "@/workspaces/flow/next/lib/utils"
+import { cn } from "@/shared/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
diff --git a/src/workspaces/flow/next/components/ui/label.tsx b/src/shared/ui/label.tsx
similarity index 88%
rename from src/workspaces/flow/next/components/ui/label.tsx
rename to src/shared/ui/label.tsx
index 3da1370..cfaac59 100644
--- a/src/workspaces/flow/next/components/ui/label.tsx
+++ b/src/shared/ui/label.tsx
@@ -1,9 +1,9 @@
-"use client"
+"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
-import { cn } from "@/workspaces/flow/next/lib/utils"
+import { cn } from "@/shared/lib/utils"
function Label({
className,
diff --git a/src/workspaces/flow/next/components/ui/resizable.tsx b/src/shared/ui/resizable.tsx
similarity index 97%
rename from src/workspaces/flow/next/components/ui/resizable.tsx
rename to src/shared/ui/resizable.tsx
index 73c6e45..193173f 100644
--- a/src/workspaces/flow/next/components/ui/resizable.tsx
+++ b/src/shared/ui/resizable.tsx
@@ -1,7 +1,7 @@
import { GripVertical } from "lucide-react"
import { Panel, Group, Separator, type PanelImperativeHandle } from "react-resizable-panels"
-import { cn } from "@/lib/utils"
+import { cn } from "@/shared/lib/utils"
const ResizablePanelGroup = ({
className,
diff --git a/src/workspaces/ppt/ui/scroll-area.tsx b/src/shared/ui/scroll-area.tsx
similarity index 97%
rename from src/workspaces/ppt/ui/scroll-area.tsx
rename to src/shared/ui/scroll-area.tsx
index 677c344..e7acf53 100644
--- a/src/workspaces/ppt/ui/scroll-area.tsx
+++ b/src/shared/ui/scroll-area.tsx
@@ -3,7 +3,7 @@
import * as React from "react"
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
-import { cn } from "@/lib/utils"
+import { cn } from "@/shared/lib/utils"
function ScrollArea({
className,
diff --git a/src/workspaces/flow/next/components/ui/select.tsx b/src/shared/ui/select.tsx
similarity index 98%
rename from src/workspaces/flow/next/components/ui/select.tsx
rename to src/shared/ui/select.tsx
index e03a8fe..a1aad3e 100644
--- a/src/workspaces/flow/next/components/ui/select.tsx
+++ b/src/shared/ui/select.tsx
@@ -1,10 +1,10 @@
-"use client"
+"use client"
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
-import { cn } from "@/workspaces/flow/next/lib/utils"
+import { cn } from "@/shared/lib/utils"
function Select({
...props
diff --git a/src/workspaces/flow/next/components/ui/switch.tsx b/src/shared/ui/switch.tsx
similarity index 94%
rename from src/workspaces/flow/next/components/ui/switch.tsx
rename to src/shared/ui/switch.tsx
index cab365c..b6b697c 100644
--- a/src/workspaces/flow/next/components/ui/switch.tsx
+++ b/src/shared/ui/switch.tsx
@@ -1,9 +1,9 @@
-"use client"
+"use client"
import * as React from "react"
import * as SwitchPrimitive from "@radix-ui/react-switch"
-import { cn } from "@/workspaces/flow/next/lib/utils"
+import { cn } from "@/shared/lib/utils"
function Switch({
className,
diff --git a/src/workspaces/cad/ui/textarea.tsx b/src/shared/ui/textarea.tsx
similarity index 94%
rename from src/workspaces/cad/ui/textarea.tsx
rename to src/shared/ui/textarea.tsx
index f2ab8f2..da047db 100644
--- a/src/workspaces/cad/ui/textarea.tsx
+++ b/src/shared/ui/textarea.tsx
@@ -1,6 +1,6 @@
import * as React from "react"
-import { cn } from "@/lib/utils"
+import { cn } from "@/shared/lib/utils"
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
diff --git a/src/shared/ui/tooltip.tsx b/src/shared/ui/tooltip.tsx
new file mode 100644
index 0000000..f014f37
--- /dev/null
+++ b/src/shared/ui/tooltip.tsx
@@ -0,0 +1,57 @@
+"use client"
+
+import * as React from "react"
+import * as TooltipPrimitive from "@radix-ui/react-tooltip"
+
+import { cn } from "@/shared/lib/utils"
+
+function TooltipProvider({
+ delayDuration = 0,
+ ...props
+}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
+ return (
+ <TooltipPrimitive.Provider
+ data-slot="tooltip-provider"
+ delayDuration={delayDuration}
+ {...props}
+ />
+ )
+}
+
+/**
+ * Wraps its own provider so a tooltip works wherever it is dropped. Nesting a
+ * second provider is harmless, so an outer app-level one stays valid.
+ */
+function Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root>) {
+ return (
+ <TooltipProvider>
+ <TooltipPrimitive.Root data-slot="tooltip" {...props} />
+ </TooltipProvider>
+ )
+}
+
+const TooltipTrigger = TooltipPrimitive.Trigger
+
+const TooltipContent = React.forwardRef<
+ React.ElementRef<typeof TooltipPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
+>(({ className, sideOffset = 4, children, ...props }, ref) => (
+ <TooltipPrimitive.Portal>
+ <TooltipPrimitive.Content
+ ref={ref}
+ data-slot="tooltip-content"
+ sideOffset={sideOffset}
+ className={cn(
+ "bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
+ </TooltipPrimitive.Content>
+ </TooltipPrimitive.Portal>
+))
+TooltipContent.displayName = TooltipPrimitive.Content.displayName
+
+export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
diff --git a/src/workspaces/cad/CadWorkspaceShell.tsx b/src/workspaces/cad/CadWorkspaceShell.tsx
index 20dbbd3..7e1e818 100644
--- a/src/workspaces/cad/CadWorkspaceShell.tsx
+++ b/src/workspaces/cad/CadWorkspaceShell.tsx
@@ -1,20 +1,15 @@
import React, { useEffect, useRef, useState } from "react";
import { toast } from "sonner";
-import { cn } from "@/lib/utils";
-import { t } from "@/lib/i18n";
-import { useUiLanguage } from "@/lib/use-ui-language";
+import { cn } from "@/shared/lib/utils";
+import { t, useUiLanguage } from "@/shared/i18n";
import { getCadRenderFallbackTitle } from "@/lib/cad-render-titles";
-import {
- clearPersistedCadWorkspaceItem,
- readPersistedCadWorkspaceItem,
- savePersistedCadWorkspaceItem,
-} from "@/lib/cad-persistence";
+import { CAD_ANALYSIS_IMAGES_KEY, CAD_RENDERS_KEY, cadStore } from "@/workspaces/cad/storage";
import {
ResizableHandle,
ResizablePanel,
ResizablePanelGroup,
type PanelImperativeHandle,
-} from "@/workspaces/cad/ui/resizable";
+} from "@/shared/ui/resizable";
import { CAD_SYSTEM_PROMPT } from "@/lib/system-prompts";
import type { ChatMessage } from "@/ai/client";
import { generateImage } from "@/ai/client";
@@ -34,8 +29,6 @@ const CAD_WORKSPACE_STORAGE_KEY = "CanvasAnvil-cad-state-v1";
const CAD_RENDERS_STORAGE_KEY = "CanvasAnvil-cad-renders-v1";
const CAD_ANALYSIS_IMAGES_STORAGE_KEY = "CanvasAnvil-cad-analysis-images-v1";
const CAD_CHAT_STORAGE_KEY = "chat_history_v2_cad";
-const CAD_PERSISTED_RENDERS_KEY = "renders";
-const CAD_PERSISTED_ANALYSIS_IMAGES_KEY = "analysis-images";
const tryParseJson = (text: string) => {
try {
@@ -315,8 +308,8 @@ export function CadWorkspaceShell() {
void (async () => {
try {
const [persistedRenders, persistedAnalysisImages] = await Promise.all([
- readPersistedCadWorkspaceItem<CadRenderItem[]>(CAD_PERSISTED_RENDERS_KEY),
- readPersistedCadWorkspaceItem<CadRenderItem[]>(CAD_PERSISTED_ANALYSIS_IMAGES_KEY),
+ cadStore.read<CadRenderItem[]>(CAD_RENDERS_KEY),
+ cadStore.read<CadRenderItem[]>(CAD_ANALYSIS_IMAGES_KEY),
]);
if (cancelled) return;
@@ -371,7 +364,7 @@ export function CadWorkspaceShell() {
const stable = normalizeCadRenderItems(cadImages, { allowBlob: false, max: 30 });
if (stable.length > 0) {
cadStableImagesRef.current = stable;
- void savePersistedCadWorkspaceItem(CAD_PERSISTED_RENDERS_KEY, stable).catch((e) => {
+ void cadStore.save(CAD_RENDERS_KEY, stable).catch((e) => {
console.error("Failed to persist CAD render images", e);
});
try {
@@ -388,7 +381,7 @@ export function CadWorkspaceShell() {
const stable = normalizeCadRenderItems(cadAnalysisImages, { allowBlob: false, max: 2 });
if (stable.length > 0) {
cadStableAnalysisImagesRef.current = stable;
- void savePersistedCadWorkspaceItem(CAD_PERSISTED_ANALYSIS_IMAGES_KEY, stable).catch((e) => {
+ void cadStore.save(CAD_ANALYSIS_IMAGES_KEY, stable).catch((e) => {
console.error("Failed to persist CAD analysis images", e);
});
try {
@@ -1004,8 +997,8 @@ export function CadWorkspaceShell() {
} catch {
}
void Promise.all([
- clearPersistedCadWorkspaceItem(CAD_PERSISTED_RENDERS_KEY),
- clearPersistedCadWorkspaceItem(CAD_PERSISTED_ANALYSIS_IMAGES_KEY),
+ cadStore.clear(CAD_RENDERS_KEY),
+ cadStore.clear(CAD_ANALYSIS_IMAGES_KEY),
]).catch((e) => {
console.error("Failed to clear persisted CAD images", e);
});
diff --git a/src/workspaces/cad/chat/ChatInput.tsx b/src/workspaces/cad/chat/ChatInput.tsx
index cc12f64..4280b8e 100644
--- a/src/workspaces/cad/chat/ChatInput.tsx
+++ b/src/workspaces/cad/chat/ChatInput.tsx
@@ -1,11 +1,10 @@
import React, { useRef, useEffect, useMemo, useState, useCallback } from 'react';
import { Send, FileText, ImageIcon, History, Square, Trash2 } from 'lucide-react';
-import { cn } from '@/lib/utils';
+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 '@/lib/use-file-processor';
-import { t } from "@/lib/i18n";
-import { useUiLanguage } from "@/lib/use-ui-language";
+import { useFileProcessor } from '@/shared/files/use-file-processor';
+import { t, useUiLanguage } from "@/shared/i18n";
type RichInputSegment =
| { type: "text"; text: string }
@@ -66,7 +65,7 @@ export function ChatInput({
const richAppliedRef = useRef<string>("");
const [richHasFocus, setRichHasFocus] = useState(false);
- const { files, handleFileChange, setFiles, pdfData } = useFileProcessor();
+ const { files, handleFileChange, setFiles, pdfData } = useFileProcessor("cad");
const isRich = !!(richSegments && onRichSegmentsChange);
// Sync controlled files if provided
diff --git a/src/workspaces/cad/chat/ChatMessageDisplay.tsx b/src/workspaces/cad/chat/ChatMessageDisplay.tsx
index 283d85b..78c3260 100644
--- a/src/workspaces/cad/chat/ChatMessageDisplay.tsx
+++ b/src/workspaces/cad/chat/ChatMessageDisplay.tsx
@@ -20,10 +20,10 @@ import {
import ReactMarkdown from "react-markdown";
import remarkGfm from 'remark-gfm';
import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/workspaces/cad/chat/components/reasoning";
-import { ScrollArea } from "@/workspaces/cad/ui/scroll-area";
-import { CodeBlock } from "@/workspaces/cad/ui/code-block";
-import { useUiLanguage } from "@/lib/use-ui-language";
-import { cn } from "@/lib/utils";
+import { ScrollArea } from "@/shared/ui/scroll-area";
+import { CodeBlock } from "@/workspaces/cad/chat/code-block";
+import { useUiLanguage } from "@/shared/i18n";
+import { cn } from "@/shared/lib/utils";
// Types
export interface MessagePart {
diff --git a/src/workspaces/cad/chat/ChatPanel.tsx b/src/workspaces/cad/chat/ChatPanel.tsx
index 59575a3..e642444 100644
--- a/src/workspaces/cad/chat/ChatPanel.tsx
+++ b/src/workspaces/cad/chat/ChatPanel.tsx
@@ -1,6 +1,6 @@
import React, { useState, useRef, useEffect } from 'react';
import { PanelRightClose, PanelRightOpen } from 'lucide-react';
-import { cn } from '@/lib/utils';
+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';
@@ -9,7 +9,7 @@ import { ChatMessageDisplay, UIMessage } from '@/workspaces/cad/chat/ChatMessage
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 { useFileProcessor } from '@/lib/use-file-processor';
+import { useFileProcessor } from '@/shared/files/use-file-processor';
import {
buildCadAnalysisMessages,
buildCadBomMessages,
@@ -26,8 +26,7 @@ import {
import { getCadRenderFallbackTitle, getCadRenderSlotTitles } from "@/lib/cad-render-titles";
import flowPatchAgentPrompt from "../../../../agent/flow/patch.md?raw";
import flowReplaceAgentPrompt from "../../../../agent/flow/replace.md?raw";
-import { t } from "@/lib/i18n";
-import { useUiLanguage } from "@/lib/use-ui-language";
+import { t, useUiLanguage } from "@/shared/i18n";
import { toast } from "sonner";
interface Attachment {
@@ -1127,12 +1126,12 @@ export function ChatPanel({
}
} else {
// Text/PDF
- const { extractPdfText, extractTextFileContent, isPdfFile } = await import('@/lib/pdf-utils');
+ const { extractPdfText, extractTextFileContent, isPdfFile } = await import('@/shared/files');
try {
let content = "";
if (isPdfFile(file)) {
try {
- const { getPdfDocumentFromUrl, renderPdfPageToCanvas } = await import("@/lib/pdf-utils");
+ const { getPdfDocumentFromUrl, renderPdfPageToCanvas } = await import("@/shared/files");
const objectUrl = URL.createObjectURL(file);
try {
const pdf = await getPdfDocumentFromUrl(objectUrl);
diff --git a/src/workspaces/cad/ui/code-block.tsx b/src/workspaces/cad/chat/code-block.tsx
similarity index 99%
rename from src/workspaces/cad/ui/code-block.tsx
rename to src/workspaces/cad/chat/code-block.tsx
index fd508d3..1d98f2c 100644
--- a/src/workspaces/cad/ui/code-block.tsx
+++ b/src/workspaces/cad/chat/code-block.tsx
@@ -1,7 +1,7 @@
import React, { useMemo, useState } from "react";
import { Check, ChevronDown, ChevronUp, Copy, Cpu, Play, X } from "lucide-react";
import { Highlight, themes, type Language } from "prism-react-renderer";
-import { useUiLanguage } from "@/lib/use-ui-language";
+import { useUiLanguage } from "@/shared/i18n";
interface CodeBlockProps {
code: string;
diff --git a/src/workspaces/cad/chat/components/button-with-tooltip.tsx b/src/workspaces/cad/chat/components/button-with-tooltip.tsx
index 6d31a3c..0acd1c4 100644
--- a/src/workspaces/cad/chat/components/button-with-tooltip.tsx
+++ b/src/workspaces/cad/chat/components/button-with-tooltip.tsx
@@ -1,12 +1,12 @@
import type { VariantProps } from "class-variance-authority"
import type React from "react"
-import { Button, type buttonVariants } from "@/workspaces/cad/ui/button"
+import { Button, type buttonVariants } from "@/shared/ui/button"
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
-} from "@/workspaces/cad/ui/tooltip"
+} from "@/shared/ui/tooltip"
interface ButtonWithTooltipProps
extends React.ComponentProps<"button">,
diff --git a/src/workspaces/cad/chat/components/reasoning.tsx b/src/workspaces/cad/chat/components/reasoning.tsx
index 56f8a69..92c49b7 100644
--- a/src/workspaces/cad/chat/components/reasoning.tsx
+++ b/src/workspaces/cad/chat/components/reasoning.tsx
@@ -6,9 +6,9 @@ import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
-} from "@/workspaces/cad/ui/collapsible"
-import { useUiLanguage } from "@/lib/use-ui-language"
-import { cn } from "@/lib/utils"
+} from "@/shared/ui/collapsible"
+import { useUiLanguage } from "@/shared/i18n"
+import { cn } from "@/shared/lib/utils"
import { Shimmer } from "./shimmer"
type ReasoningContextValue = {
diff --git a/src/workspaces/cad/chat/components/shimmer.tsx b/src/workspaces/cad/chat/components/shimmer.tsx
index e285cd7..8651161 100644
--- a/src/workspaces/cad/chat/components/shimmer.tsx
+++ b/src/workspaces/cad/chat/components/shimmer.tsx
@@ -6,7 +6,7 @@ import {
memo,
useMemo,
} from "react"
-import { cn } from "@/lib/utils"
+import { cn } from "@/shared/lib/utils"
export type TextShimmerProps = {
children: string
diff --git a/src/workspaces/cad/chat/file-preview-list.tsx b/src/workspaces/cad/chat/file-preview-list.tsx
index 6775512..139bf66 100644
--- a/src/workspaces/cad/chat/file-preview-list.tsx
+++ b/src/workspaces/cad/chat/file-preview-list.tsx
@@ -2,9 +2,9 @@
import { FileCode, FileText, Loader2, X } from "lucide-react"
import { useEffect, useRef, useState } from "react"
-import { isPdfFile, isTextFile } from "@/lib/pdf-utils"
-import { type FileData } from "@/lib/use-file-processor"
-import { useUiLanguage } from "@/lib/use-ui-language"
+import { isPdfFile, isTextFile } from "@/shared/files"
+import { type FileData } from "@/shared/files/use-file-processor"
+import { useUiLanguage } from "@/shared/i18n"
function formatCharCount(count: number): string {
if (count >= 1000) {
diff --git a/src/workspaces/cad/chat/global-constraints-dialog.tsx b/src/workspaces/cad/chat/global-constraints-dialog.tsx
index e1854c3..91f68a7 100644
--- a/src/workspaces/cad/chat/global-constraints-dialog.tsx
+++ b/src/workspaces/cad/chat/global-constraints-dialog.tsx
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react"
-import { Button } from "@/workspaces/cad/ui/button"
+import { Button } from "@/shared/ui/button"
import {
Dialog,
DialogContent,
@@ -7,10 +7,9 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
-} from "@/workspaces/cad/ui/dialog"
-import { Textarea } from "@/workspaces/cad/ui/textarea"
-import { useUiLanguage } from "@/lib/use-ui-language";
-import { t } from "@/lib/i18n";
+} 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"
diff --git a/src/workspaces/cad/chat/history-dialog.tsx b/src/workspaces/cad/chat/history-dialog.tsx
index c498cf3..c6f83c2 100644
--- a/src/workspaces/cad/chat/history-dialog.tsx
+++ b/src/workspaces/cad/chat/history-dialog.tsx
@@ -4,12 +4,11 @@ import {
DialogContent,
DialogHeader,
DialogTitle,
-} from "@/workspaces/cad/ui/dialog"
-import { Button } from '@/workspaces/cad/ui/button';
+} from "@/shared/ui/dialog"
+import { Button } from '@/shared/ui/button';
import { Clock, RotateCcw, FileCode, Trash2 } from 'lucide-react';
-import { ScrollArea } from '@/workspaces/cad/ui/scroll-area';
-import { useUiLanguage } from "@/lib/use-ui-language";
-import { t } from "@/lib/i18n";
+import { ScrollArea } from '@/shared/ui/scroll-area';
+import { t, useUiLanguage } from "@/shared/i18n";
export interface HistoryItem {
id: string;
diff --git a/src/workspaces/cad/chat/reset-warning-modal.tsx b/src/workspaces/cad/chat/reset-warning-modal.tsx
index 03447b9..529c276 100644
--- a/src/workspaces/cad/chat/reset-warning-modal.tsx
+++ b/src/workspaces/cad/chat/reset-warning-modal.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { Button } from "@/workspaces/cad/ui/button"
+import { Button } from "@/shared/ui/button"
import {
Dialog,
DialogContent,
@@ -7,9 +7,8 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
-} from "@/workspaces/cad/ui/dialog"
-import { t } from "@/lib/i18n";
-import { useUiLanguage } from "@/lib/use-ui-language";
+} from "@/shared/ui/dialog"
+import { t, useUiLanguage } from "@/shared/i18n";
interface ResetWarningModalProps {
open: boolean
diff --git a/src/workspaces/cad/storage.ts b/src/workspaces/cad/storage.ts
new file mode 100644
index 0000000..7486d6e
--- /dev/null
+++ b/src/workspaces/cad/storage.ts
@@ -0,0 +1,7 @@
+import { createWorkspaceStore } from "@/shared/storage/indexed-db-store";
+
+/** Database name is load-bearing: changing it orphans everything users saved. */
+export const cadStore = createWorkspaceStore("CanvasAnvilCadWorkspaceDB");
+
+export const CAD_RENDERS_KEY = "renders";
+export const CAD_ANALYSIS_IMAGES_KEY = "analysis-images";
diff --git a/src/workspaces/cad/ui/button.tsx b/src/workspaces/cad/ui/button.tsx
deleted file mode 100644
index c5cd761..0000000
--- a/src/workspaces/cad/ui/button.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-import * as React from "react"
-import { Slot } from "@radix-ui/react-slot"
-import { cva, type VariantProps } from "class-variance-authority"
-
-import { cn } from "@/lib/utils"
-
-const buttonVariants = cva(
- "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
- {
- variants: {
- variant: {
- default:
- "bg-primary text-primary-foreground shadow-xs hover:brightness-75",
- destructive:
- "bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
- outline:
- "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
- secondary:
- "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
- ghost:
- "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
- link: "text-primary underline-offset-4 hover:underline",
- },
- size: {
- default: "h-9 px-4 py-2 has-[>svg]:px-3",
- sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
- lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
- icon: "size-9",
- },
- },
- defaultVariants: {
- variant: "default",
- size: "default",
- },
- }
-)
-
-const Button = React.forwardRef<
- HTMLButtonElement,
- React.ComponentProps<"button"> &
- VariantProps<typeof buttonVariants> & {
- asChild?: boolean
- }
->(({ className, variant, size, asChild = false, ...props }, ref) => {
- const Comp = asChild ? Slot : "button"
-
- return (
- <Comp
- ref={ref}
- data-slot="button"
- className={cn(buttonVariants({ variant, size, className }))}
- {...props}
- />
- )
-})
-Button.displayName = "Button"
-
-export { Button, buttonVariants }
diff --git a/src/workspaces/cad/ui/resizable.tsx b/src/workspaces/cad/ui/resizable.tsx
deleted file mode 100644
index 73c6e45..0000000
--- a/src/workspaces/cad/ui/resizable.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-import { GripVertical } from "lucide-react"
-import { Panel, Group, Separator, type PanelImperativeHandle } from "react-resizable-panels"
-
-import { cn } from "@/lib/utils"
-
-const ResizablePanelGroup = ({
- className,
- ...props
-}: React.ComponentProps<typeof Group>) => (
- <Group
- className={cn(
- "flex h-full w-full data-[panel-group-direction=vertical]:flex-col",
- className
- )}
- {...props}
- />
-)
-
-const ResizablePanel = Panel
-
-const ResizableHandle = ({
- withHandle,
- className,
- ...props
-}: React.ComponentProps<typeof Separator> & {
- withHandle?: boolean
-}) => (
- <Separator
- className={cn(
- "relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",
- className
- )}
- {...props}
- >
- {withHandle && (
- <div className="z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border">
- <GripVertical className="h-2.5 w-2.5" />
- </div>
- )}
- </Separator>
-)
-
-export { ResizablePanelGroup, ResizablePanel, ResizableHandle }
-export type { PanelImperativeHandle }
diff --git a/src/workspaces/cad/ui/scroll-area.tsx b/src/workspaces/cad/ui/scroll-area.tsx
deleted file mode 100644
index 677c344..0000000
--- a/src/workspaces/cad/ui/scroll-area.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-"use client"
-
-import * as React from "react"
-import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
-
-import { cn } from "@/lib/utils"
-
-function ScrollArea({
- className,
- children,
- ...props
-}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
- return (
- <ScrollAreaPrimitive.Root
- data-slot="scroll-area"
- className={cn("relative", className)}
- {...props}
- >
- <ScrollAreaPrimitive.Viewport
- data-slot="scroll-area-viewport"
- className="ring-ring/10 dark:ring-ring/20 dark:outline-ring/40 outline-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] focus-visible:ring-4 focus-visible:outline-1 !overflow-x-hidden"
- >
- {children}
- </ScrollAreaPrimitive.Viewport>
- <ScrollBar />
- <ScrollAreaPrimitive.Corner />
- </ScrollAreaPrimitive.Root>
- )
-}
-
-function ScrollBar({
- className,
- orientation = "vertical",
- ...props
-}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
- return (
- <ScrollAreaPrimitive.ScrollAreaScrollbar
- data-slot="scroll-area-scrollbar"
- orientation={orientation}
- className={cn(
- "flex touch-none p-px transition-colors select-none",
- orientation === "vertical" &&
- "h-full w-2.5 border-l border-l-transparent",
- orientation === "horizontal" &&
- "h-2.5 flex-col border-t border-t-transparent",
- className
- )}
- {...props}
- >
- <ScrollAreaPrimitive.ScrollAreaThumb
- data-slot="scroll-area-thumb"
- className="bg-border relative flex-1 rounded-full"
- />
- </ScrollAreaPrimitive.ScrollAreaScrollbar>
- )
-}
-
-export { ScrollArea, ScrollBar }
diff --git a/src/workspaces/cad/ui/tooltip.tsx b/src/workspaces/cad/ui/tooltip.tsx
deleted file mode 100644
index 30fc44d..0000000
--- a/src/workspaces/cad/ui/tooltip.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-"use client"
-
-import * as React from "react"
-import * as TooltipPrimitive from "@radix-ui/react-tooltip"
-
-import { cn } from "@/lib/utils"
-
-const TooltipProvider = TooltipPrimitive.Provider
-
-const Tooltip = TooltipPrimitive.Root
-
-const TooltipTrigger = TooltipPrimitive.Trigger
-
-const TooltipContent = React.forwardRef<
- React.ElementRef<typeof TooltipPrimitive.Content>,
- React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
->(({ className, sideOffset = 4, ...props }, ref) => (
- <TooltipPrimitive.Content
- ref={ref}
- sideOffset={sideOffset}
- className={cn(
- "z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
- className
- )}
- {...props}
- />
-))
-TooltipContent.displayName = TooltipPrimitive.Content.displayName
-
-export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
diff --git a/src/workspaces/cad/workspace/CadWorkspace.tsx b/src/workspaces/cad/workspace/CadWorkspace.tsx
index f522b17..0b55783 100644
--- a/src/workspaces/cad/workspace/CadWorkspace.tsx
+++ b/src/workspaces/cad/workspace/CadWorkspace.tsx
@@ -5,11 +5,11 @@ import {
ContextMenuContent,
ContextMenuItem,
ContextMenuTrigger,
-} from "@/workspaces/cad/ui/context-menu";
-import { Button } from "@/workspaces/cad/ui/button";
-import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/workspaces/cad/ui/dialog";
+} from "@/shared/ui/context-menu";
+import { Button } from "@/shared/ui/button";
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/shared/ui/dialog";
import { PDFDocument } from "pdf-lib";
-import { useUiLanguage } from "@/lib/use-ui-language";
+import { useUiLanguage } from "@/shared/i18n";
import { toast } from "sonner";
import { getCadRenderSlotTitles } from "@/lib/cad-render-titles";
diff --git a/src/workspaces/flow/next/NextFlowWorkspace.tsx b/src/workspaces/flow/next/NextFlowWorkspace.tsx
index 8a054a2..36f8e6d 100644
--- a/src/workspaces/flow/next/NextFlowWorkspace.tsx
+++ b/src/workspaces/flow/next/NextFlowWorkspace.tsx
@@ -1,14 +1,10 @@
-import React from "react";
import FlowPage from "@/workspaces/flow/next/page";
import { DiagramProvider } from "@/workspaces/flow/next/contexts/diagram-context";
-import { LanguageProvider } from "@/workspaces/flow/next/contexts/language-context";
export function NextFlowWorkspace() {
return (
- <LanguageProvider>
- <DiagramProvider>
- <FlowPage />
- </DiagramProvider>
- </LanguageProvider>
+ <DiagramProvider>
+ <FlowPage />
+ </DiagramProvider>
);
}
diff --git a/src/workspaces/flow/next/components/ai-elements/reasoning.tsx b/src/workspaces/flow/next/components/ai-elements/reasoning.tsx
index 0a63766..11e8af1 100644
--- a/src/workspaces/flow/next/components/ai-elements/reasoning.tsx
+++ b/src/workspaces/flow/next/components/ai-elements/reasoning.tsx
@@ -8,8 +8,8 @@ import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
-} from "@/workspaces/flow/next/components/ui/collapsible"
-import { cn } from "@/workspaces/flow/next/lib/utils"
+} from "@/shared/ui/collapsible"
+import { cn } from "@/shared/lib/utils"
import { Shimmer } from "./shimmer"
type ReasoningContextValue = {
diff --git a/src/workspaces/flow/next/components/ai-elements/shimmer.tsx b/src/workspaces/flow/next/components/ai-elements/shimmer.tsx
index 036d874..0e1122a 100644
--- a/src/workspaces/flow/next/components/ai-elements/shimmer.tsx
+++ b/src/workspaces/flow/next/components/ai-elements/shimmer.tsx
@@ -8,7 +8,7 @@ import {
memo,
useMemo,
} from "react"
-import { cn } from "@/workspaces/flow/next/lib/utils"
+import { cn } from "@/shared/lib/utils"
export type TextShimmerProps = {
children: string
diff --git a/src/workspaces/flow/next/components/button-with-tooltip.tsx b/src/workspaces/flow/next/components/button-with-tooltip.tsx
index ccc3355..5667b40 100644
--- a/src/workspaces/flow/next/components/button-with-tooltip.tsx
+++ b/src/workspaces/flow/next/components/button-with-tooltip.tsx
@@ -1,11 +1,11 @@
import type { VariantProps } from "class-variance-authority"
import type React from "react"
-import { Button, type buttonVariants } from "@/workspaces/flow/next/components/ui/button"
+import { Button, type buttonVariants } from "@/shared/ui/button"
import {
Tooltip,
TooltipContent,
TooltipTrigger,
-} from "@/workspaces/flow/next/components/ui/tooltip"
+} from "@/shared/ui/tooltip"
interface ButtonWithTooltipProps
extends React.ComponentProps<"button">,
diff --git a/src/workspaces/flow/next/components/chat-input.tsx b/src/workspaces/flow/next/components/chat-input.tsx
index 45130b5..6bf0cd1 100644
--- a/src/workspaces/flow/next/components/chat-input.tsx
+++ b/src/workspaces/flow/next/components/chat-input.tsx
@@ -18,10 +18,10 @@ import { ErrorToast } from "@/workspaces/flow/next/components/error-toast"
import { GlobalConstraintsDialog } from "@/workspaces/flow/next/components/global-constraints-dialog"
import { HistoryDialog } from "@/workspaces/flow/next/components/history-dialog"
import { ResetWarningModal } from "@/workspaces/flow/next/components/reset-warning-modal"
-import { Textarea } from "@/workspaces/flow/next/components/ui/textarea"
+import { Textarea } from "@/shared/ui/textarea"
import { useDiagram } from "@/workspaces/flow/next/contexts/diagram-context"
-import { useLanguage } from "@/workspaces/flow/next/contexts/language-context"
-import { isPdfFile, isTextFile } from "@/workspaces/flow/next/lib/pdf-utils"
+import { useFlowT } from "@/workspaces/flow/next/lib/translations"
+import { isPdfFile, isTextFile } from "@/shared/files"
import { FilePreviewList } from "./file-preview-list"
const MAX_IMAGE_SIZE = 2 * 1024 * 1024 // 2MB
@@ -165,7 +165,7 @@ export function ChatInput({
deepThinkingEnabled = false,
onToggleDeepThinking = () => {},
}: ChatInputProps) {
- const { t } = useLanguage()
+ const t = useFlowT()
const { diagramHistory } = useDiagram()
const textareaRef = useRef<HTMLTextAreaElement>(null)
const imageInputRef = useRef<HTMLInputElement>(null)
diff --git a/src/workspaces/flow/next/components/chat-message-display.tsx b/src/workspaces/flow/next/components/chat-message-display.tsx
index 37fa89d..be5c74a 100644
--- a/src/workspaces/flow/next/components/chat-message-display.tsx
+++ b/src/workspaces/flow/next/components/chat-message-display.tsx
@@ -25,14 +25,14 @@ import {
ReasoningContent,
ReasoningTrigger,
} from "@/workspaces/flow/next/components/ai-elements/reasoning"
-import { ScrollArea } from "@/workspaces/flow/next/components/ui/scroll-area"
-import { useLanguage } from "@/workspaces/flow/next/contexts/language-context"
+import { ScrollArea } from "@/shared/ui/scroll-area"
+import { useFlowT } from "@/workspaces/flow/next/lib/translations"
import {
applyDiagramOperations,
isMxCellXmlComplete,
type DiagramOperation,
} from "@/workspaces/flow/next/lib/diagram-operations"
-import { convertToLegalXml, replaceNodes, validateMxCellStructure } from "@/workspaces/flow/next/lib/utils"
+import { convertToLegalXml, replaceNodes, validateMxCellStructure } from "@/workspaces/flow/next/lib/drawio-xml"
import { CodeBlock } from "./code-block"
// Tool part interface for type safety
@@ -188,7 +188,7 @@ export function ChatMessageDisplay({
status = "idle",
isParsingFiles = false,
}: ChatMessageDisplayProps) {
- const { t } = useLanguage()
+ const t = useFlowT()
const { chartXML, loadDiagram: onDisplayChart } = useDiagram()
const messagesEndRef = useRef<HTMLDivElement>(null)
const previousXML = useRef<string>("")
diff --git a/src/workspaces/flow/next/components/chat-panel.tsx b/src/workspaces/flow/next/components/chat-panel.tsx
index 234a15a..18119e9 100644
--- a/src/workspaces/flow/next/components/chat-panel.tsx
+++ b/src/workspaces/flow/next/components/chat-panel.tsx
@@ -12,7 +12,7 @@ import { ButtonWithTooltip } from "@/workspaces/flow/next/components/button-with
import { ChatInput } from "@/workspaces/flow/next/components/chat-input"
import { STORAGE_GLOBAL_CONSTRAINTS_KEY } from "@/workspaces/flow/next/components/global-constraints-dialog"
import { useDiagram } from "@/workspaces/flow/next/contexts/diagram-context"
-import { useLanguage } from "@/workspaces/flow/next/contexts/language-context"
+import { useFlowT } from "@/workspaces/flow/next/lib/translations"
import { getAIConfig } from "@/workspaces/flow/next/lib/ai-config"
import {
extractPdfText,
@@ -21,11 +21,11 @@ import {
isPdfFile,
isWordFile,
isTextFile,
-} from "@/workspaces/flow/next/lib/pdf-utils"
-import { type FileData, useFileProcessor } from "@/workspaces/flow/next/lib/use-file-processor"
+} from "@/shared/files"
+import { type FileData, useFileProcessor } from "@/shared/files/use-file-processor"
import { useQuotaManager } from "@/workspaces/flow/next/lib/use-quota-manager"
import { applyDiagramOperations, isMxCellXmlComplete, type DiagramOperation } from "@/workspaces/flow/next/lib/diagram-operations"
-import { formatXML, validateAndFixXml, wrapWithMxFile } from "@/workspaces/flow/next/lib/utils"
+import { formatXML, validateAndFixXml, wrapWithMxFile } from "@/workspaces/flow/next/lib/drawio-xml"
import { ChatMessageDisplay } from "./chat-message-display"
// localStorage keys for persistence
@@ -111,7 +111,7 @@ export default function ChatPanel({
isDrawioReady,
} = useDiagram()
- const { t } = useLanguage()
+ const t = useFlowT()
const onFetchChart = (saveToHistory = true) => {
if (!isDrawioReady) {
diff --git a/src/workspaces/flow/next/components/file-preview-list.tsx b/src/workspaces/flow/next/components/file-preview-list.tsx
index f7ab612..b07987c 100644
--- a/src/workspaces/flow/next/components/file-preview-list.tsx
+++ b/src/workspaces/flow/next/components/file-preview-list.tsx
@@ -3,7 +3,7 @@
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 "@/workspaces/flow/next/lib/pdf-utils"
+import { isPdfFile, isTextFile } from "@/shared/files"
function formatCharCount(count: number): string {
if (count >= 1000) {
diff --git a/src/workspaces/flow/next/components/global-constraints-dialog.tsx b/src/workspaces/flow/next/components/global-constraints-dialog.tsx
index 2959392..7d6dc8e 100644
--- a/src/workspaces/flow/next/components/global-constraints-dialog.tsx
+++ b/src/workspaces/flow/next/components/global-constraints-dialog.tsx
@@ -2,7 +2,7 @@
import { useEffect, useState } from "react"
import { toast } from "sonner"
-import { Button } from "@/workspaces/flow/next/components/ui/button"
+import { Button } from "@/shared/ui/button"
import {
Dialog,
DialogContent,
@@ -10,9 +10,9 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
-} from "@/workspaces/flow/next/components/ui/dialog"
-import { Textarea } from "@/workspaces/flow/next/components/ui/textarea"
-import { useLanguage } from "@/workspaces/flow/next/contexts/language-context"
+} 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"
@@ -25,7 +25,7 @@ export function GlobalConstraintsDialog({
open,
onOpenChange,
}: GlobalConstraintsDialogProps) {
- const { t } = useLanguage()
+ const t = useFlowT()
const [constraints, setConstraints] = useState("")
useEffect(() => {
diff --git a/src/workspaces/flow/next/components/history-dialog.tsx b/src/workspaces/flow/next/components/history-dialog.tsx
index ad0b6b9..36b3e73 100644
--- a/src/workspaces/flow/next/components/history-dialog.tsx
+++ b/src/workspaces/flow/next/components/history-dialog.tsx
@@ -2,16 +2,16 @@
import Image from "@/workspaces/flow/next/shims/next-image"
import { useState } from "react"
-import { Button } from "@/workspaces/flow/next/components/ui/button"
+import { Button } from "@/shared/ui/button"
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
-} from "@/workspaces/flow/next/components/ui/dialog"
+} from "@/shared/ui/dialog"
import { useDiagram } from "@/workspaces/flow/next/contexts/diagram-context"
-import { useLanguage } from "@/workspaces/flow/next/contexts/language-context"
+import { useFlowT } from "@/workspaces/flow/next/lib/translations"
interface HistoryDialogProps {
showHistory: boolean
@@ -23,7 +23,7 @@ export function HistoryDialog({
onToggleHistory,
}: HistoryDialogProps) {
const { diagramHistory, loadDiagram: onDisplayChart } = useDiagram()
- const { t } = useLanguage()
+ const t = useFlowT()
const [selectedIndex, setSelectedIndex] = useState<number | null>(null)
const handleClose = () => {
diff --git a/src/workspaces/flow/next/components/quota-limit-toast.tsx b/src/workspaces/flow/next/components/quota-limit-toast.tsx
index 6fef0d2..c72dd05 100644
--- a/src/workspaces/flow/next/components/quota-limit-toast.tsx
+++ b/src/workspaces/flow/next/components/quota-limit-toast.tsx
@@ -1,7 +1,7 @@
"use client"
import { FaCoffee } from "react-icons/fa"
-import { useLanguage } from "@/workspaces/flow/next/contexts/language-context"
+import { useFlowT } from "@/workspaces/flow/next/lib/translations"
interface QuotaLimitToastProps {
limit: number
@@ -12,7 +12,7 @@ export function QuotaLimitToast({
limit,
used,
}: QuotaLimitToastProps) {
- const { t } = useLanguage()
+ const t = useFlowT()
const percentage = Math.min((used / limit) * 100, 100)
return (
diff --git a/src/workspaces/flow/next/components/reset-warning-modal.tsx b/src/workspaces/flow/next/components/reset-warning-modal.tsx
index a3c3d94..bc4b388 100644
--- a/src/workspaces/flow/next/components/reset-warning-modal.tsx
+++ b/src/workspaces/flow/next/components/reset-warning-modal.tsx
@@ -1,6 +1,6 @@
"use client"
-import { Button } from "@/workspaces/flow/next/components/ui/button"
+import { Button } from "@/shared/ui/button"
import {
Dialog,
DialogContent,
@@ -8,8 +8,8 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
-} from "@/workspaces/flow/next/components/ui/dialog"
-import { useLanguage } from "@/workspaces/flow/next/contexts/language-context"
+} from "@/shared/ui/dialog"
+import { useFlowT } from "@/workspaces/flow/next/lib/translations"
interface ResetWarningModalProps {
open: boolean
@@ -22,7 +22,7 @@ export function ResetWarningModal({
onOpenChange,
onClear,
}: ResetWarningModalProps) {
- const { t } = useLanguage()
+ const t = useFlowT()
return (
<Dialog open={open} onOpenChange={onOpenChange}>
diff --git a/src/workspaces/flow/next/components/save-dialog.tsx b/src/workspaces/flow/next/components/save-dialog.tsx
index b0caaae..4e17ebe 100644
--- a/src/workspaces/flow/next/components/save-dialog.tsx
+++ b/src/workspaces/flow/next/components/save-dialog.tsx
@@ -1,23 +1,23 @@
"use client"
import { useEffect, useState } from "react"
-import { Button } from "@/workspaces/flow/next/components/ui/button"
+import { Button } from "@/shared/ui/button"
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
-} from "@/workspaces/flow/next/components/ui/dialog"
-import { Input } from "@/workspaces/flow/next/components/ui/input"
+} from "@/shared/ui/dialog"
+import { Input } from "@/shared/ui/input"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
-} from "@/workspaces/flow/next/components/ui/select"
-import { useLanguage } from "@/workspaces/flow/next/contexts/language-context"
+} from "@/shared/ui/select"
+import { useFlowT } from "@/workspaces/flow/next/lib/translations"
export type ExportFormat = "drawio" | "png" | "svg"
@@ -44,7 +44,7 @@ export function SaveDialog({
onSave,
defaultFilename,
}: SaveDialogProps) {
- const { t } = useLanguage()
+ const t = useFlowT()
const [filename, setFilename] = useState(defaultFilename)
const [format, setFormat] = useState<ExportFormat>("drawio")
diff --git a/src/workspaces/flow/next/components/settings-dialog.tsx b/src/workspaces/flow/next/components/settings-dialog.tsx
index 0224b52..f29b6c6 100644
--- a/src/workspaces/flow/next/components/settings-dialog.tsx
+++ b/src/workspaces/flow/next/components/settings-dialog.tsx
@@ -3,18 +3,18 @@
import { Moon, Sun } from "lucide-react"
import { useEffect, useState } from "react"
import { getAIConfig as getWorkspaceAIConfig } from "@/ai/client"
-import { Button } from "@/workspaces/flow/next/components/ui/button"
+import { Button } from "@/shared/ui/button"
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
-} from "@/workspaces/flow/next/components/ui/dialog"
-import { Input } from "@/workspaces/flow/next/components/ui/input"
-import { Label } from "@/workspaces/flow/next/components/ui/label"
-import { Switch } from "@/workspaces/flow/next/components/ui/switch"
-import { useLanguage } from "@/workspaces/flow/next/contexts/language-context"
+} from "@/shared/ui/dialog"
+import { Input } from "@/shared/ui/input"
+import { Label } from "@/shared/ui/label"
+import { Switch } from "@/shared/ui/switch"
+import { useFlowT } from "@/workspaces/flow/next/lib/translations"
interface SettingsDialogProps {
open: boolean
@@ -62,7 +62,7 @@ export function SettingsDialog({
darkMode,
onToggleDarkMode,
}: SettingsDialogProps) {
- const { t } = useLanguage()
+ const t = useFlowT()
const [accessCode, setAccessCode] = useState("")
const [closeProtection, setCloseProtection] = useState(true)
const [isVerifying, setIsVerifying] = useState(false)
diff --git a/src/workspaces/flow/next/components/ui/button.tsx b/src/workspaces/flow/next/components/ui/button.tsx
deleted file mode 100644
index 90b1d38..0000000
--- a/src/workspaces/flow/next/components/ui/button.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-import * as React from "react"
-import { Slot } from "@radix-ui/react-slot"
-import { cva, type VariantProps } from "class-variance-authority"
-
-import { cn } from "@/workspaces/flow/next/lib/utils"
-
-const buttonVariants = cva(
- "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
- {
- variants: {
- variant: {
- default:
- "bg-primary text-primary-foreground shadow-xs hover:brightness-75",
- destructive:
- "bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
- outline:
- "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
- secondary:
- "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
- ghost:
- "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
- link: "text-primary underline-offset-4 hover:underline",
- },
- size: {
- default: "h-9 px-4 py-2 has-[>svg]:px-3",
- sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
- lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
- icon: "size-9",
- },
- },
- defaultVariants: {
- variant: "default",
- size: "default",
- },
- }
-)
-
-function Button({
- className,
- variant,
- size,
- asChild = false,
- ...props
-}: React.ComponentProps<"button"> &
- VariantProps<typeof buttonVariants> & {
- asChild?: boolean
- }) {
- const Comp = asChild ? Slot : "button"
-
- return (
- <Comp
- data-slot="button"
- className={cn(buttonVariants({ variant, size, className }))}
- {...props}
- />
- )
-}
-
-export { Button, buttonVariants }
-
diff --git a/src/workspaces/flow/next/components/ui/collapsible.tsx b/src/workspaces/flow/next/components/ui/collapsible.tsx
deleted file mode 100644
index 6443a91..0000000
--- a/src/workspaces/flow/next/components/ui/collapsible.tsx
+++ /dev/null
@@ -1,34 +0,0 @@
-"use client"
-
-import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
-
-function Collapsible({
- ...props
-}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
- return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
-}
-
-function CollapsibleTrigger({
- ...props
-}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
- return (
- <CollapsiblePrimitive.CollapsibleTrigger
- data-slot="collapsible-trigger"
- {...props}
- />
- )
-}
-
-function CollapsibleContent({
- ...props
-}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
- return (
- <CollapsiblePrimitive.CollapsibleContent
- data-slot="collapsible-content"
- {...props}
- />
- )
-}
-
-export { Collapsible, CollapsibleTrigger, CollapsibleContent }
-
diff --git a/src/workspaces/flow/next/components/ui/dialog.tsx b/src/workspaces/flow/next/components/ui/dialog.tsx
deleted file mode 100644
index 68bf3a1..0000000
--- a/src/workspaces/flow/next/components/ui/dialog.tsx
+++ /dev/null
@@ -1,136 +0,0 @@
-"use client"
-
-import * as React from "react"
-import * as DialogPrimitive from "@radix-ui/react-dialog"
-import { XIcon } from "lucide-react"
-
-import { cn } from "@/workspaces/flow/next/lib/utils"
-
-function Dialog({
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Root>) {
- return <DialogPrimitive.Root data-slot="dialog" {...props} />
-}
-
-function DialogTrigger({
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
- return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
-}
-
-function DialogPortal({
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
- return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
-}
-
-function DialogClose({
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Close>) {
- return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
-}
-
-function DialogOverlay({
- className,
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
- return (
- <DialogPrimitive.Overlay
- data-slot="dialog-overlay"
- className={cn(
- "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
- className
- )}
- {...props}
- />
- )
-}
-
-function DialogContent({
- className,
- children,
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Content>) {
- return (
- <DialogPortal data-slot="dialog-portal">
- <DialogOverlay />
- <DialogPrimitive.Content
- data-slot="dialog-content"
- className={cn(
- "bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
- className
- )}
- {...props}
- >
- {children}
- <DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
- <XIcon />
- <span className="sr-only">Close</span>
- </DialogPrimitive.Close>
- </DialogPrimitive.Content>
- </DialogPortal>
- )
-}
-
-function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
- return (
- <div
- data-slot="dialog-header"
- className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
- {...props}
- />
- )
-}
-
-function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
- return (
- <div
- data-slot="dialog-footer"
- className={cn(
- "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
- className
- )}
- {...props}
- />
- )
-}
-
-function DialogTitle({
- className,
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Title>) {
- return (
- <DialogPrimitive.Title
- data-slot="dialog-title"
- className={cn("text-lg leading-none font-semibold", className)}
- {...props}
- />
- )
-}
-
-function DialogDescription({
- className,
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Description>) {
- return (
- <DialogPrimitive.Description
- data-slot="dialog-description"
- className={cn("text-muted-foreground text-sm", className)}
- {...props}
- />
- )
-}
-
-export {
- Dialog,
- DialogClose,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogOverlay,
- DialogPortal,
- DialogTitle,
- DialogTrigger,
-}
-
diff --git a/src/workspaces/flow/next/components/ui/scroll-area.tsx b/src/workspaces/flow/next/components/ui/scroll-area.tsx
deleted file mode 100644
index 103dea5..0000000
--- a/src/workspaces/flow/next/components/ui/scroll-area.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-"use client"
-
-import * as React from "react"
-import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
-
-import { cn } from "@/workspaces/flow/next/lib/utils"
-
-function ScrollArea({
- className,
- children,
- ...props
-}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
- return (
- <ScrollAreaPrimitive.Root
- data-slot="scroll-area"
- className={cn("relative", className)}
- {...props}
- >
- <ScrollAreaPrimitive.Viewport
- data-slot="scroll-area-viewport"
- className="ring-ring/10 dark:ring-ring/20 dark:outline-ring/40 outline-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] focus-visible:ring-4 focus-visible:outline-1 !overflow-x-hidden"
- >
- {children}
- </ScrollAreaPrimitive.Viewport>
- <ScrollBar />
- <ScrollAreaPrimitive.Corner />
- </ScrollAreaPrimitive.Root>
- )
-}
-
-function ScrollBar({
- className,
- orientation = "vertical",
- ...props
-}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
- return (
- <ScrollAreaPrimitive.ScrollAreaScrollbar
- data-slot="scroll-area-scrollbar"
- orientation={orientation}
- className={cn(
- "flex touch-none p-px transition-colors select-none",
- orientation === "vertical" &&
- "h-full w-2.5 border-l border-l-transparent",
- orientation === "horizontal" &&
- "h-2.5 flex-col border-t border-t-transparent",
- className
- )}
- {...props}
- >
- <ScrollAreaPrimitive.ScrollAreaThumb
- data-slot="scroll-area-thumb"
- className="bg-border relative flex-1 rounded-full"
- />
- </ScrollAreaPrimitive.ScrollAreaScrollbar>
- )
-}
-
-export { ScrollArea, ScrollBar }
-
diff --git a/src/workspaces/flow/next/components/ui/textarea.tsx b/src/workspaces/flow/next/components/ui/textarea.tsx
deleted file mode 100644
index cdb640d..0000000
--- a/src/workspaces/flow/next/components/ui/textarea.tsx
+++ /dev/null
@@ -1,19 +0,0 @@
-import * as React from "react"
-
-import { cn } from "@/workspaces/flow/next/lib/utils"
-
-function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
- return (
- <textarea
- data-slot="textarea"
- className={cn(
- "border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
- className
- )}
- {...props}
- />
- )
-}
-
-export { Textarea }
-
diff --git a/src/workspaces/flow/next/components/ui/tooltip.tsx b/src/workspaces/flow/next/components/ui/tooltip.tsx
deleted file mode 100644
index 7d9eb10..0000000
--- a/src/workspaces/flow/next/components/ui/tooltip.tsx
+++ /dev/null
@@ -1,62 +0,0 @@
-"use client"
-
-import * as React from "react"
-import * as TooltipPrimitive from "@radix-ui/react-tooltip"
-
-import { cn } from "@/workspaces/flow/next/lib/utils"
-
-function TooltipProvider({
- delayDuration = 0,
- ...props
-}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
- return (
- <TooltipPrimitive.Provider
- data-slot="tooltip-provider"
- delayDuration={delayDuration}
- {...props}
- />
- )
-}
-
-function Tooltip({
- ...props
-}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
- return (
- <TooltipProvider>
- <TooltipPrimitive.Root data-slot="tooltip" {...props} />
- </TooltipProvider>
- )
-}
-
-function TooltipTrigger({
- ...props
-}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
- return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
-}
-
-function TooltipContent({
- className,
- sideOffset = 0,
- children,
- ...props
-}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
- return (
- <TooltipPrimitive.Portal>
- <TooltipPrimitive.Content
- data-slot="tooltip-content"
- sideOffset={sideOffset}
- className={cn(
- "bg-primary text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
- className
- )}
- {...props}
- >
- {children}
- <TooltipPrimitive.Arrow className="bg-primary fill-primary z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
- </TooltipPrimitive.Content>
- </TooltipPrimitive.Portal>
- )
-}
-
-export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
-
diff --git a/src/workspaces/flow/next/contexts/diagram-context.tsx b/src/workspaces/flow/next/contexts/diagram-context.tsx
index 80ad93b..51f8c02 100644
--- a/src/workspaces/flow/next/contexts/diagram-context.tsx
+++ b/src/workspaces/flow/next/contexts/diagram-context.tsx
@@ -5,7 +5,7 @@ import { createContext, useContext, useRef, useState } from "react"
import type { DrawIoEmbedRef } from "react-drawio"
import { STORAGE_DIAGRAM_XML_KEY } from "@/workspaces/flow/next/components/chat-panel"
import type { ExportFormat } from "@/workspaces/flow/next/components/save-dialog"
-import { extractDiagramXML, validateMxCellStructure } from "../lib/utils"
+import { extractDiagramXML, validateMxCellStructure } from "@/workspaces/flow/next/lib/drawio-xml"
interface DiagramContextType {
chartXML: string
diff --git a/src/workspaces/flow/next/contexts/language-context.tsx b/src/workspaces/flow/next/contexts/language-context.tsx
deleted file mode 100644
index bacb124..0000000
--- a/src/workspaces/flow/next/contexts/language-context.tsx
+++ /dev/null
@@ -1,57 +0,0 @@
-"use client"
-
-import { createContext, useContext, useEffect, useState } from "react"
-import type React from "react"
-import { getUiLanguage, setUiLanguage } from "@/lib/ui-language"
-import { translations, type Language } from "@/workspaces/flow/next/lib/translations"
-
-type LanguageContextType = {
- language: Language
- setLanguage: (lang: Language) => void
- t: (key: keyof typeof translations.en) => string
-}
-
-const LanguageContext = createContext<LanguageContextType | null>(null)
-
-export function LanguageProvider({ children }: { children: React.ReactNode }) {
- const [language, setLanguage] = useState<Language>(() => getUiLanguage())
-
- useEffect(() => {
- const syncFromGlobal = () => {
- setLanguage(getUiLanguage())
- }
-
- syncFromGlobal()
- window.addEventListener("ui-language-changed", syncFromGlobal as any)
- return () =>
- window.removeEventListener(
- "ui-language-changed",
- syncFromGlobal as any,
- )
- }, [])
-
- const handleSetLanguage = (lang: Language) => {
- setLanguage(lang)
- setUiLanguage(lang)
- }
-
- const t = (key: keyof typeof translations.en) => {
- return translations[language][key] || key
- }
-
- return (
- <LanguageContext.Provider
- value={{ language, setLanguage: handleSetLanguage, t }}
- >
- {children}
- </LanguageContext.Provider>
- )
-}
-
-export const useLanguage = () => {
- const context = useContext(LanguageContext)
- if (!context) {
- throw new Error("useLanguage must be used within a LanguageProvider")
- }
- return context
-}
diff --git a/src/workspaces/flow/next/lib/utils.ts b/src/workspaces/flow/next/lib/drawio-xml.ts
similarity index 99%
rename from src/workspaces/flow/next/lib/utils.ts
rename to src/workspaces/flow/next/lib/drawio-xml.ts
index ca564a5..9fbc9ed 100644
--- a/src/workspaces/flow/next/lib/utils.ts
+++ b/src/workspaces/flow/next/lib/drawio-xml.ts
@@ -1,10 +1,9 @@
-import { type ClassValue, clsx } from "clsx"
import * as pako from "pako"
-import { twMerge } from "tailwind-merge"
-export function cn(...inputs: ClassValue[]) {
- return twMerge(clsx(inputs))
-}
+/**
+ * draw.io XML surgery: validation, repair, formatting, and the targeted
+ * node replacement the edit_diagram tool performs.
+ */
const MAX_XML_SIZE = 1_000_000
const STRUCTURAL_ATTRS = [
diff --git a/src/workspaces/flow/next/lib/translations.ts b/src/workspaces/flow/next/lib/translations.ts
index 483c2cf..8bac124 100644
--- a/src/workspaces/flow/next/lib/translations.ts
+++ b/src/workspaces/flow/next/lib/translations.ts
@@ -1,270 +1,137 @@
-export type Language = "en" | "zh";
+import { createTranslator, type Dict } from "@/shared/i18n/translator";
-const en = {
+/** Strings owned by the Flow workspace. */
+const messages = {
// ChatPanel
- "app.title": "Next AI Drawio",
- "welcome.title": "Create diagrams with AI",
- "welcome.desc": "Describe what you want to create or upload an image to replicate",
- "app.about": "About",
- "chat.panel.show": "Show chat panel (Ctrl+B)",
- "chat.panel.hide": "Hide chat panel (Ctrl+B)",
- "chat.panel.title": "Flowchart Assistant",
- "chat.settings": "Settings",
- "chat.vertical.title": "AI Chat",
+ "app.title": { zh: "流程图助手", en: "Next AI Drawio" },
+ "welcome.title": { zh: "用 AI 创建流程图", en: "Create diagrams with AI" },
+ "welcome.desc": { zh: "描述你想创建的内容,或上传图片进行复刻", en: "Describe what you want to create or upload an image to replicate" },
+ "app.about": { zh: "关于", en: "About" },
+ "chat.panel.show": { zh: "展开交互区 (Ctrl+B)", en: "Show chat panel (Ctrl+B)" },
+ "chat.panel.hide": { zh: "收起交互区 (Ctrl+B)", en: "Hide chat panel (Ctrl+B)" },
+ "chat.panel.title": { zh: "流程图交互区", en: "Flowchart Assistant" },
+ "chat.settings": { zh: "设置", en: "Settings" },
+ "chat.vertical.title": { zh: "AI 对话", en: "AI Chat" },
// ChatInput
- "input.placeholder": "Describe your diagram or upload a file...",
- "input.clear": "Clear conversation",
- "input.upload": "Upload file (image, PDF, text)",
- "input.upload_image": "Upload image",
- "input.upload_file": "Upload file",
- "input.upload_file_types": "Upload file (.pdf, .docx, .txt)",
- "input.send": "Send message",
- "input.stop": "Stop generation",
- "input.history": "History",
- "input.history.toggle": "Toggle history",
- "input.deep_thinking": "Deep Think",
+ "input.placeholder": { zh: "描述你的流程图需求,或上传文件...", en: "Describe your diagram or upload a file..." },
+ "input.clear": { zh: "清空对话", en: "Clear conversation" },
+ "input.upload": { zh: "上传文件(图片、PDF、文本)", en: "Upload file (image, PDF, text)" },
+ "input.upload_image": { zh: "上传图片", en: "Upload image" },
+ "input.upload_file": { zh: "上传文件", en: "Upload file" },
+ "input.upload_file_types": { zh: "上传文件(.pdf、.docx、.txt)", en: "Upload file (.pdf, .docx, .txt)" },
+ "input.send": { zh: "发送消息", en: "Send message" },
+ "input.stop": { zh: "停止生成", en: "Stop generation" },
+ "input.history": { zh: "历史记录", en: "History" },
+ "input.history.toggle": { zh: "切换历史记录", en: "Toggle history" },
+ "input.deep_thinking": { zh: "深度思考", en: "Deep Think" },
// ChatMessageDisplay
- "message.sending": "Sending message...",
- "message.parsing_files": "Parsing files...",
- "message.thinking": "AI is thinking and generating response...",
- "message.copy": "Copy message",
- "message.copied": "Copied!",
- "message.copy.failed": "Failed to copy",
- "message.regenerate": "Regenerate response",
- "message.edit": "Edit message",
- "message.good": "Good response",
- "message.bad": "Bad response",
- "message.edit.cancel": "Cancel",
- "message.edit.save": "Save & Submit",
+ "message.sending": { zh: "正在发送消息...", en: "Sending message..." },
+ "message.parsing_files": { zh: "正在解析文件...", en: "Parsing files..." },
+ "message.thinking": { zh: "AI 正在思考并生成结果...", en: "AI is thinking and generating response..." },
+ "message.copy": { zh: "复制消息", en: "Copy message" },
+ "message.copied": { zh: "已复制", en: "Copied!" },
+ "message.copy.failed": { zh: "复制失败", en: "Failed to copy" },
+ "message.regenerate": { zh: "重新生成", en: "Regenerate response" },
+ "message.edit": { zh: "编辑消息", en: "Edit message" },
+ "message.good": { zh: "回答有帮助", en: "Good response" },
+ "message.bad": { zh: "回答不理想", en: "Bad response" },
+ "message.edit.cancel": { zh: "取消", en: "Cancel" },
+ "message.edit.save": { zh: "保存并提交", en: "Save & Submit" },
// SettingsDialog
- "settings.title": "Settings",
- "settings.language": "Language",
- "settings.theme": "Theme",
- "settings.provider": "AI Provider",
- "settings.model": "Model ID",
- "settings.image_model": "Image Model",
- "settings.api_key": "API Key",
- "settings.base_url": "Base URL (optional)",
- "settings.access_code": "Access Code (optional)",
- "settings.close": "Close",
- "settings.save": "Save",
- "settings.general": "General",
- "settings.theme.desc": "Dark/Light mode for interface and DrawIO canvas.",
- "settings.close_protection": "Prevent accidental close",
- "settings.close_protection.desc": "Show confirmation when leaving the page.",
- "settings.ai_config": "AI Configuration",
- "settings.ai_provider.desc": "Use your own API key to bypass usage limits. Your key is stored locally in your browser and is never stored on the server.",
- "settings.provider.placeholder": "Select provider",
- "settings.provider.default": "Default (Server)",
- "settings.api_key.placeholder": "sk-...",
- "settings.api_key.desc": "Leave empty to use default key",
- "settings.base_url.placeholder": "https://api.openai.com/v1",
- "settings.drawio_style": "DrawIO Style",
- "settings.drawio_style.desc": "Canvas style: ",
- "settings.drawio_style.minimal": "Minimal",
- "settings.drawio_style.sketch": "Sketch",
- "settings.drawio_style.switch": "Switch to ",
- "settings.clear": "Clear Settings",
+ "settings.title": { zh: "设置", en: "Settings" },
+ "settings.language": { zh: "语言", en: "Language" },
+ "settings.theme": { zh: "主题", en: "Theme" },
+ "settings.provider": { zh: "AI 服务商", en: "AI Provider" },
+ "settings.model": { zh: "模型 ID", en: "Model ID" },
+ "settings.image_model": { zh: "绘图模型", en: "Image Model" },
+ "settings.api_key": { zh: "API Key", en: "API Key" },
+ "settings.base_url": { zh: "Base URL(可选)", en: "Base URL (optional)" },
+ "settings.access_code": { zh: "访问码(可选)", en: "Access Code (optional)" },
+ "settings.close": { zh: "关闭", en: "Close" },
+ "settings.save": { zh: "保存", en: "Save" },
+ "settings.general": { zh: "通用设置", en: "General" },
+ "settings.theme.desc": { zh: "界面和 DrawIO 画布的深色/浅色模式。", en: "Dark/Light mode for interface and DrawIO canvas." },
+ "settings.close_protection": { zh: "防误关闭", en: "Prevent accidental close" },
+ "settings.close_protection.desc": { zh: "离开页面时弹出确认提示。", en: "Show confirmation when leaving the page." },
+ "settings.ai_config": { zh: "AI 配置", en: "AI Configuration" },
+ "settings.ai_provider.desc": { zh: "使用你自己的 API Key 可绕过默认额度限制。密钥仅保存在浏览器本地,不会存到服务端。", en: "Use your own API key to bypass usage limits. Your key is stored locally in your browser and is never stored on the server." },
+ "settings.provider.placeholder": { zh: "选择服务商", en: "Select provider" },
+ "settings.provider.default": { zh: "默认(服务端)", en: "Default (Server)" },
+ "settings.api_key.placeholder": { zh: "sk-...", en: "sk-..." },
+ "settings.api_key.desc": { zh: "留空则使用默认密钥", en: "Leave empty to use default key" },
+ "settings.base_url.placeholder": { zh: "https://api.openai.com/v1", en: "https://api.openai.com/v1" },
+ "settings.drawio_style": { zh: "DrawIO 风格", en: "DrawIO Style" },
+ "settings.drawio_style.desc": { zh: "画布风格:", en: "Canvas style: " },
+ "settings.drawio_style.minimal": { zh: "简洁", en: "Minimal" },
+ "settings.drawio_style.sketch": { zh: "手绘", en: "Sketch" },
+ "settings.drawio_style.switch": { zh: "切换为 ", en: "Switch to " },
+ "settings.clear": { zh: "清空设置", en: "Clear Settings" },
// QuotaLimitToast
- "quota.limit.reached": "Daily limit reached",
- "quota.limit.desc": "You have reached your daily limit of {limit} requests.",
- "quota.limit.tip": "Tip: You can use your own API key (click the Settings icon) or self-host the project to bypass these limits.",
- "quota.limit.reset": "Your limit resets tomorrow. Thanks for understanding!",
- "quota.sponsor": "Sponsor",
- "quota.learn_more": "Learn more ->",
+ "quota.limit.reached": { zh: "已达到当日额度", en: "Daily limit reached" },
+ "quota.limit.desc": { zh: "你今天已达到 {limit} 次请求上限。", en: "You have reached your daily limit of {limit} requests." },
+ "quota.limit.tip": { zh: "提示:你可以使用自己的 API Key(点击设置图标)或自托管项目来绕过限制。", en: "Tip: You can use your own API key (click the Settings icon) or self-host the project to bypass these limits." },
+ "quota.limit.reset": { zh: "额度将在明天重置,感谢理解!", en: "Your limit resets tomorrow. Thanks for understanding!" },
+ "quota.sponsor": { zh: "赞助", en: "Sponsor" },
+ "quota.learn_more": { zh: "了解更多 ->", en: "Learn more ->" },
// ResetWarningModal
- "reset.title": "Clear Everything?",
- "reset.desc": "This will clear the current conversation and reset the diagram. This action cannot be undone.",
- "reset.confirm": "Clear Everything",
- "reset.cancel": "Cancel",
+ "reset.title": { zh: "确认清空?", en: "Clear Everything?" },
+ "reset.desc": { zh: "这会清空当前对话并重置流程图,且无法撤销。", en: "This will clear the current conversation and reset the diagram. This action cannot be undone." },
+ "reset.confirm": { zh: "确认清空", en: "Clear Everything" },
+ "reset.cancel": { zh: "取消", en: "Cancel" },
// SaveDialog
- "save.title": "Save Diagram",
- "save.desc": "Choose a format to save your diagram.",
- "save.format": "Format",
- "save.filename": "Filename",
- "save.filename.placeholder": "diagram",
- "save.download": "Download",
+ "save.title": { zh: "保存流程图", en: "Save Diagram" },
+ "save.desc": { zh: "选择保存格式。", en: "Choose a format to save your diagram." },
+ "save.format": { zh: "格式", en: "Format" },
+ "save.filename": { zh: "文件名", en: "Filename" },
+ "save.filename.placeholder": { zh: "diagram", en: "diagram" },
+ "save.download": { zh: "下载", en: "Download" },
// ExamplePanel
- "example.aws.title": "AWS Architecture",
- "example.aws.desc": "Create a cloud architecture diagram with AWS icons",
- "example.flowchart.title": "Replicate Flowchart",
- "example.flowchart.desc": "Upload and replicate an existing flowchart",
- "example.creative.title": "Creative Drawing",
- "example.creative.desc": "Draw something fun and creative",
- "example.cached": "Examples are cached for instant response",
- "example.new": "NEW",
- "examples.title": "Quick Examples",
- "examples.paper.title": "Paper to Diagram",
- "examples.paper.desc": "Upload .pdf, .txt, .md, .json, .csv, .py, .js, .ts and more",
- "examples.animated.title": "Animated Diagram",
- "examples.animated.desc": "Draw a transformer architecture with animated connectors",
- "tooltip.history": "Diagram history",
- "tooltip.save": "Save diagram",
- "tooltip.deep_thinking": "Deep Think",
+ "example.aws.title": { zh: "AWS 架构图", en: "AWS Architecture" },
+ "example.aws.desc": { zh: "用 AWS 图标生成云架构图", en: "Create a cloud architecture diagram with AWS icons" },
+ "example.flowchart.title": { zh: "复刻流程图", en: "Replicate Flowchart" },
+ "example.flowchart.desc": { zh: "上传并复刻已有流程图", en: "Upload and replicate an existing flowchart" },
+ "example.creative.title": { zh: "创意绘图", en: "Creative Drawing" },
+ "example.creative.desc": { zh: "生成有趣的创意图形", en: "Draw something fun and creative" },
+ "example.cached": { zh: "示例已缓存,可快速响应", en: "Examples are cached for instant response" },
+ "example.new": { zh: "新", en: "NEW" },
+ "examples.title": { zh: "快速示例", en: "Quick Examples" },
+ "examples.paper.title": { zh: "论文转流程图", en: "Paper to Diagram" },
+ "examples.paper.desc": { zh: "支持上传 .pdf、.txt、.md、.json、.csv、.py、.js、.ts 等文件", en: "Upload .pdf, .txt, .md, .json, .csv, .py, .js, .ts and more" },
+ "examples.animated.title": { zh: "动画流程图", en: "Animated Diagram" },
+ "examples.animated.desc": { zh: "绘制带动画连线的 Transformer 架构图", en: "Draw a transformer architecture with animated connectors" },
+ "tooltip.history": { zh: "流程图历史", en: "Diagram history" },
+ "tooltip.save": { zh: "保存流程图", en: "Save diagram" },
+ "tooltip.deep_thinking": { zh: "深度思考", en: "Deep Think" },
// HistoryDialog
- "history.title": "Diagram History",
- "history.empty": "No history available yet. Send messages to create diagram history.",
- "history.version": "Version",
- "history.restore": "Restore to Version",
- "history.confirm": "Confirm",
- "history.cancel": "Cancel",
- "history.close": "Close",
+ "history.title": { zh: "流程图历史记录", en: "Diagram History" },
+ "history.empty": { zh: "暂无历史记录,发送消息后会生成历史版本。", en: "No history available yet. Send messages to create diagram history." },
+ "history.version": { zh: "版本", en: "Version" },
+ "history.restore": { zh: "恢复到版本", en: "Restore to Version" },
+ "history.confirm": { zh: "确认", en: "Confirm" },
+ "history.cancel": { zh: "取消", en: "Cancel" },
+ "history.close": { zh: "关闭", en: "Close" },
// GlobalConstraintsDialog
- "global_constraints.title": "Global Constraints",
- "global_constraints.description": "Enter instructions that will be applied to every AI response.",
- "global_constraints.placeholder": "e.g., Always use blue for decision nodes...",
- "tooltip.global_constraints": "Global Constraints",
+ "global_constraints.title": { zh: "全局约束", en: "Global Constraints" },
+ "global_constraints.description": { zh: "填写会应用到每次 AI 回复的约束指令。", en: "Enter instructions that will be applied to every AI response." },
+ "global_constraints.placeholder": { zh: "例如:决策节点统一使用蓝色...", en: "e.g., Always use blue for decision nodes..." },
+ "tooltip.global_constraints": { zh: "全局约束", en: "Global Constraints" },
// Common
- "common.error": "Error",
- "common.loading": "Loading...",
- "common.save": "Save",
- "common.saved": "Saved successfully",
- "common.regenerate_error": "Failed to regenerate: missing history state",
- "common.busy": "System is busy, please wait...",
-} as const;
-
-export const translations = {
- en,
- zh: {
- // ChatPanel
- "app.title": "流程图助手",
- "welcome.title": "用 AI 创建流程图",
- "welcome.desc": "描述你想创建的内容,或上传图片进行复刻",
- "app.about": "关于",
- "chat.panel.show": "展开交互区 (Ctrl+B)",
- "chat.panel.hide": "收起交互区 (Ctrl+B)",
- "chat.panel.title": "流程图交互区",
- "chat.settings": "设置",
- "chat.vertical.title": "AI 对话",
-
- // ChatInput
- "input.placeholder": "描述你的流程图需求,或上传文件...",
- "input.clear": "清空对话",
- "input.upload": "上传文件(图片、PDF、文本)",
- "input.upload_image": "上传图片",
- "input.upload_file": "上传文件",
- "input.upload_file_types": "上传文件(.pdf、.docx、.txt)",
- "input.send": "发送消息",
- "input.stop": "停止生成",
- "input.history": "历史记录",
- "input.history.toggle": "切换历史记录",
- "input.deep_thinking": "深度思考",
-
- // ChatMessageDisplay
- "message.sending": "正在发送消息...",
- "message.parsing_files": "正在解析文件...",
- "message.thinking": "AI 正在思考并生成结果...",
- "message.copy": "复制消息",
- "message.copied": "已复制",
- "message.copy.failed": "复制失败",
- "message.regenerate": "重新生成",
- "message.edit": "编辑消息",
- "message.good": "回答有帮助",
- "message.bad": "回答不理想",
- "message.edit.cancel": "取消",
- "message.edit.save": "保存并提交",
-
- // SettingsDialog
- "settings.title": "设置",
- "settings.language": "语言",
- "settings.theme": "主题",
- "settings.provider": "AI 服务商",
- "settings.model": "模型 ID",
- "settings.image_model": "绘图模型",
- "settings.api_key": "API Key",
- "settings.base_url": "Base URL(可选)",
- "settings.access_code": "访问码(可选)",
- "settings.close": "关闭",
- "settings.save": "保存",
- "settings.general": "通用设置",
- "settings.theme.desc": "界面和 DrawIO 画布的深色/浅色模式。",
- "settings.close_protection": "防误关闭",
- "settings.close_protection.desc": "离开页面时弹出确认提示。",
- "settings.ai_config": "AI 配置",
- "settings.ai_provider.desc": "使用你自己的 API Key 可绕过默认额度限制。密钥仅保存在浏览器本地,不会存到服务端。",
- "settings.provider.placeholder": "选择服务商",
- "settings.provider.default": "默认(服务端)",
- "settings.api_key.placeholder": "sk-...",
- "settings.api_key.desc": "留空则使用默认密钥",
- "settings.base_url.placeholder": "https://api.openai.com/v1",
- "settings.drawio_style": "DrawIO 风格",
- "settings.drawio_style.desc": "画布风格:",
- "settings.drawio_style.minimal": "简洁",
- "settings.drawio_style.sketch": "手绘",
- "settings.drawio_style.switch": "切换为 ",
- "settings.clear": "清空设置",
-
- // QuotaLimitToast
- "quota.limit.reached": "已达到当日额度",
- "quota.limit.desc": "你今天已达到 {limit} 次请求上限。",
- "quota.limit.tip": "提示:你可以使用自己的 API Key(点击设置图标)或自托管项目来绕过限制。",
- "quota.limit.reset": "额度将在明天重置,感谢理解!",
- "quota.sponsor": "赞助",
- "quota.learn_more": "了解更多 ->",
-
- // ResetWarningModal
- "reset.title": "确认清空?",
- "reset.desc": "这会清空当前对话并重置流程图,且无法撤销。",
- "reset.confirm": "确认清空",
- "reset.cancel": "取消",
-
- // SaveDialog
- "save.title": "保存流程图",
- "save.desc": "选择保存格式。",
- "save.format": "格式",
- "save.filename": "文件名",
- "save.filename.placeholder": "diagram",
- "save.download": "下载",
-
- // ExamplePanel
- "example.aws.title": "AWS 架构图",
- "example.aws.desc": "用 AWS 图标生成云架构图",
- "example.flowchart.title": "复刻流程图",
- "example.flowchart.desc": "上传并复刻已有流程图",
- "example.creative.title": "创意绘图",
- "example.creative.desc": "生成有趣的创意图形",
- "example.cached": "示例已缓存,可快速响应",
- "example.new": "新",
- "examples.title": "快速示例",
- "examples.paper.title": "论文转流程图",
- "examples.paper.desc": "支持上传 .pdf、.txt、.md、.json、.csv、.py、.js、.ts 等文件",
- "examples.animated.title": "动画流程图",
- "examples.animated.desc": "绘制带动画连线的 Transformer 架构图",
- "tooltip.history": "流程图历史",
- "tooltip.save": "保存流程图",
- "tooltip.deep_thinking": "深度思考",
-
- // HistoryDialog
- "history.title": "流程图历史记录",
- "history.empty": "暂无历史记录,发送消息后会生成历史版本。",
- "history.version": "版本",
- "history.restore": "恢复到版本",
- "history.confirm": "确认",
- "history.cancel": "取消",
- "history.close": "关闭",
-
- // GlobalConstraintsDialog
- "global_constraints.title": "全局约束",
- "global_constraints.description": "填写会应用到每次 AI 回复的约束指令。",
- "global_constraints.placeholder": "例如:决策节点统一使用蓝色...",
- "tooltip.global_constraints": "全局约束",
-
- // Common
- "common.error": "错误",
- "common.loading": "加载中...",
- "common.save": "保存",
- "common.saved": "保存成功",
- "common.regenerate_error": "重新生成失败:缺少历史状态",
- "common.busy": "系统忙碌中,请稍后...",
- },
-};
+ "common.error": { zh: "错误", en: "Error" },
+ "common.loading": { zh: "加载中...", en: "Loading..." },
+ "common.save": { zh: "保存", en: "Save" },
+ "common.saved": { zh: "保存成功", en: "Saved successfully" },
+ "common.regenerate_error": { zh: "重新生成失败:缺少历史状态", en: "Failed to regenerate: missing history state" },
+ "common.busy": { zh: "系统忙碌中,请稍后...", en: "System is busy, please wait..." },
+} satisfies Dict;
+
+export const { t, useT: useFlowT } = createTranslator(messages);
diff --git a/src/workspaces/flow/next/lib/use-file-processor.tsx b/src/workspaces/flow/next/lib/use-file-processor.tsx
deleted file mode 100644
index ddd106d..0000000
--- a/src/workspaces/flow/next/lib/use-file-processor.tsx
+++ /dev/null
@@ -1,241 +0,0 @@
-"use client"
-
-import { useState } from "react"
-import { toast } from "sonner"
-import {
- extractPdfText,
- extractWordText,
- extractTextFileContent,
- extractPdfVisualAssets,
- extractWordVisualAssets,
- extractThirdPartyVisualAssets,
- extractLatexZipText,
- extractLatexZipVisualAssets,
- extractLatexTarGzText,
- extractLatexTarGzVisualAssets,
- type ExtractedVisualAsset,
- isPdfFile,
- isWordFile,
- isTextFile,
- isZipFile,
- isTarGzFile,
- MAX_EXTRACTED_CHARS,
-} from "@/workspaces/flow/next/lib/pdf-utils"
-import { getAIConfig } from "@/ai/client"
-
-export interface FileData {
- text: string
- charCount: number
- isExtracting: boolean
- visualAssets?: ExtractedVisualAsset[]
-}
-
-type ParserSource = "third_party" | "local" | "third_party_fallback_local"
-
-const reportFileParserSource = async (params: {
- workspace: "flow" | "ppt" | "unknown"
- file: File
- parserSource: ParserSource
- detail?: string
-}) => {
- try {
- await fetch("/api/log-file-parser", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- workspace: params.workspace,
- fileName: params.file.name,
- mimeType: params.file.type || "",
- fileSize: params.file.size || 0,
- parserSource: params.parserSource,
- detail: params.detail || "",
- }),
- keepalive: true,
- })
- } catch (e) {
- console.warn("Failed to report file parser source", e)
- }
-}
-
-/**
- * Hook for processing file uploads, especially PDFs and text files.
- * Handles text extraction, character limit validation, and cleanup.
- */
-export function useFileProcessor(workspace: "flow" | "ppt" | "unknown" = "unknown") {
- const [files, setFiles] = useState<File[]>([])
- const [pdfData, setPdfData] = useState<Map<File, FileData>>(new Map())
-
- const handleFileChange = async (newFiles: File[]) => {
- setFiles(newFiles)
-
- // Extract text immediately for new PDF/text files
- for (const file of newFiles) {
- const needsExtraction =
- (isPdfFile(file) ||
- isWordFile(file) ||
- isTextFile(file) ||
- isZipFile(file) ||
- isTarGzFile(file)) &&
- !pdfData.has(file)
- if (needsExtraction) {
- // Mark as extracting
- setPdfData((prev) => {
- const next = new Map(prev)
- next.set(file, {
- text: "",
- charCount: 0,
- isExtracting: true,
- })
- return next
- })
-
- // Extract text asynchronously
- try {
- const aiConfig = getAIConfig()
- const parserToken = String(aiConfig.fileParserApiToken || "").trim()
- const parserBase = "https://mineru.net"
- const supportsThirdParty = isPdfFile(file) || isWordFile(file)
- // Rule: if MinerU token is configured, prefer third-party parser;
- // otherwise use local extraction.
- const useThirdPartyVisualParser =
- Boolean(parserToken) && supportsThirdParty
-
- let text: string
- let visualAssets: ExtractedVisualAsset[] = []
- if (isPdfFile(file)) {
- text = await extractPdfText(file)
- if (useThirdPartyVisualParser) {
- try {
- visualAssets = await extractThirdPartyVisualAssets(file, {
- apiBase: parserBase,
- apiToken: parserToken,
- })
- void reportFileParserSource({
- workspace,
- file,
- parserSource: "third_party",
- detail: "pdf",
- })
- } catch (e) {
- console.error("Third-party parser failed, fallback to local PDF extraction:", e)
- visualAssets = await extractPdfVisualAssets(file)
- void reportFileParserSource({
- workspace,
- file,
- parserSource: "third_party_fallback_local",
- detail: "pdf",
- })
- }
- } else {
- visualAssets = await extractPdfVisualAssets(file)
- void reportFileParserSource({
- workspace,
- file,
- parserSource: "local",
- detail: "pdf",
- })
- }
- } else if (isWordFile(file)) {
- text = await extractWordText(file)
- if (useThirdPartyVisualParser) {
- try {
- visualAssets = await extractThirdPartyVisualAssets(file, {
- apiBase: parserBase,
- apiToken: parserToken,
- })
- void reportFileParserSource({
- workspace,
- file,
- parserSource: "third_party",
- detail: "word",
- })
- } catch (e) {
- console.error("Third-party parser failed, fallback to local Word extraction:", e)
- visualAssets = await extractWordVisualAssets(file)
- void reportFileParserSource({
- workspace,
- file,
- parserSource: "third_party_fallback_local",
- detail: "word",
- })
- }
- } else {
- visualAssets = await extractWordVisualAssets(file)
- void reportFileParserSource({
- workspace,
- file,
- parserSource: "local",
- detail: "word",
- })
- }
- } else if (isZipFile(file)) {
- // LaTeX bundle (.zip): parse tex + includegraphics to extract original figures.
- text = await extractLatexZipText(file)
- visualAssets = await extractLatexZipVisualAssets(file)
- } else if (isTarGzFile(file)) {
- // LaTeX bundle (.tar.gz/.tgz)
- text = await extractLatexTarGzText(file)
- visualAssets = await extractLatexTarGzVisualAssets(file)
- } else {
- text = await extractTextFileContent(file)
- }
-
- // Check character limit
- if (text.length > MAX_EXTRACTED_CHARS) {
- const limitK = MAX_EXTRACTED_CHARS / 1000
- toast.error(
- `${file.name}: Content exceeds ${limitK}k character limit (${(text.length / 1000).toFixed(1)}k chars)`,
- )
- setPdfData((prev) => {
- const next = new Map(prev)
- next.delete(file)
- return next
- })
- // Remove the file from the list
- setFiles((prev) => prev.filter((f) => f !== file))
- continue
- }
-
- setPdfData((prev) => {
- const next = new Map(prev)
- next.set(file, {
- text,
- charCount: text.length,
- isExtracting: false,
- visualAssets,
- })
- return next
- })
- } catch (error) {
- console.error("Failed to extract text:", error)
- toast.error(`Failed to read file: ${file.name}`)
- setPdfData((prev) => {
- const next = new Map(prev)
- next.delete(file)
- return next
- })
- }
- }
- }
-
- // Clean up pdfData for removed files
- setPdfData((prev) => {
- const next = new Map(prev)
- for (const key of prev.keys()) {
- if (!newFiles.includes(key)) {
- next.delete(key)
- }
- }
- return next
- })
- }
-
- return {
- files,
- pdfData,
- visualAssets: Array.from(pdfData.values()).flatMap((x) => x.visualAssets || []),
- handleFileChange,
- setFiles, // Export for external control (e.g., clearing files)
- }
-}
-
diff --git a/src/workspaces/flow/next/page.tsx b/src/workspaces/flow/next/page.tsx
index 8ab5a57..fbc4a5e 100644
--- a/src/workspaces/flow/next/page.tsx
+++ b/src/workspaces/flow/next/page.tsx
@@ -8,7 +8,7 @@ import {
ResizablePanel,
ResizablePanelGroup,
type PanelImperativeHandle,
-} from "@/workspaces/flow/next/components/ui/resizable"
+} from "@/shared/ui/resizable"
import { useDiagram } from "@/workspaces/flow/next/contexts/diagram-context"
const drawioBaseUrl =
diff --git a/src/workspaces/ppt/PptWorkspaceShell.tsx b/src/workspaces/ppt/PptWorkspaceShell.tsx
index 1288a3d..3cd0d87 100644
--- a/src/workspaces/ppt/PptWorkspaceShell.tsx
+++ b/src/workspaces/ppt/PptWorkspaceShell.tsx
@@ -1,18 +1,17 @@
import React, { useEffect, useRef, useState } from "react";
-import { cn } from "@/lib/utils";
-import { t } from "@/lib/i18n";
-import { useUiLanguage } from "@/lib/use-ui-language";
+import { cn } from "@/shared/lib/utils";
+import { t, useUiLanguage } from "@/shared/i18n";
import {
ResizableHandle,
ResizablePanel,
ResizablePanelGroup,
type PanelImperativeHandle,
-} from "@/workspaces/ppt/ui/resizable";
+} from "@/shared/ui/resizable";
import {
PPT_OUTLINE_EDIT_SYSTEM_PROMPT,
PPT_SLIDES_EDIT_SYSTEM_PROMPT,
} from "@/lib/system-prompts";
-import { clearPersistedPptWorkspaceState } from "@/lib/ppt-persistence";
+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";
@@ -248,7 +247,7 @@ export function PptWorkspaceShell() {
localStorage.removeItem(PPT_WORKSPACE_STORAGE_KEY);
} catch {
}
- void clearPersistedPptWorkspaceState().catch((e) => {
+ void pptStore.clear(PPT_STATE_KEY).catch((e) => {
console.error("Failed to clear persisted PPT workspace", e);
});
try {
diff --git a/src/workspaces/ppt/chat/ChatInput.tsx b/src/workspaces/ppt/chat/ChatInput.tsx
index 74ab3eb..cad4045 100644
--- a/src/workspaces/ppt/chat/ChatInput.tsx
+++ b/src/workspaces/ppt/chat/ChatInput.tsx
@@ -1,11 +1,10 @@
import React, { useRef, useEffect, useMemo, useState, useCallback } from 'react';
import { Send, FileText, ImageIcon, History, Square, Trash2 } from 'lucide-react';
-import { cn } from '@/lib/utils';
+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 '@/lib/use-file-processor';
-import { t } from "@/lib/i18n";
-import { useUiLanguage } from "@/lib/use-ui-language";
+import { useFileProcessor } from '@/shared/files/use-file-processor';
+import { t, useUiLanguage } from "@/shared/i18n";
type RichInputSegment =
| { type: "text"; text: string }
@@ -65,7 +64,7 @@ export function ChatInput({
const richAppliedRef = useRef<string>("");
const [richHasFocus, setRichHasFocus] = useState(false);
- const { files, handleFileChange, setFiles, pdfData } = useFileProcessor();
+ const { files, handleFileChange, setFiles, pdfData } = useFileProcessor("ppt");
const isRich = !!(richSegments && onRichSegmentsChange);
// Sync controlled files if provided
diff --git a/src/workspaces/ppt/chat/ChatMessageDisplay.tsx b/src/workspaces/ppt/chat/ChatMessageDisplay.tsx
index 73613f7..5022d38 100644
--- a/src/workspaces/ppt/chat/ChatMessageDisplay.tsx
+++ b/src/workspaces/ppt/chat/ChatMessageDisplay.tsx
@@ -18,10 +18,10 @@ import {
import ReactMarkdown from "react-markdown";
import remarkGfm from 'remark-gfm';
import { Reasoning, ReasoningContent, ReasoningTrigger } from "@/workspaces/ppt/chat/components/reasoning";
-import { ScrollArea } from "@/workspaces/ppt/ui/scroll-area";
-import { CodeBlock } from "@/workspaces/ppt/ui/code-block";
-import { useUiLanguage } from "@/lib/use-ui-language";
-import { cn } from "@/lib/utils";
+import { ScrollArea } from "@/shared/ui/scroll-area";
+import { CodeBlock } from "@/workspaces/ppt/chat/code-block";
+import { useUiLanguage } from "@/shared/i18n";
+import { cn } from "@/shared/lib/utils";
// Types
export interface MessagePart {
diff --git a/src/workspaces/ppt/chat/ChatPanel.tsx b/src/workspaces/ppt/chat/ChatPanel.tsx
index b7fa100..3191183 100644
--- a/src/workspaces/ppt/chat/ChatPanel.tsx
+++ b/src/workspaces/ppt/chat/ChatPanel.tsx
@@ -1,6 +1,6 @@
import React, { useState, useRef, useEffect } from 'react';
import { PanelRightClose, PanelRightOpen } from 'lucide-react';
-import { cn } from '@/lib/utils';
+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';
@@ -9,13 +9,12 @@ import { ChatMessageDisplay, UIMessage } from '@/workspaces/ppt/chat/ChatMessage
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 { useFileProcessor } from '@/lib/use-file-processor';
+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';
import flowPatchAgentPrompt from "../../../../agent/flow/patch.md?raw";
import flowReplaceAgentPrompt from "../../../../agent/flow/replace.md?raw";
-import { t } from "@/lib/i18n";
-import { useUiLanguage } from "@/lib/use-ui-language";
+import { t, useUiLanguage } from "@/shared/i18n";
interface Attachment {
id: string;
@@ -634,12 +633,12 @@ export function ChatPanel({
}
} else {
// Text/PDF
- const { extractPdfText, extractTextFileContent, isPdfFile } = await import('@/lib/pdf-utils');
+ const { extractPdfText, extractTextFileContent, isPdfFile } = await import('@/shared/files');
try {
let content = "";
if (isPdfFile(file)) {
try {
- const { getPdfDocumentFromUrl, renderPdfPageToCanvas } = await import("@/lib/pdf-utils");
+ const { getPdfDocumentFromUrl, renderPdfPageToCanvas } = await import("@/shared/files");
const objectUrl = URL.createObjectURL(file);
try {
const pdf = await getPdfDocumentFromUrl(objectUrl);
diff --git a/src/workspaces/ppt/ui/code-block.tsx b/src/workspaces/ppt/chat/code-block.tsx
similarity index 99%
rename from src/workspaces/ppt/ui/code-block.tsx
rename to src/workspaces/ppt/chat/code-block.tsx
index 9eab18f..82c957f 100644
--- a/src/workspaces/ppt/ui/code-block.tsx
+++ b/src/workspaces/ppt/chat/code-block.tsx
@@ -1,7 +1,7 @@
import React, { useMemo, useRef, useState } from 'react';
import { Highlight, themes, type Language } from "prism-react-renderer";
import { ChevronRight, Loader2 } from 'lucide-react';
-import { cn } from '@/lib/utils';
+import { cn } from '@/shared/lib/utils';
interface CodeBlockProps {
code: string;
diff --git a/src/workspaces/ppt/chat/components/button-with-tooltip.tsx b/src/workspaces/ppt/chat/components/button-with-tooltip.tsx
index b1306b1..d99cf2c 100644
--- a/src/workspaces/ppt/chat/components/button-with-tooltip.tsx
+++ b/src/workspaces/ppt/chat/components/button-with-tooltip.tsx
@@ -1,12 +1,12 @@
import type { VariantProps } from "class-variance-authority"
import type React from "react"
-import { Button, type buttonVariants } from "@/workspaces/ppt/ui/button"
+import { Button, type buttonVariants } from "@/shared/ui/button"
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
-} from "@/workspaces/ppt/ui/tooltip"
+} from "@/shared/ui/tooltip"
interface ButtonWithTooltipProps
extends React.ComponentProps<"button">,
diff --git a/src/workspaces/ppt/chat/components/reasoning.tsx b/src/workspaces/ppt/chat/components/reasoning.tsx
index 629358a..27be22c 100644
--- a/src/workspaces/ppt/chat/components/reasoning.tsx
+++ b/src/workspaces/ppt/chat/components/reasoning.tsx
@@ -6,8 +6,8 @@ import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
-} from "@/workspaces/ppt/ui/collapsible"
-import { cn } from "@/lib/utils"
+} from "@/shared/ui/collapsible"
+import { cn } from "@/shared/lib/utils"
import { Shimmer } from "./shimmer"
type ReasoningContextValue = {
diff --git a/src/workspaces/ppt/chat/components/shimmer.tsx b/src/workspaces/ppt/chat/components/shimmer.tsx
index e285cd7..8651161 100644
--- a/src/workspaces/ppt/chat/components/shimmer.tsx
+++ b/src/workspaces/ppt/chat/components/shimmer.tsx
@@ -6,7 +6,7 @@ import {
memo,
useMemo,
} from "react"
-import { cn } from "@/lib/utils"
+import { cn } from "@/shared/lib/utils"
export type TextShimmerProps = {
children: string
diff --git a/src/workspaces/ppt/chat/file-preview-list.tsx b/src/workspaces/ppt/chat/file-preview-list.tsx
index 01d625e..b437992 100644
--- a/src/workspaces/ppt/chat/file-preview-list.tsx
+++ b/src/workspaces/ppt/chat/file-preview-list.tsx
@@ -2,8 +2,8 @@
import { FileCode, FileText, Loader2, X } from "lucide-react"
import { useEffect, useRef, useState } from "react"
-import { isPdfFile, isTextFile } from "@/lib/pdf-utils"
-import { type FileData } from "@/lib/use-file-processor"
+import { isPdfFile, isTextFile } from "@/shared/files"
+import { type FileData } from "@/shared/files/use-file-processor"
function formatCharCount(count: number): string {
if (count >= 1000) {
diff --git a/src/workspaces/ppt/chat/global-constraints-dialog.tsx b/src/workspaces/ppt/chat/global-constraints-dialog.tsx
index b2481e8..0312bd4 100644
--- a/src/workspaces/ppt/chat/global-constraints-dialog.tsx
+++ b/src/workspaces/ppt/chat/global-constraints-dialog.tsx
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react"
-import { Button } from "@/workspaces/ppt/ui/button"
+import { Button } from "@/shared/ui/button"
import {
Dialog,
DialogContent,
@@ -7,10 +7,9 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
-} from "@/workspaces/ppt/ui/dialog"
-import { Textarea } from "@/workspaces/ppt/ui/textarea"
-import { useUiLanguage } from "@/lib/use-ui-language";
-import { t } from "@/lib/i18n";
+} 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"
diff --git a/src/workspaces/ppt/chat/history-dialog.tsx b/src/workspaces/ppt/chat/history-dialog.tsx
index 036f891..e03c94a 100644
--- a/src/workspaces/ppt/chat/history-dialog.tsx
+++ b/src/workspaces/ppt/chat/history-dialog.tsx
@@ -4,12 +4,11 @@ import {
DialogContent,
DialogHeader,
DialogTitle,
-} from "@/workspaces/ppt/ui/dialog"
-import { Button } from '@/workspaces/ppt/ui/button';
+} from "@/shared/ui/dialog"
+import { Button } from '@/shared/ui/button';
import { Clock, RotateCcw, FileCode, Trash2 } from 'lucide-react';
-import { ScrollArea } from '@/workspaces/ppt/ui/scroll-area';
-import { useUiLanguage } from "@/lib/use-ui-language";
-import { t } from "@/lib/i18n";
+import { ScrollArea } from '@/shared/ui/scroll-area';
+import { t, useUiLanguage } from "@/shared/i18n";
export interface HistoryItem {
id: string;
diff --git a/src/workspaces/ppt/chat/reset-warning-modal.tsx b/src/workspaces/ppt/chat/reset-warning-modal.tsx
index d6a5c81..67dc47b 100644
--- a/src/workspaces/ppt/chat/reset-warning-modal.tsx
+++ b/src/workspaces/ppt/chat/reset-warning-modal.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { Button } from "@/workspaces/ppt/ui/button"
+import { Button } from "@/shared/ui/button"
import {
Dialog,
DialogContent,
@@ -7,9 +7,8 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
-} from "@/workspaces/ppt/ui/dialog"
-import { t } from "@/lib/i18n";
-import { useUiLanguage } from "@/lib/use-ui-language";
+} from "@/shared/ui/dialog"
+import { t, useUiLanguage } from "@/shared/i18n";
interface ResetWarningModalProps {
open: boolean
diff --git a/src/workspaces/ppt/storage.ts b/src/workspaces/ppt/storage.ts
new file mode 100644
index 0000000..18afb55
--- /dev/null
+++ b/src/workspaces/ppt/storage.ts
@@ -0,0 +1,7 @@
+import { createWorkspaceStore } from "@/shared/storage/indexed-db-store";
+
+/** Database name is load-bearing: changing it orphans everything users saved. */
+export const pptStore = createWorkspaceStore("CanvasAnvilPptWorkspaceDB");
+
+export const PPT_STATE_KEY = "primary";
+export const PPT_TEMPLATE_LIBRARY_KEY = "template-library";
diff --git a/src/workspaces/ppt/ui/collapsible.tsx b/src/workspaces/ppt/ui/collapsible.tsx
deleted file mode 100644
index 9fa4894..0000000
--- a/src/workspaces/ppt/ui/collapsible.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-"use client"
-
-import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
-
-const Collapsible = CollapsiblePrimitive.Root
-
-const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger
-
-const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent
-
-export { Collapsible, CollapsibleTrigger, CollapsibleContent }
diff --git a/src/workspaces/ppt/ui/context-menu.tsx b/src/workspaces/ppt/ui/context-menu.tsx
deleted file mode 100644
index 3e52999..0000000
--- a/src/workspaces/ppt/ui/context-menu.tsx
+++ /dev/null
@@ -1,198 +0,0 @@
-import * as React from "react"
-import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
-import { Check, ChevronRight, Circle } from "lucide-react"
-
-import { cn } from "@/lib/utils"
-
-const ContextMenu = ContextMenuPrimitive.Root
-
-const ContextMenuTrigger = ContextMenuPrimitive.Trigger
-
-const ContextMenuGroup = ContextMenuPrimitive.Group
-
-const ContextMenuPortal = ContextMenuPrimitive.Portal
-
-const ContextMenuSub = ContextMenuPrimitive.Sub
-
-const ContextMenuRadioGroup = ContextMenuPrimitive.RadioGroup
-
-const ContextMenuSubTrigger = React.forwardRef<
- React.ElementRef<typeof ContextMenuPrimitive.SubTrigger>,
- React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubTrigger> & {
- inset?: boolean
- }
->(({ className, inset, children, ...props }, ref) => (
- <ContextMenuPrimitive.SubTrigger
- ref={ref}
- className={cn(
- "flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
- inset && "pl-8",
- className
- )}
- {...props}
- >
- {children}
- <ChevronRight className="ml-auto h-4 w-4" />
- </ContextMenuPrimitive.SubTrigger>
-))
-ContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName
-
-const ContextMenuSubContent = React.forwardRef<
- React.ElementRef<typeof ContextMenuPrimitive.SubContent>,
- React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubContent>
->(({ className, ...props }, ref) => (
- <ContextMenuPrimitive.SubContent
- ref={ref}
- className={cn(
- "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
- className
- )}
- {...props}
- />
-))
-ContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName
-
-const ContextMenuContent = React.forwardRef<
- React.ElementRef<typeof ContextMenuPrimitive.Content>,
- React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Content>
->(({ className, ...props }, ref) => (
- <ContextMenuPrimitive.Portal>
- <ContextMenuPrimitive.Content
- ref={ref}
- className={cn(
- "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md animate-in fade-in-80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
- className
- )}
- {...props}
- />
- </ContextMenuPrimitive.Portal>
-))
-ContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName
-
-const ContextMenuItem = React.forwardRef<
- React.ElementRef<typeof ContextMenuPrimitive.Item>,
- React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Item> & {
- inset?: boolean
- }
->(({ className, inset, ...props }, ref) => (
- <ContextMenuPrimitive.Item
- ref={ref}
- className={cn(
- "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
- inset && "pl-8",
- className
- )}
- {...props}
- />
-))
-ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName
-
-const ContextMenuCheckboxItem = React.forwardRef<
- React.ElementRef<typeof ContextMenuPrimitive.CheckboxItem>,
- React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.CheckboxItem>
->(({ className, children, checked, ...props }, ref) => (
- <ContextMenuPrimitive.CheckboxItem
- ref={ref}
- className={cn(
- "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
- className
- )}
- checked={checked}
- {...props}
- >
- <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
- <ContextMenuPrimitive.ItemIndicator>
- <Check className="h-4 w-4" />
- </ContextMenuPrimitive.ItemIndicator>
- </span>
- {children}
- </ContextMenuPrimitive.CheckboxItem>
-))
-ContextMenuCheckboxItem.displayName =
- ContextMenuPrimitive.CheckboxItem.displayName
-
-const ContextMenuRadioItem = React.forwardRef<
- React.ElementRef<typeof ContextMenuPrimitive.RadioItem>,
- React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.RadioItem>
->(({ className, children, ...props }, ref) => (
- <ContextMenuPrimitive.RadioItem
- ref={ref}
- className={cn(
- "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
- className
- )}
- {...props}
- >
- <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
- <ContextMenuPrimitive.ItemIndicator>
- <Circle className="h-2 w-2 fill-current" />
- </ContextMenuPrimitive.ItemIndicator>
- </span>
- {children}
- </ContextMenuPrimitive.RadioItem>
-))
-ContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName
-
-const ContextMenuLabel = React.forwardRef<
- React.ElementRef<typeof ContextMenuPrimitive.Label>,
- React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Label> & {
- inset?: boolean
- }
->(({ className, inset, ...props }, ref) => (
- <ContextMenuPrimitive.Label
- ref={ref}
- className={cn(
- "px-2 py-1.5 text-sm font-semibold text-foreground",
- inset && "pl-8",
- className
- )}
- {...props}
- />
-))
-ContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName
-
-const ContextMenuSeparator = React.forwardRef<
- React.ElementRef<typeof ContextMenuPrimitive.Separator>,
- React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Separator>
->(({ className, ...props }, ref) => (
- <ContextMenuPrimitive.Separator
- ref={ref}
- className={cn("-mx-1 my-1 h-px bg-border", className)}
- {...props}
- />
-))
-ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName
-
-const ContextMenuShortcut = ({
- className,
- ...props
-}: React.HTMLAttributes<HTMLSpanElement>) => {
- return (
- <span
- className={cn(
- "ml-auto text-xs tracking-widest text-muted-foreground",
- className
- )}
- {...props}
- />
- )
-}
-ContextMenuShortcut.displayName = "ContextMenuShortcut"
-
-export {
- ContextMenu,
- ContextMenuTrigger,
- ContextMenuContent,
- ContextMenuItem,
- ContextMenuCheckboxItem,
- ContextMenuRadioItem,
- ContextMenuLabel,
- ContextMenuSeparator,
- ContextMenuShortcut,
- ContextMenuGroup,
- ContextMenuPortal,
- ContextMenuSub,
- ContextMenuSubContent,
- ContextMenuSubTrigger,
- ContextMenuRadioGroup,
-}
diff --git a/src/workspaces/ppt/ui/dialog.tsx b/src/workspaces/ppt/ui/dialog.tsx
deleted file mode 100644
index 0245804..0000000
--- a/src/workspaces/ppt/ui/dialog.tsx
+++ /dev/null
@@ -1,135 +0,0 @@
-"use client"
-
-import * as React from "react"
-import * as DialogPrimitive from "@radix-ui/react-dialog"
-import { XIcon } from "lucide-react"
-
-import { cn } from "@/lib/utils"
-
-function Dialog({
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Root>) {
- return <DialogPrimitive.Root data-slot="dialog" {...props} />
-}
-
-function DialogTrigger({
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
- return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
-}
-
-function DialogPortal({
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
- return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
-}
-
-function DialogClose({
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Close>) {
- return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
-}
-
-function DialogOverlay({
- className,
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
- return (
- <DialogPrimitive.Overlay
- data-slot="dialog-overlay"
- className={cn(
- "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
- className
- )}
- {...props}
- />
- )
-}
-
-function DialogContent({
- className,
- children,
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Content>) {
- return (
- <DialogPortal data-slot="dialog-portal">
- <DialogOverlay />
- <DialogPrimitive.Content
- data-slot="dialog-content"
- className={cn(
- "bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
- className
- )}
- {...props}
- >
- {children}
- <DialogPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-none disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
- <XIcon />
- <span className="sr-only">Close</span>
- </DialogPrimitive.Close>
- </DialogPrimitive.Content>
- </DialogPortal>
- )
-}
-
-function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
- return (
- <div
- data-slot="dialog-header"
- className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
- {...props}
- />
- )
-}
-
-function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
- return (
- <div
- data-slot="dialog-footer"
- className={cn(
- "flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
- className
- )}
- {...props}
- />
- )
-}
-
-function DialogTitle({
- className,
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Title>) {
- return (
- <DialogPrimitive.Title
- data-slot="dialog-title"
- className={cn("text-lg leading-none font-semibold", className)}
- {...props}
- />
- )
-}
-
-function DialogDescription({
- className,
- ...props
-}: React.ComponentProps<typeof DialogPrimitive.Description>) {
- return (
- <DialogPrimitive.Description
- data-slot="dialog-description"
- className={cn("text-muted-foreground text-sm", className)}
- {...props}
- />
- )
-}
-
-export {
- Dialog,
- DialogClose,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogOverlay,
- DialogPortal,
- DialogTitle,
- DialogTrigger,
-}
diff --git a/src/workspaces/ppt/ui/resizable.tsx b/src/workspaces/ppt/ui/resizable.tsx
deleted file mode 100644
index 73c6e45..0000000
--- a/src/workspaces/ppt/ui/resizable.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-import { GripVertical } from "lucide-react"
-import { Panel, Group, Separator, type PanelImperativeHandle } from "react-resizable-panels"
-
-import { cn } from "@/lib/utils"
-
-const ResizablePanelGroup = ({
- className,
- ...props
-}: React.ComponentProps<typeof Group>) => (
- <Group
- className={cn(
- "flex h-full w-full data-[panel-group-direction=vertical]:flex-col",
- className
- )}
- {...props}
- />
-)
-
-const ResizablePanel = Panel
-
-const ResizableHandle = ({
- withHandle,
- className,
- ...props
-}: React.ComponentProps<typeof Separator> & {
- withHandle?: boolean
-}) => (
- <Separator
- className={cn(
- "relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",
- className
- )}
- {...props}
- >
- {withHandle && (
- <div className="z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border">
- <GripVertical className="h-2.5 w-2.5" />
- </div>
- )}
- </Separator>
-)
-
-export { ResizablePanelGroup, ResizablePanel, ResizableHandle }
-export type { PanelImperativeHandle }
diff --git a/src/workspaces/ppt/ui/textarea.tsx b/src/workspaces/ppt/ui/textarea.tsx
deleted file mode 100644
index f2ab8f2..0000000
--- a/src/workspaces/ppt/ui/textarea.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-import * as React from "react"
-
-import { cn } from "@/lib/utils"
-
-function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
- return (
- <textarea
- data-slot="textarea"
- className={cn(
- "border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-sm transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
- className
- )}
- {...props}
- />
- )
-}
-
-export { Textarea }
diff --git a/src/workspaces/ppt/ui/tooltip.tsx b/src/workspaces/ppt/ui/tooltip.tsx
deleted file mode 100644
index 30fc44d..0000000
--- a/src/workspaces/ppt/ui/tooltip.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-"use client"
-
-import * as React from "react"
-import * as TooltipPrimitive from "@radix-ui/react-tooltip"
-
-import { cn } from "@/lib/utils"
-
-const TooltipProvider = TooltipPrimitive.Provider
-
-const Tooltip = TooltipPrimitive.Root
-
-const TooltipTrigger = TooltipPrimitive.Trigger
-
-const TooltipContent = React.forwardRef<
- React.ElementRef<typeof TooltipPrimitive.Content>,
- React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
->(({ className, sideOffset = 4, ...props }, ref) => (
- <TooltipPrimitive.Content
- ref={ref}
- sideOffset={sideOffset}
- className={cn(
- "z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
- className
- )}
- {...props}
- />
-))
-TooltipContent.displayName = TooltipPrimitive.Content.displayName
-
-export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
diff --git a/src/workspaces/ppt/workspace/PptWorkspace.tsx b/src/workspaces/ppt/workspace/PptWorkspace.tsx
index d2aefcd..95f5484 100644
--- a/src/workspaces/ppt/workspace/PptWorkspace.tsx
+++ b/src/workspaces/ppt/workspace/PptWorkspace.tsx
@@ -3,25 +3,19 @@ import { motion } from "framer-motion";
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';
-import {
- clearPersistedPptWorkspaceState,
- readPersistedPptTemplateLibraryState,
- readPersistedPptWorkspaceState,
- savePersistedPptTemplateLibraryState,
- savePersistedPptWorkspaceState,
-} from '@/lib/ppt-persistence';
+import { PPT_STATE_KEY, PPT_TEMPLATE_LIBRARY_KEY, pptStore } from "@/workspaces/ppt/storage";
import { Loader2, Plus, Image as ImageIcon, MessageSquarePlus, Upload, Presentation, Sparkles, Check, Play, FileText, Download, Lightbulb, X, ArrowLeft, ArrowRight, Eye, Trash2, Maximize2, Minimize2, RefreshCcw } from 'lucide-react';
import {
ContextMenu,
ContextMenuContent,
ContextMenuItem,
ContextMenuTrigger,
-} from "@/workspaces/ppt/ui/context-menu";
-import { Button } from "@/workspaces/ppt/ui/button";
-import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/workspaces/ppt/ui/dialog";
-import { Textarea } from "@/workspaces/ppt/ui/textarea";
-import { useUiLanguage } from "@/lib/use-ui-language";
-import { useFileProcessor as useFlowFileProcessor } from "@/workspaces/flow/next/lib/use-file-processor";
+} from "@/shared/ui/context-menu";
+import { Button } from "@/shared/ui/button";
+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/shared/ui/dialog";
+import { Textarea } from "@/shared/ui/textarea";
+import { useUiLanguage } from "@/shared/i18n";
+import { useFileProcessor as useFlowFileProcessor } from "@/shared/files/use-file-processor";
import {
canvasAnvilToEditorSlide,
editorSlideToExportPayload,
@@ -1038,7 +1032,7 @@ export function PptWorkspace({
void (async () => {
try {
- const raw = await readPersistedPptWorkspaceState<any>();
+ const raw = await pptStore.read<any>(PPT_STATE_KEY);
if (cancelled || !raw || typeof raw !== "object") return;
const persistedState = migrateLegacyTextlessVersions(raw);
const snapshotState =
@@ -1167,7 +1161,7 @@ export function PptWorkspace({
void (async () => {
try {
- const persistedTemplateLibrary = await readPersistedPptTemplateLibraryState<any>();
+ const persistedTemplateLibrary = await pptStore.read<any>(PPT_TEMPLATE_LIBRARY_KEY);
if (cancelled || !persistedTemplateLibrary || typeof persistedTemplateLibrary !== "object") return;
setUploadedTemplates(normalizePersistedUploadedTemplates(persistedTemplateLibrary.uploadedTemplates));
setHiddenPresetTemplateIds(normalizePersistedStringArray(persistedTemplateLibrary.hiddenPresetTemplateIds));
@@ -1193,7 +1187,7 @@ export function PptWorkspace({
useEffect(() => {
if (typeof window === "undefined") return;
if (!isTemplateLibraryHydrated) return;
- void savePersistedPptTemplateLibraryState({
+ void pptStore.save(PPT_TEMPLATE_LIBRARY_KEY, {
uploadedTemplates,
hiddenPresetTemplateIds,
updatedAt: Date.now(),
@@ -1260,7 +1254,7 @@ export function PptWorkspace({
} catch (e) {
console.error("Failed to persist PPT workspace snapshot to localStorage", e);
}
- void savePersistedPptWorkspaceState(workspaceState).catch((e) => {
+ void pptStore.save(PPT_STATE_KEY, workspaceState).catch((e) => {
console.error("Failed to persist PPT workspace to IndexedDB", e);
});
}, [
@@ -4413,7 +4407,7 @@ export function PptWorkspace({
};
const extractPdfPagesAsImages = async (file: File) => {
- const { getPdfDocumentFromUrl, renderPdfPageToCanvas } = await import("@/lib/pdf-utils");
+ const { getPdfDocumentFromUrl, renderPdfPageToCanvas } = await import("@/shared/files");
const objectUrl = URL.createObjectURL(file);
try {
const pdf = await getPdfDocumentFromUrl(objectUrl);
@@ -5287,7 +5281,7 @@ export function PptWorkspace({
localStorage.removeItem(PPT_WORKSPACE_STORAGE_KEY);
} catch {
}
- void clearPersistedPptWorkspaceState().catch((e) => {
+ void pptStore.clear(PPT_STATE_KEY).catch((e) => {
console.error("Failed to clear persisted PPT workspace", e);
});
setLocalSlides([]);