From e6ecab13fa80ee21f01de947b71ae2a8221e79fe Mon Sep 17 00:00:00 2001 From: drelich Date: Tue, 17 Mar 2026 09:19:03 +0100 Subject: [PATCH] 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 --- src/components/NoteEditor.tsx | 49 +++++++++++++++++++++-------------- 1 file changed, 30 insertions(+), 19 deletions(-) diff --git a/src/components/NoteEditor.tsx b/src/components/NoteEditor.tsx index 011b20c..c61a1ed 100644 --- a/src/components/NoteEditor.tsx +++ b/src/components/NoteEditor.tsx @@ -53,26 +53,37 @@ export function NoteEditor({ note, onUpdateNote, fontSize }: NoteEditorProps) { }); 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) { - handleSave(); - } - - 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); + // Save if there are unsaved changes + if (hasUnsavedChanges && editor) { + handleSave(); + } + // Load new note after a brief delay to ensure save completes + setTimeout(loadNewNote, 100); + } else { + // First load or same note, load immediately + loadNewNote(); } }, [note?.id, editor]);