Fix note switching to save unsaved changes before loading new note

- Added loadNewNote helper function to encapsulate note loading logic
- Check for unsaved changes when switching notes
- Save previous note if it has unsaved changes
- Add 100ms delay before loading new note to ensure save completes
- Prevents data loss when switching from unsaved note to another note
- Fixes bug where new note content would overwrite unsaved changes
This commit is contained in:
drelich
2026-03-17 09:19:03 +01:00
parent 489f2f847d
commit e6ecab13fa

View File

@@ -53,26 +53,37 @@ export function NoteEditor({ note, onUpdateNote, fontSize }: NoteEditorProps) {
}); });
useEffect(() => { useEffect(() => {
const loadNewNote = () => {
if (note && editor) {
setLocalTitle(note.title);
setLocalFavorite(note.favorite);
setHasUnsavedChanges(false);
// Only reset titleManuallyEdited when switching to a different note
// Check if the current title matches the first line of content
const firstLine = note.content.split('\n')[0].replace(/^#+\s*/, '').trim();
const titleMatchesFirstLine = note.title === firstLine || note.title === firstLine.substring(0, 50);
setTitleManuallyEdited(!titleMatchesFirstLine);
previousNoteIdRef.current = note.id;
// Convert markdown to HTML using marked library
const html = marked.parse(note.content || '', { async: false }) as string;
editor.commands.setContent(html);
}
};
// If switching notes, save the previous note first
if (previousNoteIdRef.current !== null && previousNoteIdRef.current !== note?.id) { if (previousNoteIdRef.current !== null && previousNoteIdRef.current !== note?.id) {
handleSave(); // Save if there are unsaved changes
} if (hasUnsavedChanges && editor) {
handleSave();
if (note && editor) { }
setLocalTitle(note.title); // Load new note after a brief delay to ensure save completes
setLocalFavorite(note.favorite); setTimeout(loadNewNote, 100);
setHasUnsavedChanges(false); } else {
// First load or same note, load immediately
// Only reset titleManuallyEdited when switching to a different note loadNewNote();
// Check if the current title matches the first line of content
const firstLine = note.content.split('\n')[0].replace(/^#+\s*/, '').trim();
const titleMatchesFirstLine = note.title === firstLine || note.title === firstLine.substring(0, 50);
setTitleManuallyEdited(!titleMatchesFirstLine);
previousNoteIdRef.current = note.id;
// Convert markdown to HTML using marked library
const html = marked.parse(note.content || '', { async: false }) as string;
editor.commands.setContent(html);
} }
}, [note?.id, editor]); }, [note?.id, editor]);