修复编辑模式下的三个交互问题
1. 中文输入法回车误提交:新建文件/文件夹、重命名的回车提交不再吃掉 输入法组合中的回车(isComposing / keyCode 229),拼音选词不会再把 半截文本当成文件名创建出去。聊天输入框与搜索框同样存在该问题, 一并改用新的 useImeSafeEnter,并保留原有 Ctrl/Cmd+Enter 发送。 2. 重命名不允许再改动文件类型:输入框只暴露主名,后缀作为固定后缀 展示并在提交时强制拼回,误删后缀导致文件无法浏览/预览的情况不再 出现;目录名整体视为名称(v1.2.0 这类目录不按点切分)。同时补上 路径分隔符校验、重名校验、重复提交保护,重命名成功后编辑器与地址栏 跟随到新路径(改文件夹时视图也不再空白),不再清空正在编辑的文档。 3. 宽屏下编辑器两侧留白:ByteMD 把编辑区正文锁死在 800px 居中, 「仅编辑区」在大屏上左右各空一大片。现编辑区按可用宽度铺满, 预览区保留可读行长但放宽到 1100px 以内。main
parent
f1ba8949f6
commit
0d66d78e50
|
|
@ -17,6 +17,7 @@ import {
|
|||
Typography,
|
||||
} from 'antd'
|
||||
import Toast from '@/components/Toast/Toast'
|
||||
import { useImeSafeEnter } from '@/utils/ime'
|
||||
import {
|
||||
FolderOutlined,
|
||||
EditOutlined,
|
||||
|
|
@ -1032,6 +1033,12 @@ function Chat() {
|
|||
}
|
||||
}
|
||||
|
||||
// 输入框/文本域的回车提交:输入法组合中的回车留给输入法选词,
|
||||
// 避免「拼音打完按回车选词」把还没上屏的半截文本直接发送或搜索出去
|
||||
const composerImeSubmit = useImeSafeEnter(handleSend, { allowCtrlMeta: true })
|
||||
const newSessionImeSubmit = useImeSafeEnter(handleCreateSession, { allowCtrlMeta: true })
|
||||
const searchImeSubmit = useImeSafeEnter(handleSearch)
|
||||
|
||||
const handleSelectSearchResult = async (item) => {
|
||||
setSearchVisible(false)
|
||||
await openSession(item.session_id, { message_id: item.message_id })
|
||||
|
|
@ -1361,12 +1368,7 @@ function Chat() {
|
|||
onChange={(e) => setInputValue(e.target.value)}
|
||||
autoSize={{ minRows: 1, maxRows: 8 }}
|
||||
placeholder="随心输入"
|
||||
onPressEnter={(e) => {
|
||||
if (!e.shiftKey) {
|
||||
e.preventDefault()
|
||||
handleSend()
|
||||
}
|
||||
}}
|
||||
{...composerImeSubmit}
|
||||
/>
|
||||
<div className="chat-composer-actions">
|
||||
<div className="chat-composer-left">
|
||||
|
|
@ -1448,12 +1450,7 @@ function Chat() {
|
|||
autoFocus
|
||||
autoSize={{ minRows: 2, maxRows: 10 }}
|
||||
placeholder="随心输入"
|
||||
onPressEnter={(e) => {
|
||||
if (!e.shiftKey) {
|
||||
e.preventDefault()
|
||||
handleCreateSession()
|
||||
}
|
||||
}}
|
||||
{...newSessionImeSubmit}
|
||||
/>
|
||||
<div className="chat-composer-actions">
|
||||
<div className="chat-composer-left">
|
||||
|
|
@ -1567,7 +1564,7 @@ function Chat() {
|
|||
onChange={handleSearchKeywordChange}
|
||||
placeholder="输入聊天关键词,仅搜索对话内容"
|
||||
allowClear
|
||||
onPressEnter={handleSearch}
|
||||
{...searchImeSubmit}
|
||||
/>
|
||||
<Button type="primary" icon={<SearchOutlined />} loading={searchLoading} onClick={handleSearch}>
|
||||
搜索
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<div
|
||||
key={file.key}
|
||||
|
|
@ -1695,23 +1797,39 @@ function DocumentEditor() {
|
|||
: '重命名'
|
||||
}
|
||||
open={modalVisible}
|
||||
// 弹窗每次打开都重建内容,避免上一次的名称残留
|
||||
destroyOnHidden
|
||||
// Input 自带的 autoFocus 会被 rc-dialog 抢走(动效结束时它会把焦点收进对话框容器),
|
||||
// 所以等动效结束再把焦点交回名称输入框,实测这样点开就能直接打字
|
||||
afterOpenChange={(open) => {
|
||||
if (open) nameInputRef.current?.focus()
|
||||
}}
|
||||
onOk={handleOperation}
|
||||
onCancel={() => {
|
||||
setModalVisible(false)
|
||||
setNewName('')
|
||||
setLockedExtension('')
|
||||
setRightClickNode(null)
|
||||
}}
|
||||
>
|
||||
<Input
|
||||
ref={nameInputRef}
|
||||
placeholder={
|
||||
operationType === 'create_file' ? '文件名(如:新文档.md)' :
|
||||
operationType === 'create_dir' ? '文件夹名' :
|
||||
'新名称'
|
||||
'仅名称(不含后缀)'
|
||||
}
|
||||
value={newName}
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
onPressEnter={handleOperation}
|
||||
addonAfter={operationType === 'rename' ? lockedExtension || null : null}
|
||||
{...nameInputImeSubmit}
|
||||
/>
|
||||
{operationType === 'rename' && lockedExtension && (
|
||||
<div className="modal-field-hint">后缀 <code>{lockedExtension}</code> 由文件类型决定,已锁定,重命名不会改动它</div>
|
||||
)}
|
||||
{operationType === 'create_file' && (
|
||||
<div className="modal-field-hint">不写后缀时默认创建 Markdown 文档(.md)</div>
|
||||
)}
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
|
|
|
|||
|
|
@ -0,0 +1,45 @@
|
|||
/**
|
||||
* 文件名拆分与校验工具。
|
||||
*
|
||||
* 产品约定:重命名只允许改「名字」,不允许改「文件类型(后缀)」。
|
||||
* 后缀一旦被人手改坏(例如误删 `.md`),文件在项目里就打不开也预览不了,
|
||||
* 所以把主名和后缀拆开,输入框只暴露主名,后缀作为固定后缀展示。
|
||||
*/
|
||||
|
||||
/**
|
||||
* 把文件名拆成可编辑主名与固定后缀:
|
||||
* 'intro.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, '')
|
||||
}
|
||||
|
|
@ -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 `<Input>` / `<TextArea>` 上即可:
|
||||
*
|
||||
* const enterSubmit = useImeSafeEnter(handleOk)
|
||||
* <Input {...enterSubmit} />
|
||||
*
|
||||
* 用来取代 `onPressEnter={handleOk}`。组合状态额外用 ref 兜一层:
|
||||
* 少数输入法在 keydown 时既不带 isComposing 也不带 keyCode 229,
|
||||
* 自己记录 compositionstart/end 才靠得住。
|
||||
*
|
||||
* allowCtrlMeta:聊天输入框这类「Shift+Enter 换行、Ctrl/Cmd+Enter 也发送」的场景传 true,
|
||||
* 保留组合键提交的旧行为;表单里只需要纯回车提交,保持默认 false 即可。
|
||||
*/
|
||||
export function useImeSafeEnter(onEnter, { allowCtrlMeta = false } = {}) {
|
||||
const composingRef = useRef(false)
|
||||
|
||||
const handleKeyDown = useCallback((event) => {
|
||||
if (event.key !== 'Enter' || event.shiftKey) return
|
||||
if (!allowCtrlMeta && (event.ctrlKey || event.altKey || event.metaKey)) return
|
||||
if (composingRef.current || isImeComposingKeyEvent(event)) {
|
||||
// 这是输入法用来上屏的回车,原样交回输入法,不触发提交
|
||||
return
|
||||
}
|
||||
event.preventDefault()
|
||||
onEnter?.(event)
|
||||
}, [onEnter, allowCtrlMeta])
|
||||
|
||||
return {
|
||||
onCompositionStart: () => {
|
||||
composingRef.current = true
|
||||
},
|
||||
onCompositionEnd: () => {
|
||||
composingRef.current = false
|
||||
},
|
||||
// 输入法被切换或输入框失焦时可能收不到 compositionend,避免状态卡在「组合中」
|
||||
onBlur: () => {
|
||||
composingRef.current = false
|
||||
},
|
||||
onKeyDown: handleKeyDown,
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue