import { useState, useEffect, useRef, useMemo } from 'react' import { useParams, useNavigate, useSearchParams } from 'react-router-dom' import { Layout, Menu, Button, Modal, Input, Space, Tooltip, Dropdown, Upload, Select, Progress, TreeSelect } from 'antd' import { FileOutlined, FolderOutlined, PlusOutlined, DeleteOutlined, EditOutlined, SaveOutlined, FileAddOutlined, FolderAddOutlined, UploadOutlined, SwapOutlined, ReloadOutlined, FileImageOutlined, FilePdfOutlined, FileTextOutlined, UndoOutlined, CloseOutlined, } from '@ant-design/icons' import { Editor } from '@bytemd/react' import gfm from '@bytemd/plugin-gfm' import highlight from '@bytemd/plugin-highlight' import breaks from '@bytemd/plugin-breaks' import frontmatter from '@bytemd/plugin-frontmatter' import gemoji from '@bytemd/plugin-gemoji' import 'bytemd/dist/index.css' import 'highlight.js/styles/github.css' import { saveFile, operateFile, uploadFile, importDocuments, uploadDocument, } from '@/api/file' import Toast from '@/components/Toast/Toast' import ModeSwitch from '@/components/ModeSwitch/ModeSwitch' import { findNodeByKey } from './documentBrowserUtils' import useDocumentEditorWorkspace from './useDocumentEditorWorkspace' import './DocumentEditor.css' const { Sider, Content } = Layout function DocumentEditor() { const { projectId } = useParams() const navigate = useNavigate() const [searchParams, setSearchParams] = useSearchParams() const fileInputRef = useRef(null) const { treeData, selectedFile, selectedNode, fileContent, loading, openKeys, selectedMenuKey, isPdfSelected, refreshing, projectName, userRole, setOpenKeys, setSelectedNode, setSelectedFile, setSelectedMenuKey, setFileContent, fetchTree, clearSelection, openNodeByKey, handleMenuClick, refreshCurrentDocument, } = useDocumentEditorWorkspace({ projectId, searchParams, setSearchParams, }) const [saving, setSaving] = useState(false) const [modalVisible, setModalVisible] = useState(false) const [moveModalVisible, setMoveModalVisible] = useState(false) const [operationType, setOperationType] = useState(null) const [newName, setNewName] = useState('') const [rightClickNode, setRightClickNode] = useState(null) const [creationParentPath, setCreationParentPath] = useState('') const [moveTargetPath, setMoveTargetPath] = useState('') const [dirOptions, setDirOptions] = useState([]) const [editorHeight, setEditorHeight] = useState(600) // 设置初始高度为600px const [uploadProgress, setUploadProgress] = useState(0) // 上传进度 const [uploading, setUploading] = useState(false) // 是否正在上传 const [fileList, setFileList] = useState([]) // 控制上传文件列表 const uploadingRef = useRef(false) // 使用ref防止重复上传 const [linkModalVisible, setLinkModalVisible] = useState(false) const [linkTarget, setLinkTarget] = useState(null) const [modeSwitchValue, setModeSwitchValue] = useState('edit') const editorCtxRef = useRef(null) const modeSwitchingRef = useRef(false) const navigateWithTransition = (to) => { if (document.startViewTransition) { document.startViewTransition(() => navigate(to)) return } navigate(to) } // 插入内链接 const handleInsertLink = () => { if (!linkTarget) { Toast.warning('提示', '请选择文件') return } if (editorCtxRef.current && editorCtxRef.current.editor) { const editor = editorCtxRef.current.editor // 获取当前选中的文字 const selection = editor.getSelection() // 简单的从路径获取文件名作为备选 const fileName = linkTarget.split('/').pop() // 如果没有选中文字,则使用文件名作为链接文字;否则保留原文字 const linkTitle = selection || fileName const linkText = `[${linkTitle}](${linkTarget})` editor.replaceSelection(linkText) editor.focus() } setLinkModalVisible(false) setLinkTarget(null) } // 在组件挂载后立即计算正确的高度 useEffect(() => { const calculateHeight = () => { const windowHeight = window.innerHeight const newHeight = Math.max(windowHeight - 180, 400) // 最小高度400px setEditorHeight(newHeight) } // 立即执行一次 calculateHeight() // 监听窗口大小变化 window.addEventListener('resize', calculateHeight) return () => window.removeEventListener('resize', calculateHeight) }, []) const handleRefresh = async () => { await refreshCurrentDocument() } const handleClose = () => { Modal.confirm({ title: '确认退出', content: '确定要退出编辑页面吗?未保存的修改可能会丢失。', okText: '退出', cancelText: '取消', onOk: () => { if (userRole === 'owner') { navigate('/projects/my') } else { navigate('/projects/share') } }, }) } // 重置当前编辑内容(重新从服务器加载) const handleReset = () => { if (!selectedFile) return Modal.confirm({ title: '确认重置', content: '确定要重置当前修改吗?所有未保存的更改都将丢失。', onOk: async () => { await openNodeByKey(selectedFile, null, false) Toast.success('重置成功', '已恢复至最后保存的版本') }, }) } const handleSaveFile = async () => { if (!selectedFile) { Toast.warning('提示', '请先选择文件') return } setSaving(true) try { await saveFile(projectId, { path: selectedFile, content: fileContent, }) Toast.success('成功', '保存成功') } catch (error) { // 错误已通过request interceptor处理 } finally { setSaving(false) } } const getParentPath = (node) => { if (!node) return '' if (!node.isLeaf) return node.key const parts = node.key.split('/') parts.pop() return parts.join('/') } const handleCreateFile = (node = null) => { // If clicked from button (node is event or undefined), use selectedNode // If clicked from context menu (node is passed), use it const targetNode = (node && node.key) ? node : selectedNode const parentPath = getParentPath(targetNode) setCreationParentPath(parentPath) setOperationType('create_file') setModalVisible(true) } const handleCreateDir = (node = null) => { const targetNode = (node && node.key) ? node : selectedNode const parentPath = getParentPath(targetNode) setCreationParentPath(parentPath) setOperationType('create_dir') setModalVisible(true) } const handleDelete = (path = selectedFile) => { if (!path) { Toast.warning('提示', '请先选择文件') return } Modal.confirm({ title: '确认删除', content: `确定要删除 ${path} 吗?`, onOk: async () => { try { await operateFile(projectId, { action: 'delete', path: path, }) Toast.success('成功', '删除成功') if (selectedFile === path) { clearSelection() } fetchTree() } catch (error) { console.error('Delete error:', error) Toast.error('错误', '删除失败') } }, }) } const handleRename = (path) => { const fileName = path.split('/').pop() // 保护README.md if (fileName === 'README.md' && path.indexOf('/') === -1) { Toast.error('错误', '根目录的README.md不允许重命名') return } setRightClickNode(path) setNewName(fileName) setOperationType('rename') setModalVisible(true) } const handleOperation = async () => { if (!newName.trim()) { Toast.warning('提示', '请输入名称') return } try { let path, params if (operationType === 'rename') { // 重命名操作 const oldPath = rightClickNode const pathParts = oldPath.split('/') pathParts[pathParts.length - 1] = newName const newPath = pathParts.join('/') params = { action: 'rename', path: oldPath, new_path: newPath, } } else { // 自动补全后缀 (仅针对新建文件) let finalName = newName if (operationType === 'create_file' && finalName.indexOf('.') === -1) { finalName += '.md' } // 创建操作 - 使用预先计算的父目录路径 path = creationParentPath ? `${creationParentPath}/${finalName}` : finalName // 检查文件是否已存在 const fileExists = checkFileExists(path) if (fileExists) { Modal.confirm({ title: '文件已存在', content: `文件 "${finalName}" 已存在,是否覆盖?`, okText: '覆盖', cancelText: '取消', onOk: async () => { await executeOperation(operationType, path) }, }) return } params = { action: operationType, path: path, content: operationType === 'create_file' ? '# 新文件\n' : undefined, } } await operateFile(projectId, params) Toast.success('成功', '操作成功') setModalVisible(false) setNewName('') setRightClickNode(null) fetchTree() // 如果重命名的是当前打开的文件,清空编辑器 if (operationType === 'rename' && selectedFile === rightClickNode) { clearSelection() } } catch (error) { console.error('Operation error:', error) Toast.error('错误', '操作失败') } } // 检查文件是否存在 const checkFileExists = (path) => { const checkInTree = (nodes, targetPath) => { for (const node of nodes) { if (node.key === targetPath) { return true } if (node.children) { if (checkInTree(node.children, targetPath)) { return true } } } return false } return checkInTree(treeData, path) } // 执行创建操作 const executeOperation = async (operation, path) => { const params = { action: operation, path: path, content: operation === 'create_file' ? '# 新文件\n' : undefined, } await operateFile(projectId, params) Toast.success('成功', '操作成功') setModalVisible(false) setNewName('') setRightClickNode(null) fetchTree() } // 上传文档(支持MD和PDF) const handleImportDocuments = async (info) => { // 防止重复触发 if (uploadingRef.current) { return } const { fileList: currentFileList } = info // 立即更新state以显示当前选择的文件 setFileList(currentFileList) // 过滤出有效文件 const mdFiles = currentFileList.filter((f) => f.name.endsWith('.md')) const pdfFiles = currentFileList.filter((f) => f.name.toLowerCase().endsWith('.pdf')) const allFiles = [...mdFiles, ...pdfFiles] if (allFiles.length === 0) { Toast.warning('提示', '请选择.md或.pdf格式的文档') setFileList([]) // 清空文件列表 return } // 设置上传标记 uploadingRef.current = true // 确定目标路径(如果选中了目录,上传到该目录) const targetPath = selectedNode && !selectedNode.isLeaf ? selectedNode.key : '' // 检查是否有重名文件 const existingFiles = [] allFiles.forEach((f) => { const filePath = targetPath ? `${targetPath}/${f.name}` : f.name if (checkFileExists(filePath)) { existingFiles.push(f.name) } }) // 如果有重名文件,询问是否覆盖 if (existingFiles.length > 0) { Modal.confirm({ title: '文件已存在', content: (
以下文件已存在,是否覆盖?
PDF文件请在浏览模式下查看
请从左侧选择要编辑的文件
选择目标目录:
选择要链接的文件: