'use client'; import { useState, useEffect } from 'react'; import { Box, TextField, Typography, IconButton, Tooltip, Collapse } from '@mui/material'; import EditIcon from '@mui/icons-material/Edit'; import SaveIcon from '@mui/icons-material/Save'; import CancelIcon from '@mui/icons-material/Cancel'; import NotesIcon from '@mui/icons-material/Notes'; import { useTranslation } from 'react-i18next'; /** * 备注输入组件 */ export default function NoteInput({ value = '', onChange, placeholder, readOnly = false, maxLength = 500, minRows = 3, maxRows = 6 }) { const { t } = useTranslation(); const [isEditing, setIsEditing] = useState(false); const [noteValue, setNoteValue] = useState(value); const [tempValue, setTempValue] = useState(value); // 同步外部value变化 useEffect(() => { setNoteValue(value); setTempValue(value); }, [value]); // 开始编辑 const handleStartEdit = () => { setIsEditing(true); setTempValue(noteValue); }; // 保存备注 const handleSave = () => { setNoteValue(tempValue); setIsEditing(false); if (onChange) { onChange(tempValue); } }; // 取消编辑 const handleCancel = () => { setTempValue(noteValue); setIsEditing(false); }; // 处理键盘快捷键 const handleKeyDown = event => { if (event.ctrlKey || event.metaKey) { if (event.key === 'Enter') { event.preventDefault(); handleSave(); } else if (event.key === 'Escape') { event.preventDefault(); handleCancel(); } } }; if (readOnly) { return ( {t('datasets.note', '备注')} {noteValue ? ( {noteValue} ) : ( {t('datasets.noNote', '暂无备注')} )} ); } return ( {/* 标题和操作按钮 */} {t('datasets.note', '备注')} {noteValue && !isEditing && ( ({noteValue.length} / {maxLength}) )} {!isEditing && ( )} {/* 显示模式 */} {noteValue ? ( {noteValue} ) : ( {placeholder || t('datasets.clickToAddNote', '点击添加备注...')} )} {/* 编辑模式 */} setTempValue(e.target.value)} onKeyDown={handleKeyDown} placeholder={placeholder || t('datasets.enterNote', '请输入备注...')} inputProps={{ maxLength }} helperText={ {t('datasets.noteShortcuts', 'Ctrl+Enter 保存,Esc 取消')} maxLength * 0.9 ? 'warning.main' : 'text.secondary'} > {tempValue.length} / {maxLength} } sx={{ mb: 1 }} /> maxLength}> ); }