@@ -1567,7 +1564,7 @@ function Chat() {
onChange={handleSearchKeywordChange}
placeholder="输入聊天关键词,仅搜索对话内容"
allowClear
- onPressEnter={handleSearch}
+ {...searchImeSubmit}
/>
} loading={searchLoading} onClick={handleSearch}>
搜索
diff --git a/frontend/src/pages/Document/DocumentEditor.css b/frontend/src/pages/Document/DocumentEditor.css
index a47e6b3..17eb226 100644
--- a/frontend/src/pages/Document/DocumentEditor.css
+++ b/frontend/src/pages/Document/DocumentEditor.css
@@ -516,6 +516,21 @@
color: var(--text-color);
}
+/* ByteMD 把编辑区正文锁成 800px 居中(.CodeMirror-lines { max-width: 800px; margin: 0 auto }),
+ 「仅编辑区」在宽屏显示器上左右各空出一大片,看起来像页面没铺满、字数也浪费。
+ 源码编辑器按可用宽度铺满更符合直觉(和 VS Code 一致),行号与光标位置由 CodeMirror 自己测量,不受影响。 */
+.bytemd-wrapper .bytemd-editor .CodeMirror .CodeMirror-lines {
+ max-width: none;
+ margin: 0;
+ padding: var(--space-md) 0;
+}
+
+/* 原本左右 4% 的内缩是给 800px 窄栏配的,铺满后按比例越拉越宽,改成固定留白 */
+.bytemd-wrapper .bytemd-editor .CodeMirror pre.CodeMirror-line,
+.bytemd-wrapper .bytemd-editor .CodeMirror pre.CodeMirror-line-like {
+ padding: 0 var(--space-md);
+}
+
/* CodeMirror 滚动容器 */
.bytemd-editor .CodeMirror-scroll {
overflow-y: scroll !important;
@@ -524,6 +539,14 @@
height: 100% !important;
}
+/* 预览区继续保留「可读行长」,但跟着视口放宽:ByteMD 固定在 800px,
+ 宽屏分栏/仅预览时同样会留出大片空白,这里放到 1100px 并保证不留横向死边。 */
+.bytemd-wrapper .bytemd-preview .markdown-body {
+ max-width: min(100%, 1100px);
+ margin: 0 auto;
+ padding: var(--space-md) var(--space-lg);
+}
+
/* 预览区域的markdown样式 */
.bytemd-preview h1,
.bytemd-preview h2,
@@ -638,6 +661,21 @@
}
}
+/* 新建/重命名弹窗的补充说明:解释后缀规则,避免用户以为后缀被吞掉了 */
+.modal-field-hint {
+ margin-top: var(--space-xs);
+ font-size: 12px;
+ line-height: 1.6;
+ color: var(--text-color-secondary);
+}
+
+.modal-field-hint code {
+ padding: 0 var(--space-xxs);
+ color: var(--text-color);
+ background: var(--code-bg);
+ border-radius: var(--radius-xs);
+}
+
/* 未保存改动标记:与保存按钮同处内容区右上角,弱化但可辨识 */
.content-header-actions .unsaved-badge {
display: inline-flex;
diff --git a/frontend/src/pages/Document/DocumentEditor.jsx b/frontend/src/pages/Document/DocumentEditor.jsx
index 3952fef..028e3d4 100644
--- a/frontend/src/pages/Document/DocumentEditor.jsx
+++ b/frontend/src/pages/Document/DocumentEditor.jsx
@@ -52,6 +52,8 @@ import ProjectFileTree from '@/components/ProjectFileTree/ProjectFileTree'
import FloatingToc from '@/components/FloatingToc/FloatingToc'
import { extractMarkdownHeadings } from '@/utils/markdownToc'
import { findNodeByKey, mergeParentKeys } from '@/utils/treeUtils'
+import { useImeSafeEnter } from '@/utils/ime'
+import { applyExtension, containsPathSeparator, splitFileName, stripMarkdownExtension } from '@/utils/fileNaming'
import {
EDITOR_VIEW_MODES,
EDITOR_VIEW_MODE_LABELS,
@@ -83,6 +85,12 @@ function DocumentEditor() {
const [moveModalVisible, setMoveModalVisible] = useState(false)
const [operationType, setOperationType] = useState(null)
const [newName, setNewName] = useState('')
+ // 重命名时锁定的后缀:输入框里只放主名,后缀单独展示,用户改不到文件类型
+ const [lockedExtension, setLockedExtension] = useState('')
+ // 提交中标记:回车和「确定」按钮可能被连续触发,避免同一次文件操作发两遍
+ const operatingRef = useRef(false)
+ // 新建/重命名弹窗里的名称输入框,用于弹窗打开后把焦点抢回来
+ const nameInputRef = useRef(null)
const [rightClickNode, setRightClickNode] = useState(null)
const [creationParentPath, setCreationParentPath] = useState('')
const [moveTargetPath, setMoveTargetPath] = useState('')
@@ -844,6 +852,7 @@ function DocumentEditor() {
setCreationParentPath(parentPath)
setOperationType('create_file')
+ setLockedExtension('')
setModalVisible(true)
}
@@ -853,6 +862,7 @@ function DocumentEditor() {
setCreationParentPath(parentPath)
setOperationType('create_dir')
+ setLockedExtension('')
setModalVisible(true)
}
@@ -894,83 +904,174 @@ function DocumentEditor() {
return
}
+ // 文件夹整体是名字(v1.2.0 这类目录名不能按点切分);只有文件才拆出固定后缀
+ const node = findNodeByKey(treeData, path)
+ const isFile = node ? node.isLeaf !== false : fileName.includes('.')
+ const { base, ext } = isFile ? splitFileName(fileName) : { base: fileName, ext: '' }
+
setRightClickNode(path)
- setNewName(fileName)
+ setNewName(base)
+ setLockedExtension(isFile ? ext : '')
setOperationType('rename')
setModalVisible(true)
}
const handleOperation = async () => {
- if (!newName.trim()) {
+ if (operatingRef.current) return
+
+ const rawName = newName.trim()
+ if (!rawName) {
Toast.warning('提示', '请输入名称')
return
}
+ if (containsPathSeparator(rawName)) {
+ Toast.warning('提示', '名称里不能包含 / 或 \\ ,只能在当前目录下改名')
+ return
+ }
- try {
- let path, params
+ let path, params
+ let renamedFrom = null
+ let renamedTo = null
- 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) {
- Toast.confirm({
- title: '文件已存在',
- content: `文件 "${finalName}" 已存在,是否覆盖?`,
- okText: '覆盖',
- cancelText: '取消',
- onOk: async () => {
- await executeOperation(operationType, path)
- },
- })
- return
- }
-
- params = {
- action: operationType,
- path: path,
- content: operationType === 'create_file' ? '# 新文件\n' : undefined,
- }
+ if (operationType === 'rename') {
+ // 重命名只替换路径的最后一段,并强制拼回原后缀:文件类型由系统锁定,用户改不了
+ const oldPath = rightClickNode
+ const oldName = oldPath.split('/').pop()
+ const finalName = applyExtension(rawName, lockedExtension)
+ if (!finalName) {
+ Toast.warning('提示', '请输入名称')
+ return
+ }
+ if (finalName === oldName) {
+ // 名字没变,直接收起弹窗,免得白记一条操作记录
+ setModalVisible(false)
+ return
}
+ const pathParts = oldPath.split('/')
+ pathParts[pathParts.length - 1] = finalName
+ renamedFrom = oldPath
+ renamedTo = pathParts.join('/')
+
+ if (checkFileExists(renamedTo)) {
+ Toast.error('无法重命名', `同级目录下已有 "${finalName}"`)
+ return
+ }
+
+ params = {
+ action: 'rename',
+ path: oldPath,
+ new_path: renamedTo,
+ }
+ } else {
+ // 自动补全后缀 (仅针对新建文件)
+ let finalName = rawName
+ if (operationType === 'create_file' && finalName.indexOf('.') === -1) {
+ finalName += '.md'
+ }
+
+ // 创建操作 - 使用预先计算的父目录路径
+ path = creationParentPath ? `${creationParentPath}/${finalName}` : finalName
+
+ // 检查文件是否已存在
+ const fileExists = checkFileExists(path)
+ if (fileExists) {
+ Toast.confirm({
+ title: '文件已存在',
+ content: `文件 "${finalName}" 已存在,是否覆盖?`,
+ okText: '覆盖',
+ cancelText: '取消',
+ onOk: async () => {
+ await executeOperation(operationType, path)
+ },
+ })
+ return
+ }
+
+ params = {
+ action: operationType,
+ path: path,
+ content: operationType === 'create_file' ? '# 新文件\n' : undefined,
+ }
+ }
+
+ operatingRef.current = true
+ try {
await operateFile(projectId, params)
Toast.success('成功', '操作成功')
setModalVisible(false)
setNewName('')
+ setLockedExtension('')
setRightClickNode(null)
fetchTree()
- // 如果重命名的是当前打开的文件,清空编辑器
- if (operationType === 'rename' && selectedFile === rightClickNode) {
- setSelectedFile(null)
- setFileContent('')
+ if (renamedFrom) {
+ syncSelectionAfterRename(renamedFrom, renamedTo)
}
} catch (error) {
console.error('Operation error:', error)
Toast.error('错误', '操作失败')
+ } finally {
+ operatingRef.current = false
}
}
+ /**
+ * 重命名之后同步编辑器、文件夹视图与地址栏。
+ *
+ * 重命名改变的只是路径前缀,节点内容本身没变,所以凡是落在被改名节点内部
+ * (含节点自身)的选中项都换成对应的新路径、继续停在原地:
+ * 开着文件就接着编辑,浏览着文件夹就接着浏览,
+ * 而不是像以前那样清空选中态,让用户白白丢一篇正在编辑的文章。
+ */
+ const syncSelectionAfterRename = (oldPath, newPath) => {
+ // 路径是否就是被改名的节点,或者位于它内部
+ const withinRenamed = (path) => Boolean(path)
+ && (path === oldPath || path.startsWith(`${oldPath}/`))
+ // 把旧路径替换成对应的新路径(只换前缀,深度不变)
+ const toNewPath = (path) => newPath + path.slice(oldPath.length)
+
+ // 树节点 key 本身就是路径,也要跟着换。
+ // fetchTree 是异步的,此刻 treeData 里还是改名前的节点,
+ // 因此只能手动改 key/title(如上传时按 selectedNode.key 决定目标目录)。
+ setSelectedNode((prev) => {
+ if (!withinRenamed(prev?.key)) return prev
+ const nextKey = toNewPath(prev.key)
+ return { ...prev, key: nextKey, title: nextKey.split('/').pop() }
+ })
+
+ // 已展开的目录同理,否则改名后子目录的展开状态会整块丢失
+ setOpenKeys((prev) => prev.map((key) => (withinRenamed(key) ? toNewPath(key) : key)))
+
+ // 1) 正在编辑(或内置预览)的文件
+ if (withinRenamed(selectedFile)) {
+ const nextFile = toNewPath(selectedFile)
+ setSelectedFile(nextFile)
+ setSelectedMenuKey(nextFile)
+ updateFileParam(nextFile)
+ expandParentFolders(nextFile)
+ if (isPdfSelected) {
+ // PDF 靠 URL 渲染,路径变了必须重新生成带鉴权参数的地址
+ setPdfUrl(buildDocumentUrl(nextFile))
+ setPdfFilename(nextFile.split('/').pop())
+ }
+ return
+ }
+
+ // 2) 正在浏览的文件夹(此时没有选中文件,内容区展示的是文件夹内容)
+ if (withinRenamed(selectedFolderKey)) {
+ const nextFolder = toNewPath(selectedFolderKey)
+ setSelectedFolderKey(nextFolder)
+ setSelectedMenuKey(nextFolder)
+ updateSelectedParam(nextFolder, false)
+ // 与 selectFolder 保持一致:借用占位子路径,让父级链和自身都保持展开
+ expandParentFolders(`${nextFolder}/placeholder`)
+ }
+ }
+
+ // 新建/重命名弹窗的回车提交:输入法组合输入中的回车留给输入法选词,不会误触发创建
+ const nameInputImeSubmit = useImeSafeEnter(handleOperation)
+
// 检查文件是否存在
const checkFileExists = (path) => {
const checkInTree = (nodes, targetPath) => {
@@ -1000,6 +1101,7 @@ function DocumentEditor() {
Toast.success('成功', '操作成功')
setModalVisible(false)
setNewName('')
+ setLockedExtension('')
setRightClickNode(null)
fetchTree()
}
@@ -1580,7 +1682,7 @@ function DocumentEditor() {
))}
{files.map(file => {
const isPdf = file.title.toLowerCase().endsWith('.pdf')
- const displayName = isPdf ? file.title : file.title.replace(/.md$/i, '')
+ const displayName = isPdf ? file.title : stripMarkdownExtension(file.title)
return (
{
+ if (open) nameInputRef.current?.focus()
+ }}
onOk={handleOperation}
onCancel={() => {
setModalVisible(false)
setNewName('')
+ setLockedExtension('')
setRightClickNode(null)
}}
>
setNewName(e.target.value)}
- onPressEnter={handleOperation}
+ addonAfter={operationType === 'rename' ? lockedExtension || null : null}
+ {...nameInputImeSubmit}
/>
+ {operationType === 'rename' && lockedExtension && (
+
后缀 {lockedExtension} 由文件类型决定,已锁定,重命名不会改动它
+ )}
+ {operationType === 'create_file' && (
+
不写后缀时默认创建 Markdown 文档(.md)
+ )}
{ base: 'intro', ext: '.md' }
+ * 'archive.tar.gz'-> { base: 'archive.tar', ext: '.gz' }
+ * 'README' -> { base: 'README', ext: '' }
+ * '.gitignore' -> { base: '.gitignore', ext: '' }(隐藏文件整体是名字)
+ */
+export function splitFileName(fileName = '') {
+ const dotIndex = fileName.lastIndexOf('.')
+ if (dotIndex <= 0) return { base: fileName, ext: '' }
+ return { base: fileName.slice(0, dotIndex), ext: fileName.slice(dotIndex) }
+}
+
+/** 名称里不允许出现路径分隔符,否则等于绕过父目录约束去改动目录结构 */
+export function containsPathSeparator(name = '') {
+ return name.includes('/') || name.includes('\\')
+}
+
+/**
+ * 用固定后缀拼回完整文件名。
+ * 用户把后缀一起打进输入框("report.md")时不会被拼成 "report.md.md";
+ * 只输入了后缀(主名为空)时返回空串,交由调用方提示。
+ */
+export function applyExtension(base, ext = '') {
+ const cleanBase = (base || '').trim()
+ if (!ext) return cleanBase
+ if (cleanBase.toLowerCase().endsWith(ext.toLowerCase())) {
+ const nameOnly = cleanBase.slice(0, cleanBase.length - ext.length)
+ return nameOnly ? cleanBase : ''
+ }
+ return cleanBase + ext
+}
+
+/** 去掉 Markdown 后缀用于展示;后缀大小写不限,且不会误伤同名结尾的字母 */
+export function stripMarkdownExtension(fileName = '') {
+ return fileName.replace(/\.md$/i, '')
+}
diff --git a/frontend/src/utils/ime.js b/frontend/src/utils/ime.js
new file mode 100644
index 0000000..380636d
--- /dev/null
+++ b/frontend/src/utils/ime.js
@@ -0,0 +1,64 @@
+import { useCallback, useRef } from 'react'
+
+/**
+ * 输入法(IME)与「回车提交」的冲突处理。
+ *
+ * 中文输入法在组合输入(拼音、候选词)过程中,回车表示「把候选词上屏」,
+ * 而不是「提交表单」。这两种回车在 DOM 里是同一个 keydown 事件,只能靠事件标记区分:
+ * - 标准标记:KeyboardEvent.isComposing === true
+ * - 兼容标记:组合输入期间 keydown 的 keyCode 恒为 229
+ * (Safari 与部分输入法不上报 isComposing,只能靠 keyCode)
+ * Ant Design 的 onPressEnter 不区分这两种回车,于是「拼音打完按回车选词」会连带
+ * 触发提交,用的还是候选词尚未上屏的半截文本,造成新建/重命名文件名写错。
+ */
+
+/** 判断键盘事件是否来自输入法组合输入过程 */
+export function isImeComposingKeyEvent(event) {
+ if (!event) return false
+ const nativeEvent = event.nativeEvent || event
+ if (nativeEvent && nativeEvent.isComposing) return true
+ const keyCode = event.keyCode !== undefined ? event.keyCode : nativeEvent && nativeEvent.keyCode
+ return keyCode === 229
+}
+
+/**
+ * 生成「回车安全提交」所需的一组属性,展开到 antd `` / `