import React, { useEffect, useRef, useState } from 'react'; import { useNotebookStore } from '@/store/notebookStore'; import { useTranslation } from '@/hooks/useTranslation'; import { useResponsiveSize } from '@/hooks/useResponsiveSize'; import { TextSelection } from '@/utils/sel'; import { md5Fingerprint } from '@/utils/md5'; import { BookNote } from '@/types/book'; import useShortcuts from '@/hooks/useShortcuts'; import TextEditor, { TextEditorRef } from '@/components/TextEditor'; import TextButton from '@/components/TextButton'; interface NoteEditorProps { onSave: (selection: TextSelection, note: string) => void; onEdit: (annotation: BookNote) => void; } const NoteEditor: React.FC = ({ onSave, onEdit }) => { const _ = useTranslation(); const { notebookNewAnnotation, notebookEditAnnotation, setNotebookNewAnnotation, setNotebookEditAnnotation, saveNotebookAnnotationDraft, getNotebookAnnotationDraft, } = useNotebookStore(); const editorRef = useRef(null); const [note, setNote] = useState(''); const separatorWidth = useResponsiveSize(3); useEffect(() => { if (notebookEditAnnotation) { const noteText = notebookEditAnnotation.note; setNote(noteText); editorRef.current?.setValue(noteText); editorRef.current?.focus(); } else if (notebookNewAnnotation) { const noteText = getAnnotationText(); if (noteText) { const draftNote = getNotebookAnnotationDraft(md5Fingerprint(noteText)) || ''; setNote(draftNote); editorRef.current?.setValue(draftNote); editorRef.current?.focus(); } } // eslint-disable-next-line react-hooks/exhaustive-deps }, [notebookNewAnnotation, notebookEditAnnotation]); const getAnnotationText = () => { return notebookEditAnnotation?.text || notebookNewAnnotation?.text || ''; }; const handleNoteChange = (value: string) => { setNote(value); }; const handleBlur = () => { const currentValue = editorRef.current?.getValue(); if (currentValue) { const noteText = getAnnotationText(); if (noteText) { saveNotebookAnnotationDraft(md5Fingerprint(noteText), currentValue); } } }; const handleSaveNote = () => { const currentValue = editorRef.current?.getValue(); if (currentValue) { if (notebookNewAnnotation) { onSave(notebookNewAnnotation, currentValue); } else if (notebookEditAnnotation) { notebookEditAnnotation.note = currentValue; onEdit(notebookEditAnnotation); } } }; const handleEscape = () => { if (notebookNewAnnotation) { setNotebookNewAnnotation(null); } if (notebookEditAnnotation) { setNotebookEditAnnotation(null); } }; useShortcuts({ onSaveNote: () => { const currentValue = editorRef.current?.getValue(); if (currentValue) { handleSaveNote(); } }, onEscape: handleEscape, }); const canSave = Boolean(note.trim()); return (
{getAnnotationText()}
{_('Cancel')} {_('Save')}
); }; export default NoteEditor;