增加文件管理器,增加文件编辑
This commit is contained in:
@@ -35,7 +35,7 @@ import { SplitPane } from "@/components/ui/split-pane";
|
||||
import { WebviewPreview } from "./WebviewPreview";
|
||||
import { FileExplorerPanel } from "./FileExplorerPanel";
|
||||
import { GitPanel } from "./GitPanel";
|
||||
import { FileEditor } from "./FileEditor";
|
||||
import { FileEditorEnhanced } from "./FileEditorEnhanced";
|
||||
import type { ClaudeStreamMessage } from "./AgentExecution";
|
||||
import { useVirtualizer } from "@tanstack/react-virtual";
|
||||
import { useTrackEvent, useComponentMetrics, useWorkflowTracking } from "@/hooks";
|
||||
@@ -1504,9 +1504,9 @@ export const ClaudeCodeSession: React.FC<ClaudeCodeSessionProps> = ({
|
||||
className="h-full"
|
||||
/>
|
||||
) : editingFile ? (
|
||||
// File Editor layout
|
||||
// File Editor layout with enhanced features
|
||||
<div className="h-full flex flex-col relative">
|
||||
<FileEditor
|
||||
<FileEditorEnhanced
|
||||
filePath={editingFile}
|
||||
onClose={() => setEditingFile(null)}
|
||||
className="flex-1"
|
||||
|
301
src/components/FileEditor.tsx
Normal file
301
src/components/FileEditor.tsx
Normal file
@@ -0,0 +1,301 @@
|
||||
import React, { useState, useEffect, useCallback } from "react";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import {
|
||||
X,
|
||||
Save,
|
||||
FileText,
|
||||
AlertCircle,
|
||||
Check,
|
||||
Loader2
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import Editor from "@monaco-editor/react";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
|
||||
interface FileEditorProps {
|
||||
filePath: string;
|
||||
onClose: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
// 根据文件扩展名获取语言
|
||||
const getLanguageFromPath = (path: string): string => {
|
||||
const ext = path.split(".").pop()?.toLowerCase();
|
||||
|
||||
const languageMap: Record<string, string> = {
|
||||
// JavaScript/TypeScript
|
||||
js: "javascript",
|
||||
jsx: "javascript",
|
||||
ts: "typescript",
|
||||
tsx: "typescript",
|
||||
|
||||
// Web
|
||||
html: "html",
|
||||
htm: "html",
|
||||
css: "css",
|
||||
scss: "scss",
|
||||
sass: "sass",
|
||||
less: "less",
|
||||
|
||||
// Programming Languages
|
||||
py: "python",
|
||||
java: "java",
|
||||
c: "c",
|
||||
cpp: "cpp",
|
||||
cc: "cpp",
|
||||
cxx: "cpp",
|
||||
cs: "csharp",
|
||||
php: "php",
|
||||
rb: "ruby",
|
||||
go: "go",
|
||||
rs: "rust",
|
||||
kt: "kotlin",
|
||||
swift: "swift",
|
||||
m: "objective-c",
|
||||
scala: "scala",
|
||||
sh: "shell",
|
||||
bash: "shell",
|
||||
zsh: "shell",
|
||||
fish: "shell",
|
||||
ps1: "powershell",
|
||||
r: "r",
|
||||
lua: "lua",
|
||||
perl: "perl",
|
||||
|
||||
// Data/Config
|
||||
json: "json",
|
||||
xml: "xml",
|
||||
yaml: "yaml",
|
||||
yml: "yaml",
|
||||
toml: "toml",
|
||||
ini: "ini",
|
||||
cfg: "ini",
|
||||
conf: "ini",
|
||||
|
||||
// Documentation
|
||||
md: "markdown",
|
||||
markdown: "markdown",
|
||||
rst: "restructuredtext",
|
||||
tex: "latex",
|
||||
|
||||
// Database
|
||||
sql: "sql",
|
||||
|
||||
// Others
|
||||
dockerfile: "dockerfile",
|
||||
makefile: "makefile",
|
||||
cmake: "cmake",
|
||||
gradle: "gradle",
|
||||
};
|
||||
|
||||
return languageMap[ext || ""] || "plaintext";
|
||||
};
|
||||
|
||||
export const FileEditor: React.FC<FileEditorProps> = ({
|
||||
filePath,
|
||||
onClose,
|
||||
className,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [content, setContent] = useState<string>("");
|
||||
const [originalContent, setOriginalContent] = useState<string>("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const [hasChanges, setHasChanges] = useState(false);
|
||||
|
||||
const fileName = filePath.split("/").pop() || filePath;
|
||||
const language = getLanguageFromPath(filePath);
|
||||
|
||||
// 加载文件内容
|
||||
const loadFile = useCallback(async () => {
|
||||
if (!filePath) return;
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const fileContent = await invoke<string>("read_file", {
|
||||
path: filePath,
|
||||
});
|
||||
|
||||
setContent(fileContent);
|
||||
setOriginalContent(fileContent);
|
||||
setHasChanges(false);
|
||||
} catch (err) {
|
||||
console.error("Failed to load file:", err);
|
||||
setError(err instanceof Error ? err.message : "Failed to load file");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [filePath]);
|
||||
|
||||
// 保存文件
|
||||
const saveFile = useCallback(async () => {
|
||||
if (!filePath || !hasChanges) return;
|
||||
|
||||
try {
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
|
||||
await invoke("write_file", {
|
||||
path: filePath,
|
||||
content: content,
|
||||
});
|
||||
|
||||
setOriginalContent(content);
|
||||
setHasChanges(false);
|
||||
setSaved(true);
|
||||
|
||||
// 显示保存成功提示
|
||||
setTimeout(() => setSaved(false), 2000);
|
||||
} catch (err) {
|
||||
console.error("Failed to save file:", err);
|
||||
setError(err instanceof Error ? err.message : "Failed to save file");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}, [filePath, content, hasChanges]);
|
||||
|
||||
// 处理内容变化
|
||||
const handleContentChange = (value: string | undefined) => {
|
||||
if (value !== undefined) {
|
||||
setContent(value);
|
||||
setHasChanges(value !== originalContent);
|
||||
}
|
||||
};
|
||||
|
||||
// 处理关闭
|
||||
const handleClose = () => {
|
||||
if (hasChanges) {
|
||||
if (confirm(t("app.unsavedChangesConfirm"))) {
|
||||
onClose();
|
||||
}
|
||||
} else {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
// 快捷键处理
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
// Ctrl/Cmd + S 保存
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === "s" && hasChanges) {
|
||||
e.preventDefault();
|
||||
saveFile();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [hasChanges, saveFile]);
|
||||
|
||||
// 加载文件
|
||||
useEffect(() => {
|
||||
if (filePath) {
|
||||
loadFile();
|
||||
}
|
||||
}, [filePath, loadFile]);
|
||||
|
||||
return (
|
||||
<div className={cn("flex flex-col h-full bg-background", className)}>
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-4 py-2 border-b shrink-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<FileText className="h-4 w-4 text-muted-foreground" />
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium text-sm">{fileName}</span>
|
||||
{hasChanges && (
|
||||
<span className="text-xs px-1.5 py-0.5 bg-yellow-500/10 text-yellow-600 rounded">
|
||||
{t("app.modified")}
|
||||
</span>
|
||||
)}
|
||||
<AnimatePresence>
|
||||
{saved && (
|
||||
<motion.span
|
||||
initial={{ opacity: 0, x: -10 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0 }}
|
||||
className="text-xs px-1.5 py-0.5 bg-green-500/10 text-green-600 rounded flex items-center gap-1"
|
||||
>
|
||||
<Check className="h-3 w-3" />
|
||||
{t("app.saved")}
|
||||
</motion.span>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{hasChanges && (
|
||||
<Button
|
||||
variant="default"
|
||||
size="sm"
|
||||
onClick={saveFile}
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<>
|
||||
<Save className="h-4 w-4 mr-1" />
|
||||
{t("app.save")}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={handleClose}
|
||||
className="h-7 w-7"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Editor */}
|
||||
{error ? (
|
||||
<div className="flex flex-col items-center justify-center flex-1 p-8">
|
||||
<AlertCircle className="h-12 w-12 text-destructive mb-4" />
|
||||
<p className="text-lg font-medium mb-2">{t("app.error")}</p>
|
||||
<p className="text-sm text-muted-foreground text-center">{error}</p>
|
||||
</div>
|
||||
) : loading ? (
|
||||
<div className="flex items-center justify-center flex-1">
|
||||
<Loader2 className="h-8 w-8 animate-spin" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex-1 min-h-0">
|
||||
<Editor
|
||||
height="100%"
|
||||
language={language}
|
||||
value={content}
|
||||
onChange={handleContentChange}
|
||||
theme="vs-dark"
|
||||
options={{
|
||||
fontSize: 14,
|
||||
minimap: { enabled: true },
|
||||
lineNumbers: "on",
|
||||
rulers: [80, 120],
|
||||
wordWrap: "on",
|
||||
scrollBeyondLastLine: false,
|
||||
automaticLayout: true,
|
||||
tabSize: 2,
|
||||
insertSpaces: true,
|
||||
formatOnPaste: true,
|
||||
formatOnType: true,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default FileEditor;
|
674
src/components/FileEditorEnhanced.tsx
Normal file
674
src/components/FileEditorEnhanced.tsx
Normal file
@@ -0,0 +1,674 @@
|
||||
import React, { useState, useEffect, useCallback, useRef } from "react";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import {
|
||||
X,
|
||||
Save,
|
||||
AlertCircle,
|
||||
Check,
|
||||
Loader2,
|
||||
Maximize2,
|
||||
Minimize2,
|
||||
Settings2,
|
||||
FileCode2,
|
||||
Sparkles,
|
||||
Bug,
|
||||
Zap,
|
||||
AlertTriangle,
|
||||
Info
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import Editor, { Monaco } from "@monaco-editor/react";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import * as monaco from "monaco-editor";
|
||||
import {
|
||||
initializeMonaco,
|
||||
formatDocument
|
||||
} from "@/lib/monaco-config";
|
||||
import { setupRealtimeLinting } from "@/lib/eslint-integration";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
|
||||
interface FileEditorEnhancedProps {
|
||||
filePath: string;
|
||||
onClose: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
// 根据文件扩展名获取语言
|
||||
const getLanguageFromPath = (path: string): string => {
|
||||
const ext = path.split(".").pop()?.toLowerCase();
|
||||
|
||||
const languageMap: Record<string, string> = {
|
||||
// JavaScript/TypeScript
|
||||
js: "javascript",
|
||||
jsx: "javascript",
|
||||
mjs: "javascript",
|
||||
ts: "typescript",
|
||||
tsx: "typescript",
|
||||
|
||||
// Web
|
||||
html: "html",
|
||||
htm: "html",
|
||||
css: "css",
|
||||
scss: "scss",
|
||||
sass: "sass",
|
||||
less: "less",
|
||||
|
||||
// Programming Languages
|
||||
py: "python",
|
||||
java: "java",
|
||||
c: "c",
|
||||
cpp: "cpp",
|
||||
cc: "cpp",
|
||||
cxx: "cpp",
|
||||
cs: "csharp",
|
||||
php: "php",
|
||||
rb: "ruby",
|
||||
go: "go",
|
||||
rs: "rust",
|
||||
kt: "kotlin",
|
||||
swift: "swift",
|
||||
m: "objective-c",
|
||||
scala: "scala",
|
||||
sh: "shell",
|
||||
bash: "shell",
|
||||
zsh: "shell",
|
||||
fish: "shell",
|
||||
ps1: "powershell",
|
||||
r: "r",
|
||||
lua: "lua",
|
||||
perl: "perl",
|
||||
|
||||
// Data/Config
|
||||
json: "json",
|
||||
jsonc: "json",
|
||||
xml: "xml",
|
||||
yaml: "yaml",
|
||||
yml: "yaml",
|
||||
toml: "toml",
|
||||
ini: "ini",
|
||||
cfg: "ini",
|
||||
conf: "ini",
|
||||
|
||||
// Documentation
|
||||
md: "markdown",
|
||||
markdown: "markdown",
|
||||
rst: "restructuredtext",
|
||||
tex: "latex",
|
||||
|
||||
// Database
|
||||
sql: "sql",
|
||||
mysql: "mysql",
|
||||
pgsql: "pgsql",
|
||||
|
||||
// Others
|
||||
dockerfile: "dockerfile",
|
||||
makefile: "makefile",
|
||||
cmake: "cmake",
|
||||
gradle: "gradle",
|
||||
graphql: "graphql",
|
||||
proto: "protobuf",
|
||||
};
|
||||
|
||||
return languageMap[ext || ""] || "plaintext";
|
||||
};
|
||||
|
||||
// 诊断信息接口
|
||||
interface DiagnosticInfo {
|
||||
line: number;
|
||||
column: number;
|
||||
message: string;
|
||||
severity: 'error' | 'warning' | 'info';
|
||||
source?: string;
|
||||
}
|
||||
|
||||
export const FileEditorEnhanced: React.FC<FileEditorEnhancedProps> = ({
|
||||
filePath,
|
||||
onClose,
|
||||
className,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [content, setContent] = useState<string>("");
|
||||
const [originalContent, setOriginalContent] = useState<string>("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const [hasChanges, setHasChanges] = useState(false);
|
||||
const [isFullscreen, setIsFullscreen] = useState(false);
|
||||
const [diagnostics, setDiagnostics] = useState<DiagnosticInfo[]>([]);
|
||||
const [showDiagnostics, setShowDiagnostics] = useState(true);
|
||||
const [theme, setTheme] = useState<'vs-dark-plus' | 'vs-dark' | 'vs' | 'hc-black'>('vs-dark-plus');
|
||||
const [fontSize, setFontSize] = useState(14);
|
||||
const [minimap, setMinimap] = useState(true);
|
||||
const [wordWrap, setWordWrap] = useState<'on' | 'off'>('on');
|
||||
const [autoSave, setAutoSave] = useState(false);
|
||||
|
||||
const editorRef = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);
|
||||
const monacoRef = useRef<Monaco | null>(null);
|
||||
const autoSaveTimerRef = useRef<NodeJS.Timeout | null>(null);
|
||||
|
||||
const fileName = filePath.split("/").pop() || filePath;
|
||||
const language = getLanguageFromPath(filePath);
|
||||
|
||||
// 加载文件内容
|
||||
const loadFile = useCallback(async () => {
|
||||
if (!filePath) return;
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const fileContent = await invoke<string>("read_file", {
|
||||
path: filePath,
|
||||
});
|
||||
|
||||
setContent(fileContent);
|
||||
setOriginalContent(fileContent);
|
||||
setHasChanges(false);
|
||||
} catch (err) {
|
||||
console.error("Failed to load file:", err);
|
||||
setError(err instanceof Error ? err.message : "Failed to load file");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [filePath]);
|
||||
|
||||
// 保存文件
|
||||
const saveFile = useCallback(async () => {
|
||||
if (!filePath || !hasChanges) return;
|
||||
|
||||
try {
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
|
||||
await invoke("write_file", {
|
||||
path: filePath,
|
||||
content: content,
|
||||
});
|
||||
|
||||
setOriginalContent(content);
|
||||
setHasChanges(false);
|
||||
setSaved(true);
|
||||
|
||||
// 显示保存成功提示
|
||||
setTimeout(() => setSaved(false), 2000);
|
||||
} catch (err) {
|
||||
console.error("Failed to save file:", err);
|
||||
setError(err instanceof Error ? err.message : "Failed to save file");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}, [filePath, content, hasChanges]);
|
||||
|
||||
// 自动保存
|
||||
useEffect(() => {
|
||||
if (autoSave && hasChanges) {
|
||||
if (autoSaveTimerRef.current) {
|
||||
clearTimeout(autoSaveTimerRef.current);
|
||||
}
|
||||
|
||||
autoSaveTimerRef.current = setTimeout(() => {
|
||||
saveFile();
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (autoSaveTimerRef.current) {
|
||||
clearTimeout(autoSaveTimerRef.current);
|
||||
}
|
||||
};
|
||||
}, [autoSave, hasChanges, saveFile]);
|
||||
|
||||
// 处理内容变化
|
||||
const handleContentChange = (value: string | undefined) => {
|
||||
if (value !== undefined) {
|
||||
setContent(value);
|
||||
setHasChanges(value !== originalContent);
|
||||
|
||||
// 触发语法检查
|
||||
if (editorRef.current && (language === 'typescript' || language === 'javascript')) {
|
||||
validateCode(value);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// 验证代码
|
||||
const validateCode = async (_code: string) => {
|
||||
if (!monacoRef.current || !editorRef.current) return;
|
||||
|
||||
const model = editorRef.current.getModel();
|
||||
if (!model) return;
|
||||
|
||||
// 获取 Monaco 的内置诊断
|
||||
const markers = monacoRef.current.editor.getModelMarkers({ resource: model.uri });
|
||||
|
||||
const newDiagnostics: DiagnosticInfo[] = markers.map(marker => ({
|
||||
line: marker.startLineNumber,
|
||||
column: marker.startColumn,
|
||||
message: marker.message,
|
||||
severity: marker.severity === 8 ? 'error' :
|
||||
marker.severity === 4 ? 'warning' : 'info',
|
||||
source: marker.source || 'typescript'
|
||||
}));
|
||||
|
||||
setDiagnostics(newDiagnostics);
|
||||
};
|
||||
|
||||
// 格式化代码
|
||||
const handleFormat = () => {
|
||||
if (editorRef.current) {
|
||||
formatDocument(editorRef.current);
|
||||
}
|
||||
};
|
||||
|
||||
// 处理关闭
|
||||
const handleClose = () => {
|
||||
if (hasChanges) {
|
||||
if (confirm(t("app.unsavedChangesConfirm"))) {
|
||||
onClose();
|
||||
}
|
||||
} else {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
// 切换全屏
|
||||
const toggleFullscreen = () => {
|
||||
setIsFullscreen(!isFullscreen);
|
||||
};
|
||||
|
||||
// Monaco Editor 挂载时的处理
|
||||
const handleEditorDidMount = (editor: monaco.editor.IStandaloneCodeEditor, monaco: Monaco) => {
|
||||
editorRef.current = editor;
|
||||
monacoRef.current = monaco;
|
||||
|
||||
// 初始化 Monaco 配置
|
||||
initializeMonaco();
|
||||
|
||||
// 设置实时语法检查
|
||||
setupRealtimeLinting(editor, {
|
||||
enabled: true,
|
||||
delay: 500,
|
||||
showInlineErrors: true,
|
||||
showErrorsInScrollbar: true,
|
||||
showErrorsInMinimap: true,
|
||||
});
|
||||
|
||||
// 设置快捷键
|
||||
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {
|
||||
saveFile();
|
||||
});
|
||||
|
||||
editor.addCommand(monaco.KeyMod.Alt | monaco.KeyMod.Shift | monaco.KeyCode.KeyF, () => {
|
||||
handleFormat();
|
||||
});
|
||||
|
||||
// 监听光标位置变化
|
||||
editor.onDidChangeCursorPosition(() => {
|
||||
// 可以在这里更新状态栏信息
|
||||
});
|
||||
|
||||
// 初始验证
|
||||
if (language === 'typescript' || language === 'javascript') {
|
||||
setTimeout(() => validateCode(content), 1000);
|
||||
}
|
||||
};
|
||||
|
||||
// 快捷键处理
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
// Ctrl/Cmd + S 保存
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === "s") {
|
||||
e.preventDefault();
|
||||
saveFile();
|
||||
}
|
||||
|
||||
// Ctrl/Cmd + Shift + F 格式化
|
||||
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === "f") {
|
||||
e.preventDefault();
|
||||
handleFormat();
|
||||
}
|
||||
|
||||
// F11 全屏
|
||||
if (e.key === "F11") {
|
||||
e.preventDefault();
|
||||
toggleFullscreen();
|
||||
}
|
||||
|
||||
// Esc 退出全屏
|
||||
if (e.key === "Escape" && isFullscreen) {
|
||||
setIsFullscreen(false);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [hasChanges, saveFile, isFullscreen]);
|
||||
|
||||
// 加载文件
|
||||
useEffect(() => {
|
||||
if (filePath) {
|
||||
loadFile();
|
||||
}
|
||||
}, [filePath, loadFile]);
|
||||
|
||||
// 计算诊断统计
|
||||
const diagnosticStats = {
|
||||
errors: diagnostics.filter(d => d.severity === 'error').length,
|
||||
warnings: diagnostics.filter(d => d.severity === 'warning').length,
|
||||
infos: diagnostics.filter(d => d.severity === 'info').length,
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cn(
|
||||
"flex flex-col h-full bg-background",
|
||||
isFullscreen && "fixed inset-0 z-50",
|
||||
className
|
||||
)}>
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between px-4 py-2 border-b shrink-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<FileCode2 className="h-4 w-4 text-muted-foreground" />
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="font-medium text-sm">{fileName}</span>
|
||||
<span className="text-xs text-muted-foreground">({language})</span>
|
||||
{hasChanges && (
|
||||
<span className="text-xs px-1.5 py-0.5 bg-yellow-500/10 text-yellow-600 rounded">
|
||||
{t("app.modified")}
|
||||
</span>
|
||||
)}
|
||||
<AnimatePresence>
|
||||
{saved && (
|
||||
<motion.span
|
||||
initial={{ opacity: 0, x: -10 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0 }}
|
||||
className="text-xs px-1.5 py-0.5 bg-green-500/10 text-green-600 rounded flex items-center gap-1"
|
||||
>
|
||||
<Check className="h-3 w-3" />
|
||||
{t("app.saved")}
|
||||
</motion.span>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{/* 诊断信息 */}
|
||||
{showDiagnostics && diagnostics.length > 0 && (
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
{diagnosticStats.errors > 0 && (
|
||||
<span className="flex items-center gap-1 text-red-500">
|
||||
<Bug className="h-3 w-3" />
|
||||
{diagnosticStats.errors}
|
||||
</span>
|
||||
)}
|
||||
{diagnosticStats.warnings > 0 && (
|
||||
<span className="flex items-center gap-1 text-yellow-500">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
{diagnosticStats.warnings}
|
||||
</span>
|
||||
)}
|
||||
{diagnosticStats.infos > 0 && (
|
||||
<span className="flex items-center gap-1 text-blue-500">
|
||||
<Info className="h-3 w-3" />
|
||||
{diagnosticStats.infos}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 自动保存指示器 */}
|
||||
{autoSave && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="flex items-center gap-1 text-xs text-green-500">
|
||||
<Zap className="h-3 w-3" />
|
||||
Auto
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>自动保存已启用</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
|
||||
{/* 格式化按钮 */}
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleFormat}
|
||||
>
|
||||
<Sparkles className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>格式化代码 (Alt+Shift+F)</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
|
||||
{/* 设置菜单 */}
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm">
|
||||
<Settings2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setTheme('vs-dark-plus')}>
|
||||
主题: VS Dark+
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setTheme('vs-dark')}>
|
||||
主题: VS Dark
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setTheme('vs')}>
|
||||
主题: VS Light
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => setFontSize(fontSize + 1)}>
|
||||
字体放大
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setFontSize(fontSize - 1)}>
|
||||
字体缩小
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => setMinimap(!minimap)}>
|
||||
{minimap ? '隐藏' : '显示'}小地图
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setWordWrap(wordWrap === 'on' ? 'off' : 'on')}>
|
||||
{wordWrap === 'on' ? '关闭' : '开启'}自动换行
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setShowDiagnostics(!showDiagnostics)}>
|
||||
{showDiagnostics ? '隐藏' : '显示'}诊断信息
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={() => setAutoSave(!autoSave)}>
|
||||
{autoSave ? '关闭' : '开启'}自动保存
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
{/* 保存按钮 */}
|
||||
{hasChanges && (
|
||||
<Button
|
||||
variant="default"
|
||||
size="sm"
|
||||
onClick={saveFile}
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<>
|
||||
<Save className="h-4 w-4 mr-1" />
|
||||
{t("app.save")}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* 全屏按钮 */}
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={toggleFullscreen}
|
||||
className="h-7 w-7"
|
||||
>
|
||||
{isFullscreen ? (
|
||||
<Minimize2 className="h-4 w-4" />
|
||||
) : (
|
||||
<Maximize2 className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{isFullscreen ? '退出全屏 (Esc)' : '全屏 (F11)'}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
|
||||
{/* 关闭按钮 */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={handleClose}
|
||||
className="h-7 w-7"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 诊断面板 */}
|
||||
{showDiagnostics && diagnostics.length > 0 && (
|
||||
<div className="max-h-32 overflow-y-auto border-b bg-muted/50 p-2">
|
||||
<div className="space-y-1">
|
||||
{diagnostics.map((diagnostic, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className={cn(
|
||||
"flex items-start gap-2 text-xs p-1 rounded cursor-pointer hover:bg-background",
|
||||
diagnostic.severity === 'error' && "text-red-500",
|
||||
diagnostic.severity === 'warning' && "text-yellow-500",
|
||||
diagnostic.severity === 'info' && "text-blue-500"
|
||||
)}
|
||||
onClick={() => {
|
||||
// 跳转到错误位置
|
||||
if (editorRef.current) {
|
||||
editorRef.current.setPosition({
|
||||
lineNumber: diagnostic.line,
|
||||
column: diagnostic.column
|
||||
});
|
||||
editorRef.current.focus();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{diagnostic.severity === 'error' && <Bug className="h-3 w-3 mt-0.5" />}
|
||||
{diagnostic.severity === 'warning' && <AlertTriangle className="h-3 w-3 mt-0.5" />}
|
||||
{diagnostic.severity === 'info' && <Info className="h-3 w-3 mt-0.5" />}
|
||||
<span className="flex-1">
|
||||
[{diagnostic.line}:{diagnostic.column}] {diagnostic.message}
|
||||
</span>
|
||||
{diagnostic.source && (
|
||||
<span className="text-muted-foreground">({diagnostic.source})</span>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Editor */}
|
||||
{error ? (
|
||||
<div className="flex flex-col items-center justify-center flex-1 p-8">
|
||||
<AlertCircle className="h-12 w-12 text-destructive mb-4" />
|
||||
<p className="text-lg font-medium mb-2">{t("app.error")}</p>
|
||||
<p className="text-sm text-muted-foreground text-center">{error}</p>
|
||||
</div>
|
||||
) : loading ? (
|
||||
<div className="flex items-center justify-center flex-1">
|
||||
<Loader2 className="h-8 w-8 animate-spin" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex-1 min-h-0">
|
||||
<Editor
|
||||
height="100%"
|
||||
language={language}
|
||||
value={content}
|
||||
onChange={handleContentChange}
|
||||
onMount={handleEditorDidMount}
|
||||
theme={theme}
|
||||
options={{
|
||||
fontSize: fontSize,
|
||||
minimap: { enabled: minimap },
|
||||
lineNumbers: "on",
|
||||
rulers: [80, 120],
|
||||
wordWrap: wordWrap,
|
||||
scrollBeyondLastLine: false,
|
||||
automaticLayout: true,
|
||||
tabSize: 2,
|
||||
insertSpaces: true,
|
||||
formatOnPaste: true,
|
||||
formatOnType: true,
|
||||
suggestOnTriggerCharacters: true,
|
||||
quickSuggestions: true,
|
||||
parameterHints: { enabled: true },
|
||||
folding: true,
|
||||
foldingStrategy: 'indentation',
|
||||
showFoldingControls: 'always',
|
||||
bracketPairColorization: { enabled: true },
|
||||
guides: {
|
||||
indentation: true,
|
||||
bracketPairs: true,
|
||||
},
|
||||
stickyScroll: { enabled: true },
|
||||
inlineSuggest: { enabled: true },
|
||||
lightbulb: { enabled: "onCodeActionsChange" as any },
|
||||
hover: { enabled: true, delay: 300 },
|
||||
definitionLinkOpensInPeek: true,
|
||||
peekWidgetDefaultFocus: 'editor',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 状态栏 */}
|
||||
<div className="flex items-center justify-between px-4 py-1 border-t text-xs text-muted-foreground bg-muted/30">
|
||||
<div className="flex items-center gap-4">
|
||||
<span>{language.toUpperCase()}</span>
|
||||
<span>UTF-8</span>
|
||||
<span>LF</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<span>Ln 1, Col 1</span>
|
||||
<span>Spaces: 2</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default FileEditorEnhanced;
|
584
src/components/FileExplorerPanel.tsx
Normal file
584
src/components/FileExplorerPanel.tsx
Normal file
@@ -0,0 +1,584 @@
|
||||
import React, { useState, useEffect, useCallback, useMemo } from "react";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
|
||||
import {
|
||||
Folder,
|
||||
FolderOpen,
|
||||
File,
|
||||
FileText,
|
||||
FileCode,
|
||||
FileJson,
|
||||
FileImage,
|
||||
Search,
|
||||
ChevronRight,
|
||||
ChevronDown,
|
||||
X,
|
||||
RefreshCw,
|
||||
Loader2,
|
||||
AlertCircle,
|
||||
} from "lucide-react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
ContextMenu,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuTrigger,
|
||||
} from "@/components/ui/context-menu";
|
||||
|
||||
interface FileNode {
|
||||
name: string;
|
||||
path: string;
|
||||
file_type: "file" | "directory";
|
||||
children?: FileNode[];
|
||||
size?: number;
|
||||
modified?: number;
|
||||
expanded?: boolean;
|
||||
}
|
||||
|
||||
interface FileExplorerPanelProps {
|
||||
projectPath: string;
|
||||
isVisible: boolean;
|
||||
onFileSelect?: (path: string) => void;
|
||||
onFileOpen?: (path: string) => void;
|
||||
onToggle: () => void;
|
||||
width?: number;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
// 获取文件图标
|
||||
const getFileIcon = (filename: string) => {
|
||||
const ext = filename.split(".").pop()?.toLowerCase();
|
||||
|
||||
const iconMap: Record<string, React.ReactNode> = {
|
||||
// 代码文件
|
||||
ts: <FileCode className="h-4 w-4 text-blue-500" />,
|
||||
tsx: <FileCode className="h-4 w-4 text-blue-500" />,
|
||||
js: <FileCode className="h-4 w-4 text-yellow-500" />,
|
||||
jsx: <FileCode className="h-4 w-4 text-yellow-500" />,
|
||||
py: <FileCode className="h-4 w-4 text-green-500" />,
|
||||
rs: <FileCode className="h-4 w-4 text-orange-500" />,
|
||||
go: <FileCode className="h-4 w-4 text-cyan-500" />,
|
||||
java: <FileCode className="h-4 w-4 text-red-500" />,
|
||||
cpp: <FileCode className="h-4 w-4 text-purple-500" />,
|
||||
c: <FileCode className="h-4 w-4 text-purple-500" />,
|
||||
|
||||
// 配置文件
|
||||
json: <FileJson className="h-4 w-4 text-yellow-600" />,
|
||||
yaml: <FileText className="h-4 w-4 text-pink-500" />,
|
||||
yml: <FileText className="h-4 w-4 text-pink-500" />,
|
||||
toml: <FileText className="h-4 w-4 text-gray-500" />,
|
||||
xml: <FileText className="h-4 w-4 text-orange-500" />,
|
||||
|
||||
// 文档文件
|
||||
md: <FileText className="h-4 w-4 text-gray-600" />,
|
||||
txt: <FileText className="h-4 w-4 text-gray-500" />,
|
||||
pdf: <FileText className="h-4 w-4 text-red-600" />,
|
||||
|
||||
// 图片文件
|
||||
png: <FileImage className="h-4 w-4 text-green-600" />,
|
||||
jpg: <FileImage className="h-4 w-4 text-green-600" />,
|
||||
jpeg: <FileImage className="h-4 w-4 text-green-600" />,
|
||||
gif: <FileImage className="h-4 w-4 text-green-600" />,
|
||||
svg: <FileImage className="h-4 w-4 text-purple-600" />,
|
||||
ico: <FileImage className="h-4 w-4 text-blue-600" />,
|
||||
};
|
||||
|
||||
return iconMap[ext || ""] || <File className="h-4 w-4 text-muted-foreground" />;
|
||||
};
|
||||
|
||||
export const FileExplorerPanel: React.FC<FileExplorerPanelProps> = ({
|
||||
projectPath,
|
||||
isVisible,
|
||||
onFileSelect,
|
||||
onFileOpen,
|
||||
onToggle,
|
||||
width = 280,
|
||||
className,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [fileTree, setFileTree] = useState<FileNode | null>(null);
|
||||
const [expandedNodes, setExpandedNodes] = useState<Set<string>>(new Set());
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [searchResults, setSearchResults] = useState<string[]>([]);
|
||||
const [isSearching, setIsSearching] = useState(false);
|
||||
|
||||
// 文件点击处理状态
|
||||
const [lastClickTime, setLastClickTime] = useState<number>(0);
|
||||
const [lastClickPath, setLastClickPath] = useState<string | null>(null);
|
||||
|
||||
// 键盘导航状态
|
||||
const [selectedPath, setSelectedPath] = useState<string | null>(null);
|
||||
const [flattenedNodes, setFlattenedNodes] = useState<FileNode[]>([]);
|
||||
|
||||
const unlistenRef = React.useRef<UnlistenFn | null>(null);
|
||||
|
||||
// 切换节点展开状态
|
||||
const toggleExpand = useCallback((path: string) => {
|
||||
setExpandedNodes((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(path)) {
|
||||
next.delete(path);
|
||||
} else {
|
||||
next.add(path);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// 打开文件
|
||||
const handleOpenFile = useCallback((node: FileNode) => {
|
||||
if (node.file_type === "file") {
|
||||
if (onFileOpen) {
|
||||
onFileOpen(node.path);
|
||||
}
|
||||
}
|
||||
}, [onFileOpen]);
|
||||
|
||||
// 扁平化文件树以支持键盘导航
|
||||
const flattenTree = useCallback((node: FileNode, result: FileNode[] = []): FileNode[] => {
|
||||
result.push(node);
|
||||
if (node.file_type === "directory" && expandedNodes.has(node.path) && node.children) {
|
||||
node.children.forEach(child => flattenTree(child, result));
|
||||
}
|
||||
return result;
|
||||
}, [expandedNodes]);
|
||||
|
||||
// 更新扁平化节点列表
|
||||
useEffect(() => {
|
||||
if (fileTree) {
|
||||
const flattened = flattenTree(fileTree);
|
||||
setFlattenedNodes(flattened);
|
||||
// 如果没有选中的节点,选中第一个
|
||||
if (!selectedPath && flattened.length > 0) {
|
||||
setSelectedPath(flattened[0].path);
|
||||
}
|
||||
}
|
||||
}, [fileTree, expandedNodes, flattenTree, selectedPath]);
|
||||
|
||||
// 键盘导航处理
|
||||
useEffect(() => {
|
||||
if (!isVisible) return;
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (!selectedPath || flattenedNodes.length === 0) return;
|
||||
|
||||
const currentIndex = flattenedNodes.findIndex(node => node.path === selectedPath);
|
||||
if (currentIndex === -1) return;
|
||||
|
||||
const currentNode = flattenedNodes[currentIndex];
|
||||
|
||||
switch (e.key) {
|
||||
case "ArrowUp":
|
||||
e.preventDefault();
|
||||
if (currentIndex > 0) {
|
||||
setSelectedPath(flattenedNodes[currentIndex - 1].path);
|
||||
}
|
||||
break;
|
||||
|
||||
case "ArrowDown":
|
||||
e.preventDefault();
|
||||
if (currentIndex < flattenedNodes.length - 1) {
|
||||
setSelectedPath(flattenedNodes[currentIndex + 1].path);
|
||||
}
|
||||
break;
|
||||
|
||||
case "ArrowLeft":
|
||||
e.preventDefault();
|
||||
if (currentNode.file_type === "directory" && expandedNodes.has(currentNode.path)) {
|
||||
// 收起文件夹
|
||||
toggleExpand(currentNode.path);
|
||||
} else {
|
||||
// 移动到父文件夹
|
||||
const parentPath = currentNode.path.substring(0, currentNode.path.lastIndexOf("/"));
|
||||
const parentNode = flattenedNodes.find(node => node.path === parentPath);
|
||||
if (parentNode) {
|
||||
setSelectedPath(parentNode.path);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case "ArrowRight":
|
||||
e.preventDefault();
|
||||
if (currentNode.file_type === "directory") {
|
||||
if (!expandedNodes.has(currentNode.path)) {
|
||||
// 展开文件夹
|
||||
toggleExpand(currentNode.path);
|
||||
} else if (currentNode.children && currentNode.children.length > 0) {
|
||||
// 移动到第一个子节点
|
||||
setSelectedPath(currentNode.children[0].path);
|
||||
}
|
||||
} else {
|
||||
// 打开文件
|
||||
handleOpenFile(currentNode);
|
||||
}
|
||||
break;
|
||||
|
||||
case "Enter":
|
||||
e.preventDefault();
|
||||
if (currentNode.file_type === "directory") {
|
||||
toggleExpand(currentNode.path);
|
||||
} else {
|
||||
handleOpenFile(currentNode);
|
||||
}
|
||||
break;
|
||||
|
||||
case " ": // Space key
|
||||
e.preventDefault();
|
||||
if (currentNode.file_type === "file") {
|
||||
// 添加到聊天
|
||||
onFileSelect?.(currentNode.path);
|
||||
}
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [isVisible, selectedPath, flattenedNodes, expandedNodes, toggleExpand, onFileSelect, handleOpenFile]);
|
||||
|
||||
// 加载文件树
|
||||
const loadFileTree = useCallback(async () => {
|
||||
if (!projectPath) return;
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const tree = await invoke<FileNode>("read_directory_tree", {
|
||||
path: projectPath,
|
||||
maxDepth: 5,
|
||||
ignorePatterns: [
|
||||
"node_modules",
|
||||
".git",
|
||||
"target",
|
||||
"dist",
|
||||
"build",
|
||||
".idea",
|
||||
".vscode",
|
||||
"__pycache__",
|
||||
".DS_Store",
|
||||
],
|
||||
});
|
||||
|
||||
setFileTree(tree);
|
||||
|
||||
// 默认展开根目录
|
||||
if (tree) {
|
||||
setExpandedNodes(new Set([tree.path]));
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Failed to load file tree:", err);
|
||||
setError(err instanceof Error ? err.message : "Failed to load file tree");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [projectPath]);
|
||||
|
||||
// 搜索文件
|
||||
const searchFiles = useCallback(async (query: string) => {
|
||||
if (!projectPath || !query) {
|
||||
setSearchResults([]);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsSearching(true);
|
||||
const results = await invoke<string[]>("search_files_by_name", {
|
||||
basePath: projectPath,
|
||||
query,
|
||||
maxResults: 50,
|
||||
});
|
||||
setSearchResults(results);
|
||||
} catch (err) {
|
||||
console.error("Failed to search files:", err);
|
||||
} finally {
|
||||
setIsSearching(false);
|
||||
}
|
||||
}, [projectPath]);
|
||||
|
||||
// 防抖搜索
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
if (searchQuery) {
|
||||
searchFiles(searchQuery);
|
||||
} else {
|
||||
setSearchResults([]);
|
||||
}
|
||||
}, 300);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [searchQuery, searchFiles]);
|
||||
|
||||
// 监听文件系统变化
|
||||
useEffect(() => {
|
||||
if (!projectPath || !isVisible) return;
|
||||
|
||||
const setupListener = async () => {
|
||||
try {
|
||||
// 监听文件系统变化事件
|
||||
unlistenRef.current = await listen("file-system-change", (event) => {
|
||||
console.log("File system changed:", event.payload);
|
||||
loadFileTree();
|
||||
});
|
||||
|
||||
// 启动目录监听
|
||||
await invoke("watch_directory", { path: projectPath });
|
||||
} catch (err) {
|
||||
console.error("Failed to setup file watcher:", err);
|
||||
}
|
||||
};
|
||||
|
||||
setupListener();
|
||||
loadFileTree();
|
||||
|
||||
return () => {
|
||||
if (unlistenRef.current) {
|
||||
unlistenRef.current();
|
||||
unlistenRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [projectPath, isVisible, loadFileTree]);
|
||||
|
||||
// 处理文件选择
|
||||
const handleFileClick = useCallback((node: FileNode) => {
|
||||
// 设置选中状态
|
||||
setSelectedPath(node.path);
|
||||
|
||||
if (node.file_type === "directory") {
|
||||
toggleExpand(node.path);
|
||||
} else {
|
||||
const now = Date.now();
|
||||
const timeDiff = now - lastClickTime;
|
||||
|
||||
// 检测双击(300ms内的两次点击)
|
||||
if (lastClickPath === node.path && timeDiff < 300) {
|
||||
// 双击 - 添加到提及
|
||||
onFileSelect?.(node.path);
|
||||
// 重置状态
|
||||
setLastClickTime(0);
|
||||
setLastClickPath(null);
|
||||
} else {
|
||||
// 单击 - 打开文件
|
||||
handleOpenFile(node);
|
||||
setLastClickTime(now);
|
||||
setLastClickPath(node.path);
|
||||
}
|
||||
}
|
||||
}, [onFileSelect, toggleExpand, lastClickTime, lastClickPath, handleOpenFile]);
|
||||
|
||||
// 复制路径到剪贴板
|
||||
const copyPath = useCallback(async (path: string) => {
|
||||
await navigator.clipboard.writeText(path);
|
||||
}, []);
|
||||
|
||||
// 渲染文件树节点
|
||||
const renderNode = useCallback((node: FileNode, depth = 0): React.ReactNode => {
|
||||
const isExpanded = expandedNodes.has(node.path);
|
||||
const hasChildren = node.children && node.children.length > 0;
|
||||
const isSelected = selectedPath === node.path;
|
||||
|
||||
return (
|
||||
<div key={node.path}>
|
||||
<ContextMenu>
|
||||
<ContextMenuTrigger>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center gap-1 px-2 py-1 hover:bg-accent cursor-pointer rounded-sm",
|
||||
"group transition-colors",
|
||||
isSelected && "bg-accent ring-1 ring-primary/20"
|
||||
)}
|
||||
style={{ paddingLeft: `${depth * 12 + 8}px` }}
|
||||
onClick={() => handleFileClick(node)}
|
||||
>
|
||||
{node.file_type === "directory" ? (
|
||||
<>
|
||||
{hasChildren && (
|
||||
<div className="w-4 h-4 flex items-center justify-center">
|
||||
{isExpanded ? (
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
) : (
|
||||
<ChevronRight className="h-3 w-3" />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!hasChildren && <div className="w-4" />}
|
||||
<div className="flex-shrink-0">
|
||||
{isExpanded ? (
|
||||
<FolderOpen className="h-4 w-4 text-blue-500" />
|
||||
) : (
|
||||
<Folder className="h-4 w-4 text-blue-500" />
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="w-4" />
|
||||
<div className="flex-shrink-0">{getFileIcon(node.name)}</div>
|
||||
</>
|
||||
)}
|
||||
<span className="text-sm truncate flex-1">{node.name}</span>
|
||||
</div>
|
||||
</ContextMenuTrigger>
|
||||
|
||||
<ContextMenuContent>
|
||||
<ContextMenuItem onClick={() => copyPath(node.path)}>
|
||||
{t('app.copyPath')}
|
||||
</ContextMenuItem>
|
||||
{node.file_type === "file" && (
|
||||
<>
|
||||
<ContextMenuItem onClick={() => handleOpenFile(node)}>
|
||||
{t('app.openFile')}
|
||||
</ContextMenuItem>
|
||||
<ContextMenuItem onClick={() => onFileSelect?.(node.path)}>
|
||||
{t('app.addToChat')}
|
||||
</ContextMenuItem>
|
||||
</>
|
||||
)}
|
||||
</ContextMenuContent>
|
||||
</ContextMenu>
|
||||
|
||||
{isExpanded && node.children && (
|
||||
<div>
|
||||
{node.children.map((child) => renderNode(child, depth + 1))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}, [expandedNodes, handleFileClick, copyPath, onFileSelect, onFileOpen, selectedPath, handleOpenFile]);
|
||||
|
||||
// 渲染搜索结果
|
||||
const renderSearchResults = useMemo(() => {
|
||||
if (!searchQuery || searchResults.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="border-t">
|
||||
<div className="p-2 text-xs text-muted-foreground">
|
||||
{searchResults.length > 0
|
||||
? `Found ${searchResults.length} results`
|
||||
: t('app.noFilesFound')}
|
||||
</div>
|
||||
<div className="max-h-64 overflow-y-auto">
|
||||
{searchResults.map((path) => {
|
||||
const filename = path.split("/").pop() || path;
|
||||
const relativePath = path.replace(projectPath + "/", "");
|
||||
|
||||
return (
|
||||
<div
|
||||
key={path}
|
||||
className="px-3 py-1.5 hover:bg-accent cursor-pointer text-sm"
|
||||
onClick={() => onFileSelect?.(path)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
{getFileIcon(filename)}
|
||||
<span className="truncate">{relativePath}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}, [searchQuery, searchResults, projectPath, onFileSelect]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<AnimatePresence>
|
||||
{isVisible && (
|
||||
<motion.div
|
||||
initial={{ x: "-100%" }}
|
||||
animate={{ x: 0 }}
|
||||
exit={{ x: "-100%" }}
|
||||
transition={{ type: "spring", damping: 20, stiffness: 300 }}
|
||||
className={cn(
|
||||
"fixed left-0 top-[172px] bottom-0 bg-background border-r border-border shadow-xl z-20",
|
||||
className
|
||||
)}
|
||||
style={{ width: `${width}px` }}
|
||||
>
|
||||
<div className="h-full flex flex-col">
|
||||
{/* Header */}
|
||||
<div className="p-3 border-b border-border">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Folder className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">{t('app.fileExplorer')}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={loadFileTree}
|
||||
disabled={loading}
|
||||
className="h-6 w-6"
|
||||
>
|
||||
{loading ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onToggle}
|
||||
className="h-6 w-6"
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Search */}
|
||||
<div className="relative">
|
||||
<Search className="absolute left-2 top-1/2 transform -translate-y-1/2 h-3 w-3 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder={t('app.searchFiles')}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
className="h-7 pl-7 text-xs"
|
||||
/>
|
||||
{isSearching && (
|
||||
<Loader2 className="absolute right-2 top-1/2 transform -translate-y-1/2 h-3 w-3 animate-spin" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* File Tree or Search Results */}
|
||||
<ScrollArea className="flex-1">
|
||||
{error ? (
|
||||
<div className="flex flex-col items-center justify-center h-32 p-4">
|
||||
<AlertCircle className="h-8 w-8 text-destructive mb-2" />
|
||||
<p className="text-sm text-muted-foreground text-center">{error}</p>
|
||||
</div>
|
||||
) : loading ? (
|
||||
<div className="flex items-center justify-center h-32">
|
||||
<Loader2 className="h-6 w-6 animate-spin" />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{renderSearchResults}
|
||||
{!searchQuery && fileTree && (
|
||||
<div className="py-1">
|
||||
{renderNode(fileTree)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
// Add default export
|
||||
export default FileExplorerPanel;
|
364
src/components/FileViewer.tsx
Normal file
364
src/components/FileViewer.tsx
Normal file
@@ -0,0 +1,364 @@
|
||||
import React, { useState, useEffect, useCallback } from "react";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import {
|
||||
X,
|
||||
Save,
|
||||
FileText,
|
||||
AlertCircle,
|
||||
Check,
|
||||
Edit3,
|
||||
Eye,
|
||||
Loader2
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import Editor from "@monaco-editor/react";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
|
||||
interface FileViewerProps {
|
||||
filePath: string;
|
||||
isVisible: boolean;
|
||||
onClose: () => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
// 根据文件扩展名获取语言
|
||||
const getLanguageFromPath = (path: string): string => {
|
||||
const ext = path.split(".").pop()?.toLowerCase();
|
||||
|
||||
const languageMap: Record<string, string> = {
|
||||
// JavaScript/TypeScript
|
||||
js: "javascript",
|
||||
jsx: "javascript",
|
||||
ts: "typescript",
|
||||
tsx: "typescript",
|
||||
|
||||
// Web
|
||||
html: "html",
|
||||
htm: "html",
|
||||
css: "css",
|
||||
scss: "scss",
|
||||
sass: "sass",
|
||||
less: "less",
|
||||
|
||||
// Programming Languages
|
||||
py: "python",
|
||||
java: "java",
|
||||
c: "c",
|
||||
cpp: "cpp",
|
||||
cc: "cpp",
|
||||
cxx: "cpp",
|
||||
cs: "csharp",
|
||||
php: "php",
|
||||
rb: "ruby",
|
||||
go: "go",
|
||||
rs: "rust",
|
||||
kt: "kotlin",
|
||||
swift: "swift",
|
||||
m: "objective-c",
|
||||
scala: "scala",
|
||||
sh: "shell",
|
||||
bash: "shell",
|
||||
zsh: "shell",
|
||||
fish: "shell",
|
||||
ps1: "powershell",
|
||||
r: "r",
|
||||
lua: "lua",
|
||||
perl: "perl",
|
||||
|
||||
// Data/Config
|
||||
json: "json",
|
||||
xml: "xml",
|
||||
yaml: "yaml",
|
||||
yml: "yaml",
|
||||
toml: "toml",
|
||||
ini: "ini",
|
||||
cfg: "ini",
|
||||
conf: "ini",
|
||||
|
||||
// Documentation
|
||||
md: "markdown",
|
||||
markdown: "markdown",
|
||||
rst: "restructuredtext",
|
||||
tex: "latex",
|
||||
|
||||
// Database
|
||||
sql: "sql",
|
||||
|
||||
// Others
|
||||
dockerfile: "dockerfile",
|
||||
makefile: "makefile",
|
||||
cmake: "cmake",
|
||||
gradle: "gradle",
|
||||
};
|
||||
|
||||
return languageMap[ext || ""] || "plaintext";
|
||||
};
|
||||
|
||||
export const FileViewer: React.FC<FileViewerProps> = ({
|
||||
filePath,
|
||||
isVisible,
|
||||
onClose,
|
||||
className,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [content, setContent] = useState<string>("");
|
||||
const [originalContent, setOriginalContent] = useState<string>("");
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const [hasChanges, setHasChanges] = useState(false);
|
||||
|
||||
const fileName = filePath.split("/").pop() || filePath;
|
||||
const language = getLanguageFromPath(filePath);
|
||||
|
||||
// 加载文件内容
|
||||
const loadFile = useCallback(async () => {
|
||||
if (!filePath) return;
|
||||
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const fileContent = await invoke<string>("read_file", {
|
||||
path: filePath,
|
||||
});
|
||||
|
||||
setContent(fileContent);
|
||||
setOriginalContent(fileContent);
|
||||
setHasChanges(false);
|
||||
} catch (err) {
|
||||
console.error("Failed to load file:", err);
|
||||
setError(err instanceof Error ? err.message : "Failed to load file");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [filePath]);
|
||||
|
||||
// 保存文件
|
||||
const saveFile = useCallback(async () => {
|
||||
if (!filePath || !hasChanges) return;
|
||||
|
||||
try {
|
||||
setSaving(true);
|
||||
setError(null);
|
||||
|
||||
await invoke("write_file", {
|
||||
path: filePath,
|
||||
content: content,
|
||||
});
|
||||
|
||||
setOriginalContent(content);
|
||||
setHasChanges(false);
|
||||
setSaved(true);
|
||||
|
||||
// 显示保存成功提示
|
||||
setTimeout(() => setSaved(false), 2000);
|
||||
} catch (err) {
|
||||
console.error("Failed to save file:", err);
|
||||
setError(err instanceof Error ? err.message : "Failed to save file");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}, [filePath, content, hasChanges]);
|
||||
|
||||
// 处理内容变化
|
||||
const handleContentChange = (value: string | undefined) => {
|
||||
if (value !== undefined) {
|
||||
setContent(value);
|
||||
setHasChanges(value !== originalContent);
|
||||
}
|
||||
};
|
||||
|
||||
// 处理关闭
|
||||
const handleClose = () => {
|
||||
if (hasChanges) {
|
||||
if (confirm(t("app.unsavedChangesConfirm"))) {
|
||||
onClose();
|
||||
}
|
||||
} else {
|
||||
onClose();
|
||||
}
|
||||
};
|
||||
|
||||
// 切换编辑模式
|
||||
const toggleEditMode = () => {
|
||||
setIsEditing(!isEditing);
|
||||
};
|
||||
|
||||
// 快捷键处理
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
// Ctrl/Cmd + S 保存
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === "s" && isEditing && hasChanges) {
|
||||
e.preventDefault();
|
||||
saveFile();
|
||||
}
|
||||
// Esc 退出编辑模式
|
||||
if (e.key === "Escape" && isEditing) {
|
||||
setIsEditing(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isVisible) {
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}
|
||||
}, [isVisible, isEditing, hasChanges, saveFile]);
|
||||
|
||||
// 加载文件
|
||||
useEffect(() => {
|
||||
if (isVisible && filePath) {
|
||||
loadFile();
|
||||
}
|
||||
}, [isVisible, filePath, loadFile]);
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{isVisible && (
|
||||
<motion.div
|
||||
initial={{ opacity: 0, scale: 0.95 }}
|
||||
animate={{ opacity: 1, scale: 1 }}
|
||||
exit={{ opacity: 0, scale: 0.95 }}
|
||||
transition={{ duration: 0.2 }}
|
||||
className={cn(
|
||||
"fixed inset-0 z-50 flex items-center justify-center bg-black/50",
|
||||
className
|
||||
)}
|
||||
onClick={handleClose}
|
||||
>
|
||||
<motion.div
|
||||
className="relative w-[90%] h-[90%] max-w-6xl bg-background border rounded-lg shadow-2xl overflow-hidden"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between p-4 border-b">
|
||||
<div className="flex items-center gap-3">
|
||||
<FileText className="h-5 w-5 text-muted-foreground" />
|
||||
<div>
|
||||
<h3 className="font-semibold">{fileName}</h3>
|
||||
<p className="text-xs text-muted-foreground">{filePath}</p>
|
||||
</div>
|
||||
{hasChanges && (
|
||||
<span className="text-xs px-2 py-1 bg-yellow-500/10 text-yellow-600 rounded">
|
||||
{t("app.modified")}
|
||||
</span>
|
||||
)}
|
||||
{saved && (
|
||||
<motion.span
|
||||
initial={{ opacity: 0, x: -10 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: -10 }}
|
||||
className="text-xs px-2 py-1 bg-green-500/10 text-green-600 rounded flex items-center gap-1"
|
||||
>
|
||||
<Check className="h-3 w-3" />
|
||||
{t("app.saved")}
|
||||
</motion.span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={toggleEditMode}
|
||||
className={cn(isEditing && "text-primary")}
|
||||
>
|
||||
{isEditing ? (
|
||||
<Eye className="h-4 w-4" />
|
||||
) : (
|
||||
<Edit3 className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{isEditing ? t("app.viewMode") : t("app.editMode")}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
|
||||
{isEditing && hasChanges && (
|
||||
<Button
|
||||
variant="default"
|
||||
size="sm"
|
||||
onClick={saveFile}
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<>
|
||||
<Save className="h-4 w-4 mr-1" />
|
||||
{t("app.save")}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={handleClose}
|
||||
className="h-8 w-8"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
{error ? (
|
||||
<div className="flex flex-col items-center justify-center h-full p-8">
|
||||
<AlertCircle className="h-12 w-12 text-destructive mb-4" />
|
||||
<p className="text-lg font-medium mb-2">{t("app.error")}</p>
|
||||
<p className="text-sm text-muted-foreground text-center">{error}</p>
|
||||
</div>
|
||||
) : loading ? (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<Loader2 className="h-8 w-8 animate-spin" />
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-[calc(100%-73px)]">
|
||||
<Editor
|
||||
height="100%"
|
||||
language={language}
|
||||
value={content}
|
||||
onChange={handleContentChange}
|
||||
theme="vs-dark"
|
||||
options={{
|
||||
readOnly: !isEditing,
|
||||
fontSize: 14,
|
||||
minimap: { enabled: false },
|
||||
lineNumbers: "on",
|
||||
rulers: [80, 120],
|
||||
wordWrap: "on",
|
||||
scrollBeyondLastLine: false,
|
||||
automaticLayout: true,
|
||||
tabSize: 2,
|
||||
insertSpaces: true,
|
||||
formatOnPaste: true,
|
||||
formatOnType: true,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</motion.div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
);
|
||||
};
|
||||
|
||||
export default FileViewer;
|
582
src/components/GitPanel.tsx
Normal file
582
src/components/GitPanel.tsx
Normal file
@@ -0,0 +1,582 @@
|
||||
import React, { useState, useEffect, useCallback } from "react";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import {
|
||||
GitBranch,
|
||||
GitCommit,
|
||||
GitMerge,
|
||||
GitPullRequest,
|
||||
FileText,
|
||||
FilePlus,
|
||||
FileMinus,
|
||||
FileEdit,
|
||||
X,
|
||||
RefreshCw,
|
||||
Loader2,
|
||||
AlertCircle,
|
||||
CheckCircle,
|
||||
Circle,
|
||||
} from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
|
||||
interface GitStatus {
|
||||
branch: string;
|
||||
ahead: number;
|
||||
behind: number;
|
||||
staged: GitFileStatus[];
|
||||
modified: GitFileStatus[];
|
||||
untracked: GitFileStatus[];
|
||||
conflicted: GitFileStatus[];
|
||||
is_clean: boolean;
|
||||
remote_url?: string;
|
||||
}
|
||||
|
||||
interface GitFileStatus {
|
||||
path: string;
|
||||
status: string;
|
||||
staged: boolean;
|
||||
}
|
||||
|
||||
interface GitCommitInfo {
|
||||
hash: string;
|
||||
short_hash: string;
|
||||
author: string;
|
||||
email: string;
|
||||
date: string;
|
||||
message: string;
|
||||
files_changed: number;
|
||||
insertions: number;
|
||||
deletions: number;
|
||||
}
|
||||
|
||||
interface GitBranchInfo {
|
||||
name: string;
|
||||
is_current: boolean;
|
||||
remote?: string;
|
||||
last_commit?: string;
|
||||
}
|
||||
|
||||
interface GitPanelProps {
|
||||
projectPath: string;
|
||||
isVisible: boolean;
|
||||
onToggle: () => void;
|
||||
width?: number;
|
||||
className?: string;
|
||||
refreshInterval?: number;
|
||||
}
|
||||
|
||||
// 获取文件状态图标
|
||||
const getFileStatusIcon = (status: string) => {
|
||||
switch (status) {
|
||||
case "added":
|
||||
return <FilePlus className="h-3 w-3 text-green-500" />;
|
||||
case "modified":
|
||||
return <FileEdit className="h-3 w-3 text-yellow-500" />;
|
||||
case "deleted":
|
||||
return <FileMinus className="h-3 w-3 text-red-500" />;
|
||||
case "renamed":
|
||||
return <FileEdit className="h-3 w-3 text-blue-500" />;
|
||||
case "untracked":
|
||||
return <Circle className="h-3 w-3 text-gray-500" />;
|
||||
case "conflicted":
|
||||
return <AlertCircle className="h-3 w-3 text-red-600" />;
|
||||
default:
|
||||
return <FileText className="h-3 w-3 text-muted-foreground" />;
|
||||
}
|
||||
};
|
||||
|
||||
// 格式化日期
|
||||
const formatDate = (dateStr: string, t: (key: string, opts?: any) => string) => {
|
||||
const date = new Date(dateStr);
|
||||
const now = new Date();
|
||||
const diff = now.getTime() - date.getTime();
|
||||
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
|
||||
const hours = Math.floor(diff / (1000 * 60 * 60));
|
||||
const minutes = Math.floor(diff / (1000 * 60));
|
||||
|
||||
if (days > 7) {
|
||||
return date.toLocaleDateString();
|
||||
} else if (days > 0) {
|
||||
return t('app.daysAgo', { count: days });
|
||||
} else if (hours > 0) {
|
||||
return t('app.hoursAgo', { count: hours });
|
||||
} else if (minutes > 0) {
|
||||
return t('app.minutesAgo', { count: minutes });
|
||||
} else {
|
||||
return t('app.justNow');
|
||||
}
|
||||
};
|
||||
|
||||
export const GitPanel: React.FC<GitPanelProps> = ({
|
||||
projectPath,
|
||||
isVisible,
|
||||
onToggle,
|
||||
width = 320,
|
||||
className,
|
||||
refreshInterval = 5000,
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const [gitStatus, setGitStatus] = useState<GitStatus | null>(null);
|
||||
const [commits, setCommits] = useState<GitCommitInfo[]>([]);
|
||||
const [branches, setBranches] = useState<GitBranchInfo[]>([]);
|
||||
const [selectedTab, setSelectedTab] = useState<"status" | "history" | "branches">("status");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
|
||||
// 获取 Git 状态
|
||||
const fetchGitStatus = useCallback(async () => {
|
||||
if (!projectPath) return;
|
||||
|
||||
try {
|
||||
setError(null);
|
||||
const status = await invoke<GitStatus>("get_git_status", {
|
||||
path: projectPath,
|
||||
});
|
||||
setGitStatus(status);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch git status:", err);
|
||||
setError(err instanceof Error ? err.message : "Failed to fetch git status");
|
||||
setGitStatus(null);
|
||||
}
|
||||
}, [projectPath]);
|
||||
|
||||
// 获取提交历史
|
||||
const fetchCommitHistory = useCallback(async () => {
|
||||
if (!projectPath) return;
|
||||
|
||||
try {
|
||||
const history = await invoke<GitCommitInfo[]>("get_git_history", {
|
||||
path: projectPath,
|
||||
limit: 50,
|
||||
});
|
||||
setCommits(history);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch commit history:", err);
|
||||
}
|
||||
}, [projectPath]);
|
||||
|
||||
// 获取分支列表
|
||||
const fetchBranches = useCallback(async () => {
|
||||
if (!projectPath) return;
|
||||
|
||||
try {
|
||||
const branchList = await invoke<GitBranchInfo[]>("get_git_branches", {
|
||||
path: projectPath,
|
||||
});
|
||||
setBranches(branchList);
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch branches:", err);
|
||||
}
|
||||
}, [projectPath]);
|
||||
|
||||
// 刷新所有数据
|
||||
const refreshAll = useCallback(async () => {
|
||||
setIsRefreshing(true);
|
||||
await Promise.all([
|
||||
fetchGitStatus(),
|
||||
fetchCommitHistory(),
|
||||
fetchBranches(),
|
||||
]);
|
||||
setIsRefreshing(false);
|
||||
}, [fetchGitStatus, fetchCommitHistory, fetchBranches]);
|
||||
|
||||
// 初始加载和定时刷新
|
||||
useEffect(() => {
|
||||
if (!projectPath || !isVisible) return;
|
||||
|
||||
setLoading(true);
|
||||
refreshAll().finally(() => setLoading(false));
|
||||
|
||||
// 定时刷新状态
|
||||
const interval = setInterval(() => {
|
||||
fetchGitStatus();
|
||||
}, refreshInterval);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [projectPath, isVisible, refreshInterval, refreshAll, fetchGitStatus]);
|
||||
|
||||
// 渲染状态视图
|
||||
const renderStatusView = () => {
|
||||
if (!gitStatus) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-32 text-muted-foreground">
|
||||
<GitBranch className="h-8 w-8 mb-2" />
|
||||
<p className="text-sm">{t('app.noGitRepository')}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Branch Info */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<GitBranch className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="font-medium">{gitStatus.branch}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{gitStatus.ahead > 0 && (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
↑ {gitStatus.ahead}
|
||||
</Badge>
|
||||
)}
|
||||
{gitStatus.behind > 0 && (
|
||||
<Badge variant="outline" className="text-xs">
|
||||
↓ {gitStatus.behind}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{gitStatus.remote_url && (
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{gitStatus.remote_url}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Status Summary */}
|
||||
{gitStatus.is_clean ? (
|
||||
<div className="flex items-center gap-2 p-3 bg-green-500/10 rounded-md">
|
||||
<CheckCircle className="h-4 w-4 text-green-600" />
|
||||
<span className="text-sm">{t('app.workingTreeClean')}</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
{gitStatus.staged.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-medium text-green-600">
|
||||
{t('app.staged')} ({gitStatus.staged.length})
|
||||
</p>
|
||||
{gitStatus.staged.map((file) => (
|
||||
<div
|
||||
key={`staged-${file.path}`}
|
||||
className="flex items-center gap-2 px-2 py-1 hover:bg-accent rounded-sm text-xs"
|
||||
>
|
||||
{getFileStatusIcon(file.status)}
|
||||
<span className="truncate">{file.path}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{gitStatus.modified.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-medium text-yellow-600">
|
||||
{t('app.modified')} ({gitStatus.modified.length})
|
||||
</p>
|
||||
{gitStatus.modified.map((file) => (
|
||||
<div
|
||||
key={`modified-${file.path}`}
|
||||
className="flex items-center gap-2 px-2 py-1 hover:bg-accent rounded-sm text-xs"
|
||||
>
|
||||
{getFileStatusIcon(file.status)}
|
||||
<span className="truncate">{file.path}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{gitStatus.untracked.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-medium text-gray-600">
|
||||
{t('app.untracked')} ({gitStatus.untracked.length})
|
||||
</p>
|
||||
{gitStatus.untracked.slice(0, 10).map((file) => (
|
||||
<div
|
||||
key={`untracked-${file.path}`}
|
||||
className="flex items-center gap-2 px-2 py-1 hover:bg-accent rounded-sm text-xs"
|
||||
>
|
||||
{getFileStatusIcon(file.status)}
|
||||
<span className="truncate">{file.path}</span>
|
||||
</div>
|
||||
))}
|
||||
{gitStatus.untracked.length > 10 && (
|
||||
<p className="text-xs text-muted-foreground pl-2">
|
||||
{t('app.andMore', { count: gitStatus.untracked.length - 10 })}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{gitStatus.conflicted.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<p className="text-xs font-medium text-red-600">
|
||||
{t('app.conflicted')} ({gitStatus.conflicted.length})
|
||||
</p>
|
||||
{gitStatus.conflicted.map((file) => (
|
||||
<div
|
||||
key={`conflicted-${file.path}`}
|
||||
className="flex items-center gap-2 px-2 py-1 hover:bg-accent rounded-sm text-xs"
|
||||
>
|
||||
{getFileStatusIcon(file.status)}
|
||||
<span className="truncate">{file.path}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// 渲染历史视图
|
||||
const renderHistoryView = () => {
|
||||
if (commits.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-32 text-muted-foreground">
|
||||
<GitCommit className="h-8 w-8 mb-2" />
|
||||
<p className="text-sm">{t('app.noCommitsFound')}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{commits.map((commit) => (
|
||||
<div
|
||||
key={commit.hash}
|
||||
className="p-3 border rounded-md hover:bg-accent transition-colors"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium truncate">
|
||||
{commit.message}
|
||||
</p>
|
||||
<div className="flex items-center gap-2 mt-1">
|
||||
<code className="text-xs text-muted-foreground">
|
||||
{commit.short_hash}
|
||||
</code>
|
||||
<span className="text-xs text-muted-foreground">•</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{commit.author}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-3 mt-1">
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{formatDate(commit.date, t)}
|
||||
</span>
|
||||
{commit.files_changed > 0 && (
|
||||
<>
|
||||
<span className="text-xs text-muted-foreground">•</span>
|
||||
<div className="flex items-center gap-2 text-xs">
|
||||
<span>{commit.files_changed} {t('app.filesChanged')}</span>
|
||||
<span className="text-green-600">+{commit.insertions}</span>
|
||||
<span className="text-red-600">-{commit.deletions}</span>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// 渲染分支视图
|
||||
const renderBranchesView = () => {
|
||||
if (branches.length === 0) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-32 text-muted-foreground">
|
||||
<GitMerge className="h-8 w-8 mb-2" />
|
||||
<p className="text-sm">{t('app.noBranchesFound')}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const localBranches = branches.filter(b => !b.remote);
|
||||
const remoteBranches = branches.filter(b => b.remote);
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{localBranches.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase">
|
||||
{t('app.localBranches')}
|
||||
</p>
|
||||
{localBranches.map((branch) => (
|
||||
<div
|
||||
key={branch.name}
|
||||
className={cn(
|
||||
"flex items-center justify-between p-2 rounded-md hover:bg-accent",
|
||||
branch.is_current && "bg-accent"
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<GitBranch className="h-3 w-3 text-muted-foreground" />
|
||||
<span className="text-sm">{branch.name}</span>
|
||||
{branch.is_current && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{t('app.current')}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
{branch.last_commit && (
|
||||
<code className="text-xs text-muted-foreground">
|
||||
{branch.last_commit.slice(0, 7)}
|
||||
</code>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{remoteBranches.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase">
|
||||
{t('app.remoteBranches')}
|
||||
</p>
|
||||
{remoteBranches.map((branch) => (
|
||||
<div
|
||||
key={branch.name}
|
||||
className="flex items-center justify-between p-2 rounded-md hover:bg-accent"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<GitPullRequest className="h-3 w-3 text-muted-foreground" />
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{branch.name}
|
||||
</span>
|
||||
</div>
|
||||
{branch.last_commit && (
|
||||
<code className="text-xs text-muted-foreground">
|
||||
{branch.last_commit.slice(0, 7)}
|
||||
</code>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<AnimatePresence>
|
||||
{isVisible && (
|
||||
<motion.div
|
||||
initial={{ x: "100%" }}
|
||||
animate={{ x: 0 }}
|
||||
exit={{ x: "100%" }}
|
||||
transition={{ type: "spring", damping: 20, stiffness: 300 }}
|
||||
className={cn(
|
||||
"fixed right-0 top-[172px] bottom-0 bg-background border-l border-border shadow-xl z-20",
|
||||
className
|
||||
)}
|
||||
style={{ width: `${width}px` }}
|
||||
>
|
||||
<div className="h-full flex flex-col">
|
||||
{/* Header */}
|
||||
<div className="p-3 border-b border-border">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<GitBranch className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-sm font-medium">{t('app.gitPanel')}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={refreshAll}
|
||||
disabled={isRefreshing}
|
||||
className="h-6 w-6"
|
||||
>
|
||||
{isRefreshing ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{t('app.refresh')}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onToggle}
|
||||
className="h-6 w-6"
|
||||
>
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<Tabs
|
||||
value={selectedTab}
|
||||
onValueChange={(v) => setSelectedTab(v as typeof selectedTab)}
|
||||
className="flex-1 flex flex-col"
|
||||
>
|
||||
<TabsList className="grid w-full grid-cols-3 rounded-none border-b">
|
||||
<TabsTrigger value="status" className="text-xs">
|
||||
{t('app.gitStatus')}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="history" className="text-xs">
|
||||
{t('app.gitHistory')}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="branches" className="text-xs">
|
||||
{t('app.gitBranches')}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{error ? (
|
||||
<div className="flex flex-col items-center justify-center h-32 p-4">
|
||||
<AlertCircle className="h-8 w-8 text-destructive mb-2" />
|
||||
<p className="text-sm text-muted-foreground text-center">{error}</p>
|
||||
</div>
|
||||
) : loading ? (
|
||||
<div className="flex items-center justify-center h-32">
|
||||
<Loader2 className="h-6 w-6 animate-spin" />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<TabsContent value="status" className="flex-1 mt-0">
|
||||
<ScrollArea className="h-full p-3">
|
||||
{renderStatusView()}
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="history" className="flex-1 mt-0">
|
||||
<ScrollArea className="h-full p-3">
|
||||
{renderHistoryView()}
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="branches" className="flex-1 mt-0">
|
||||
<ScrollArea className="h-full p-3">
|
||||
{renderBranchesView()}
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
</>
|
||||
)}
|
||||
</Tabs>
|
||||
</div>
|
||||
</motion.div>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
);
|
||||
};
|
||||
|
||||
// Add default export
|
||||
export default GitPanel;
|
192
src/components/ui/context-menu.tsx
Normal file
192
src/components/ui/context-menu.tsx
Normal file
@@ -0,0 +1,192 @@
|
||||
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,
|
||||
}
|
219
src/lib/eslint-integration.ts
Normal file
219
src/lib/eslint-integration.ts
Normal file
@@ -0,0 +1,219 @@
|
||||
import * as monaco from 'monaco-editor';
|
||||
import type { Linter } from 'eslint';
|
||||
|
||||
// 将 ESLint 诊断转换为 Monaco 标记
|
||||
export function convertESLintToMonacoMarkers(
|
||||
eslintMessages: Linter.LintMessage[],
|
||||
_model: monaco.editor.ITextModel
|
||||
): monaco.editor.IMarkerData[] {
|
||||
return eslintMessages.map(message => {
|
||||
return {
|
||||
severity: message.severity === 2
|
||||
? monaco.MarkerSeverity.Error
|
||||
: monaco.MarkerSeverity.Warning,
|
||||
startLineNumber: message.line || 1,
|
||||
startColumn: message.column || 1,
|
||||
endLineNumber: message.endLine || message.line || 1,
|
||||
endColumn: message.endColumn || (message.column ? message.column + 1 : 1),
|
||||
message: message.message,
|
||||
source: message.ruleId || 'eslint',
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// 实时语法检查配置
|
||||
export interface RealtimeLintOptions {
|
||||
enabled: boolean;
|
||||
delay: number; // 延迟时间(毫秒)
|
||||
showInlineErrors: boolean;
|
||||
showErrorsInScrollbar: boolean;
|
||||
showErrorsInMinimap: boolean;
|
||||
}
|
||||
|
||||
export const defaultLintOptions: RealtimeLintOptions = {
|
||||
enabled: true,
|
||||
delay: 500,
|
||||
showInlineErrors: true,
|
||||
showErrorsInScrollbar: true,
|
||||
showErrorsInMinimap: true,
|
||||
};
|
||||
|
||||
// 配置实时语法检查
|
||||
export function setupRealtimeLinting(
|
||||
editor: monaco.editor.IStandaloneCodeEditor,
|
||||
options: RealtimeLintOptions = defaultLintOptions
|
||||
) {
|
||||
if (!options.enabled) return;
|
||||
|
||||
let lintTimer: NodeJS.Timeout | null = null;
|
||||
|
||||
const performLinting = () => {
|
||||
const model = editor.getModel();
|
||||
if (!model) return;
|
||||
|
||||
const language = model.getLanguageId();
|
||||
if (language !== 'typescript' && language !== 'javascript' &&
|
||||
language !== 'typescriptreact' && language !== 'javascriptreact') {
|
||||
return;
|
||||
}
|
||||
|
||||
// 根据选项配置显示
|
||||
if (options.showErrorsInScrollbar) {
|
||||
editor.updateOptions({
|
||||
overviewRulerLanes: 3,
|
||||
});
|
||||
}
|
||||
|
||||
if (options.showErrorsInMinimap) {
|
||||
editor.updateOptions({
|
||||
minimap: {
|
||||
showSlider: 'always',
|
||||
renderCharacters: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// 监听内容变化
|
||||
editor.onDidChangeModelContent(() => {
|
||||
if (lintTimer) {
|
||||
clearTimeout(lintTimer);
|
||||
}
|
||||
|
||||
lintTimer = setTimeout(() => {
|
||||
performLinting();
|
||||
}, options.delay);
|
||||
});
|
||||
|
||||
// 初始检查
|
||||
performLinting();
|
||||
}
|
||||
|
||||
// 代码快速修复建议
|
||||
export interface QuickFix {
|
||||
title: string;
|
||||
kind: string;
|
||||
edit: monaco.languages.WorkspaceEdit;
|
||||
}
|
||||
|
||||
// 注册代码操作提供器(快速修复)
|
||||
export function registerCodeActionProvider() {
|
||||
monaco.languages.registerCodeActionProvider(['typescript', 'javascript', 'typescriptreact', 'javascriptreact'], {
|
||||
provideCodeActions: (model, _range, context, _token) => {
|
||||
const actions: monaco.languages.CodeAction[] = [];
|
||||
|
||||
// 检查是否有错误标记
|
||||
const markers = context.markers.filter(marker => marker.severity === monaco.MarkerSeverity.Error);
|
||||
|
||||
for (const marker of markers) {
|
||||
// 未使用变量的快速修复
|
||||
if (marker.code === '6133' || marker.message.includes('is declared but')) {
|
||||
actions.push({
|
||||
title: `Remove unused declaration`,
|
||||
kind: 'quickfix',
|
||||
diagnostics: [marker],
|
||||
edit: {
|
||||
edits: [{
|
||||
resource: model.uri,
|
||||
textEdit: {
|
||||
range: {
|
||||
startLineNumber: marker.startLineNumber,
|
||||
startColumn: 1,
|
||||
endLineNumber: marker.endLineNumber,
|
||||
endColumn: model.getLineLength(marker.endLineNumber) + 1,
|
||||
},
|
||||
text: '',
|
||||
},
|
||||
versionId: undefined,
|
||||
}],
|
||||
},
|
||||
isPreferred: true,
|
||||
});
|
||||
}
|
||||
|
||||
// 缺少导入的快速修复
|
||||
if (marker.message.includes('Cannot find name')) {
|
||||
const variableName = marker.message.match(/Cannot find name '([^']+)'/)?.[1];
|
||||
if (variableName) {
|
||||
actions.push({
|
||||
title: `Import '${variableName}'`,
|
||||
kind: 'quickfix',
|
||||
diagnostics: [marker],
|
||||
edit: {
|
||||
edits: [{
|
||||
resource: model.uri,
|
||||
textEdit: {
|
||||
range: {
|
||||
startLineNumber: 1,
|
||||
startColumn: 1,
|
||||
endLineNumber: 1,
|
||||
endColumn: 1,
|
||||
},
|
||||
text: `import { ${variableName} } from './${variableName.toLowerCase()}';\n`,
|
||||
},
|
||||
versionId: undefined,
|
||||
}],
|
||||
},
|
||||
isPreferred: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 类型错误的快速修复
|
||||
if (marker.message.includes('Type') && marker.message.includes('is not assignable')) {
|
||||
actions.push({
|
||||
title: 'Add type assertion',
|
||||
kind: 'quickfix',
|
||||
diagnostics: [marker],
|
||||
edit: {
|
||||
edits: [{
|
||||
resource: model.uri,
|
||||
textEdit: {
|
||||
range: {
|
||||
startLineNumber: marker.startLineNumber,
|
||||
startColumn: marker.startColumn,
|
||||
endLineNumber: marker.endLineNumber,
|
||||
endColumn: marker.endColumn,
|
||||
},
|
||||
text: `(${model.getValueInRange({
|
||||
startLineNumber: marker.startLineNumber,
|
||||
startColumn: marker.startColumn,
|
||||
endLineNumber: marker.endLineNumber,
|
||||
endColumn: marker.endColumn,
|
||||
})} as any)`,
|
||||
},
|
||||
versionId: undefined,
|
||||
}],
|
||||
},
|
||||
isPreferred: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 添加格式化操作
|
||||
actions.push({
|
||||
title: 'Format Document',
|
||||
kind: 'source.formatAll',
|
||||
command: {
|
||||
id: 'editor.action.formatDocument',
|
||||
title: 'Format Document',
|
||||
},
|
||||
});
|
||||
|
||||
// 添加组织导入操作
|
||||
actions.push({
|
||||
title: 'Organize Imports',
|
||||
kind: 'source.organizeImports',
|
||||
command: {
|
||||
id: 'editor.action.organizeImports',
|
||||
title: 'Organize Imports',
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
actions,
|
||||
dispose: () => {},
|
||||
};
|
||||
},
|
||||
});
|
||||
}
|
412
src/lib/monaco-config.ts
Normal file
412
src/lib/monaco-config.ts
Normal file
@@ -0,0 +1,412 @@
|
||||
import * as monaco from 'monaco-editor';
|
||||
import { registerCodeActionProvider } from './eslint-integration';
|
||||
|
||||
// TypeScript 默认编译选项
|
||||
export const defaultCompilerOptions: monaco.languages.typescript.CompilerOptions = {
|
||||
target: monaco.languages.typescript.ScriptTarget.Latest,
|
||||
allowNonTsExtensions: true,
|
||||
moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
|
||||
module: monaco.languages.typescript.ModuleKind.ESNext,
|
||||
noEmit: true,
|
||||
esModuleInterop: true,
|
||||
jsx: monaco.languages.typescript.JsxEmit.React,
|
||||
reactNamespace: 'React',
|
||||
allowJs: true,
|
||||
typeRoots: ['node_modules/@types'],
|
||||
lib: ['es2020', 'dom', 'dom.iterable', 'esnext'],
|
||||
strict: true,
|
||||
skipLibCheck: true,
|
||||
forceConsistentCasingInFileNames: true,
|
||||
resolveJsonModule: true,
|
||||
isolatedModules: true,
|
||||
noUnusedLocals: true,
|
||||
noUnusedParameters: true,
|
||||
noImplicitReturns: true,
|
||||
noFallthroughCasesInSwitch: true,
|
||||
};
|
||||
|
||||
// JavaScript 默认编译选项
|
||||
export const jsCompilerOptions: monaco.languages.typescript.CompilerOptions = {
|
||||
...defaultCompilerOptions,
|
||||
strict: false,
|
||||
noUnusedLocals: false,
|
||||
noUnusedParameters: false,
|
||||
checkJs: true,
|
||||
allowJs: true,
|
||||
};
|
||||
|
||||
// 配置 TypeScript 语言服务
|
||||
export function configureMonacoTypescript() {
|
||||
// 配置 TypeScript 默认选项
|
||||
monaco.languages.typescript.typescriptDefaults.setCompilerOptions(defaultCompilerOptions);
|
||||
|
||||
// 配置 JavaScript 默认选项
|
||||
monaco.languages.typescript.javascriptDefaults.setCompilerOptions(jsCompilerOptions);
|
||||
|
||||
// 设置诊断选项
|
||||
monaco.languages.typescript.typescriptDefaults.setDiagnosticsOptions({
|
||||
noSemanticValidation: false,
|
||||
noSyntaxValidation: false,
|
||||
noSuggestionDiagnostics: false,
|
||||
});
|
||||
|
||||
monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
|
||||
noSemanticValidation: false,
|
||||
noSyntaxValidation: false,
|
||||
noSuggestionDiagnostics: false,
|
||||
});
|
||||
|
||||
// 启用格式化选项
|
||||
monaco.languages.typescript.typescriptDefaults.setEagerModelSync(true);
|
||||
monaco.languages.typescript.javascriptDefaults.setEagerModelSync(true);
|
||||
}
|
||||
|
||||
// 添加常用类型定义
|
||||
export async function addTypeDefinitions() {
|
||||
const typeDefs = [
|
||||
{
|
||||
name: '@types/react',
|
||||
content: `
|
||||
declare module "react" {
|
||||
export interface ReactElement<P = any, T extends string | JSXElementConstructor<any> = string | JSXElementConstructor<any>> {
|
||||
type: T;
|
||||
props: P;
|
||||
key: Key | null;
|
||||
}
|
||||
export type FC<P = {}> = FunctionComponent<P>;
|
||||
export interface FunctionComponent<P = {}> {
|
||||
(props: P, context?: any): ReactElement<any, any> | null;
|
||||
}
|
||||
export function useState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
|
||||
export function useEffect(effect: EffectCallback, deps?: DependencyList): void;
|
||||
export function useCallback<T extends Function>(callback: T, deps: DependencyList): T;
|
||||
export function useMemo<T>(factory: () => T, deps: DependencyList): T;
|
||||
export function useRef<T>(initialValue: T): MutableRefObject<T>;
|
||||
}
|
||||
`
|
||||
},
|
||||
{
|
||||
name: '@types/node',
|
||||
content: `
|
||||
declare module "fs" {
|
||||
export function readFileSync(path: string, encoding?: string): string | Buffer;
|
||||
export function writeFileSync(path: string, data: string | Buffer): void;
|
||||
}
|
||||
declare module "path" {
|
||||
export function join(...paths: string[]): string;
|
||||
export function resolve(...paths: string[]): string;
|
||||
}
|
||||
`
|
||||
}
|
||||
];
|
||||
|
||||
for (const typeDef of typeDefs) {
|
||||
monaco.languages.typescript.typescriptDefaults.addExtraLib(
|
||||
typeDef.content,
|
||||
`file:///node_modules/${typeDef.name}/index.d.ts`
|
||||
);
|
||||
monaco.languages.typescript.javascriptDefaults.addExtraLib(
|
||||
typeDef.content,
|
||||
`file:///node_modules/${typeDef.name}/index.d.ts`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 注册自定义主题
|
||||
export function registerCustomThemes() {
|
||||
// VS Code Dark+ 主题
|
||||
monaco.editor.defineTheme('vs-dark-plus', {
|
||||
base: 'vs-dark',
|
||||
inherit: true,
|
||||
rules: [
|
||||
{ token: 'comment', foreground: '6A9955' },
|
||||
{ token: 'keyword', foreground: '569CD6' },
|
||||
{ token: 'string', foreground: 'CE9178' },
|
||||
{ token: 'number', foreground: 'B5CEA8' },
|
||||
{ token: 'type', foreground: '4EC9B0' },
|
||||
{ token: 'class', foreground: '4EC9B0' },
|
||||
{ token: 'function', foreground: 'DCDCAA' },
|
||||
{ token: 'variable', foreground: '9CDCFE' },
|
||||
{ token: 'constant', foreground: '4FC1FF' },
|
||||
{ token: 'parameter', foreground: '9CDCFE' },
|
||||
{ token: 'property', foreground: '9CDCFE' },
|
||||
{ token: 'regexp', foreground: 'D16969' },
|
||||
{ token: 'operator', foreground: 'D4D4D4' },
|
||||
{ token: 'namespace', foreground: '4EC9B0' },
|
||||
{ token: 'type.identifier', foreground: '4EC9B0' },
|
||||
{ token: 'tag', foreground: '569CD6' },
|
||||
{ token: 'attribute.name', foreground: '9CDCFE' },
|
||||
{ token: 'attribute.value', foreground: 'CE9178' },
|
||||
],
|
||||
colors: {
|
||||
'editor.background': '#1E1E1E',
|
||||
'editor.foreground': '#D4D4D4',
|
||||
'editorLineNumber.foreground': '#858585',
|
||||
'editorCursor.foreground': '#AEAFAD',
|
||||
'editor.selectionBackground': '#264F78',
|
||||
'editor.inactiveSelectionBackground': '#3A3D41',
|
||||
'editorIndentGuide.background': '#404040',
|
||||
'editorIndentGuide.activeBackground': '#707070',
|
||||
'editor.wordHighlightBackground': '#515C6A',
|
||||
'editor.wordHighlightStrongBackground': '#515C6A',
|
||||
'editorError.foreground': '#F48771',
|
||||
'editorWarning.foreground': '#CCA700',
|
||||
'editorInfo.foreground': '#75BEFF',
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 配置 JSON 语言
|
||||
export function configureJsonLanguage() {
|
||||
monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
|
||||
validate: true,
|
||||
schemas: [
|
||||
{
|
||||
uri: 'http://json-schema.org/draft-07/schema#',
|
||||
fileMatch: ['*.json'],
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: {},
|
||||
additionalProperties: true
|
||||
}
|
||||
},
|
||||
{
|
||||
uri: 'http://json.schemastore.org/package',
|
||||
fileMatch: ['package.json'],
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
name: { type: 'string' },
|
||||
version: { type: 'string' },
|
||||
dependencies: { type: 'object' },
|
||||
devDependencies: { type: 'object' },
|
||||
scripts: { type: 'object' }
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
uri: 'http://json.schemastore.org/tsconfig',
|
||||
fileMatch: ['tsconfig.json', 'tsconfig.*.json'],
|
||||
schema: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
compilerOptions: { type: 'object' },
|
||||
include: { type: 'array' },
|
||||
exclude: { type: 'array' }
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
allowComments: true,
|
||||
trailingCommas: 'warning'
|
||||
});
|
||||
}
|
||||
|
||||
// 添加代码片段
|
||||
export function registerSnippets() {
|
||||
// TypeScript/JavaScript 代码片段
|
||||
monaco.languages.registerCompletionItemProvider(['typescript', 'javascript', 'typescriptreact', 'javascriptreact'], {
|
||||
provideCompletionItems: (model, position) => {
|
||||
const word = model.getWordUntilPosition(position);
|
||||
const range = {
|
||||
startLineNumber: position.lineNumber,
|
||||
endLineNumber: position.lineNumber,
|
||||
startColumn: word.startColumn,
|
||||
endColumn: word.endColumn
|
||||
};
|
||||
|
||||
const suggestions = [
|
||||
{
|
||||
label: 'log',
|
||||
kind: monaco.languages.CompletionItemKind.Snippet,
|
||||
insertText: 'console.log(${1:message});',
|
||||
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
|
||||
documentation: 'Console log statement',
|
||||
range
|
||||
},
|
||||
{
|
||||
label: 'useState',
|
||||
kind: monaco.languages.CompletionItemKind.Snippet,
|
||||
insertText: 'const [${1:state}, set${1/(.*)/${1:/capitalize}/}] = useState(${2:initialValue});',
|
||||
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
|
||||
documentation: 'React useState hook',
|
||||
range
|
||||
},
|
||||
{
|
||||
label: 'useEffect',
|
||||
kind: monaco.languages.CompletionItemKind.Snippet,
|
||||
insertText: [
|
||||
'useEffect(() => {',
|
||||
'\t${1:// Effect logic}',
|
||||
'\treturn () => {',
|
||||
'\t\t${2:// Cleanup}',
|
||||
'\t};',
|
||||
'}, [${3:dependencies}]);'
|
||||
].join('\n'),
|
||||
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
|
||||
documentation: 'React useEffect hook',
|
||||
range
|
||||
},
|
||||
{
|
||||
label: 'component',
|
||||
kind: monaco.languages.CompletionItemKind.Snippet,
|
||||
insertText: [
|
||||
'const ${1:ComponentName}: React.FC = () => {',
|
||||
'\treturn (',
|
||||
'\t\t<div>',
|
||||
'\t\t\t${2:content}',
|
||||
'\t\t</div>',
|
||||
'\t);',
|
||||
'};',
|
||||
'',
|
||||
'export default ${1:ComponentName};'
|
||||
].join('\n'),
|
||||
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
|
||||
documentation: 'React functional component',
|
||||
range
|
||||
},
|
||||
{
|
||||
label: 'async',
|
||||
kind: monaco.languages.CompletionItemKind.Snippet,
|
||||
insertText: [
|
||||
'async function ${1:functionName}() {',
|
||||
'\ttry {',
|
||||
'\t\tconst result = await ${2:promise};',
|
||||
'\t\t${3:// Handle result}',
|
||||
'\t} catch (error) {',
|
||||
'\t\tconsole.error(error);',
|
||||
'\t}',
|
||||
'}'
|
||||
].join('\n'),
|
||||
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
|
||||
documentation: 'Async function with try-catch',
|
||||
range
|
||||
}
|
||||
];
|
||||
|
||||
return { suggestions };
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 配置语言特性
|
||||
export function configureLanguageFeatures() {
|
||||
// 配置 HTML 标签自动闭合
|
||||
monaco.languages.registerOnTypeFormattingEditProvider(['html', 'xml', 'javascriptreact', 'typescriptreact'], {
|
||||
autoFormatTriggerCharacters: ['>'],
|
||||
provideOnTypeFormattingEdits: (model, position, ch) => {
|
||||
if (ch === '>') {
|
||||
const lineContent = model.getLineContent(position.lineNumber);
|
||||
const beforeCursor = lineContent.substring(0, position.column - 1);
|
||||
|
||||
// 检查是否是开始标签
|
||||
const tagMatch = beforeCursor.match(/<(\w+)(?:\s+[^>]*)?>/);
|
||||
if (tagMatch) {
|
||||
const tagName = tagMatch[1];
|
||||
// 自闭合标签列表
|
||||
const selfClosingTags = ['img', 'br', 'hr', 'input', 'meta', 'link'];
|
||||
if (!selfClosingTags.includes(tagName.toLowerCase())) {
|
||||
return [{
|
||||
range: {
|
||||
startLineNumber: position.lineNumber,
|
||||
startColumn: position.column,
|
||||
endLineNumber: position.lineNumber,
|
||||
endColumn: position.column
|
||||
},
|
||||
text: `</${tagName}>`
|
||||
}];
|
||||
}
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
});
|
||||
|
||||
// 配置括号自动配对
|
||||
monaco.languages.setLanguageConfiguration('typescript', {
|
||||
autoClosingPairs: [
|
||||
{ open: '{', close: '}' },
|
||||
{ open: '[', close: ']' },
|
||||
{ open: '(', close: ')' },
|
||||
{ open: '"', close: '"' },
|
||||
{ open: "'", close: "'" },
|
||||
{ open: '`', close: '`' },
|
||||
{ open: '<', close: '>' },
|
||||
],
|
||||
surroundingPairs: [
|
||||
{ open: '{', close: '}' },
|
||||
{ open: '[', close: ']' },
|
||||
{ open: '(', close: ')' },
|
||||
{ open: '"', close: '"' },
|
||||
{ open: "'", close: "'" },
|
||||
{ open: '`', close: '`' },
|
||||
{ open: '<', close: '>' },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化 Monaco Editor 配置
|
||||
export async function initializeMonaco() {
|
||||
// 配置 TypeScript/JavaScript
|
||||
configureMonacoTypescript();
|
||||
|
||||
// 添加类型定义
|
||||
await addTypeDefinitions();
|
||||
|
||||
// 注册自定义主题
|
||||
registerCustomThemes();
|
||||
|
||||
// 配置 JSON
|
||||
configureJsonLanguage();
|
||||
|
||||
// 注册代码片段
|
||||
registerSnippets();
|
||||
|
||||
// 配置语言特性
|
||||
configureLanguageFeatures();
|
||||
|
||||
// 注册代码操作提供器(快速修复)
|
||||
registerCodeActionProvider();
|
||||
}
|
||||
|
||||
// 格式化文档
|
||||
export function formatDocument(editor: monaco.editor.IStandaloneCodeEditor) {
|
||||
editor.getAction('editor.action.formatDocument')?.run();
|
||||
}
|
||||
|
||||
// 添加错误标记
|
||||
export function addErrorMarkers(
|
||||
editor: monaco.editor.IStandaloneCodeEditor,
|
||||
errors: Array<{
|
||||
line: number;
|
||||
column: number;
|
||||
message: string;
|
||||
severity: 'error' | 'warning' | 'info';
|
||||
}>
|
||||
) {
|
||||
const model = editor.getModel();
|
||||
if (!model) return;
|
||||
|
||||
const markers = errors.map(error => ({
|
||||
severity: error.severity === 'error'
|
||||
? monaco.MarkerSeverity.Error
|
||||
: error.severity === 'warning'
|
||||
? monaco.MarkerSeverity.Warning
|
||||
: monaco.MarkerSeverity.Info,
|
||||
startLineNumber: error.line,
|
||||
startColumn: error.column,
|
||||
endLineNumber: error.line,
|
||||
endColumn: error.column + 1,
|
||||
message: error.message,
|
||||
}));
|
||||
|
||||
monaco.editor.setModelMarkers(model, 'owner', markers);
|
||||
}
|
||||
|
||||
// 清除错误标记
|
||||
export function clearErrorMarkers(editor: monaco.editor.IStandaloneCodeEditor) {
|
||||
const model = editor.getModel();
|
||||
if (model) {
|
||||
monaco.editor.setModelMarkers(model, 'owner', []);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user