diff --git a/app/pages/page.tsx b/app/pages/page.tsx index 29954d5..a7814fc 100644 --- a/app/pages/page.tsx +++ b/app/pages/page.tsx @@ -547,8 +547,37 @@ export default function CarnetPage() { } } } else { - // For other folders, use existing id or construct from title - fileKey = note.id || (noteTitle ? `user-${session?.user?.id}/${selectedFolder.toLowerCase()}/${noteTitle}${noteTitle.endsWith('.md') ? '' : '.md'}` : undefined); + // For other folders (Bloc-notes), check if a note with the same title already exists + // This prevents duplicates when creating new notes + if (!note.id || note.id.startsWith('temp-')) { + // This is a new note (no id or temporary id), check for duplicates + const sanitizedTitle = noteTitle ? noteTitle.replace(/[^a-zA-Z0-9._-]/g, '_') : 'Untitled'; + const expectedFileKey = `user-${session?.user?.id}/${selectedFolder.toLowerCase()}/${sanitizedTitle}${sanitizedTitle.endsWith('.md') ? '' : '.md'}`; + + // Check if a note with this title already exists + const existingNote = notes.find(n => { + const nTitle = n.title || ''; + const nId = n.id || ''; + // Check if title matches or if the id matches the expected fileKey + return (nTitle === noteTitle && noteTitle !== '') || + (noteTitle === '' && (nTitle === 'Untitled' || nTitle === '' || nTitle.trim() === '')) || + nId === expectedFileKey; + }); + + if (existingNote) { + // Update the existing note instead of creating a new one + console.log(`[handleSaveNote] Found existing note with same title "${noteTitle}", updating: ${existingNote.id}`); + note.id = existingNote.id; + noteTitle = existingNote.title || noteTitle || 'Untitled'; + fileKey = existingNote.id; + } else { + // No existing note found, use the expected fileKey + fileKey = expectedFileKey; + } + } else { + // Note has an id, use it (this is an update to an existing note) + fileKey = note.id; + } } if (!fileKey) { @@ -861,7 +890,10 @@ export default function CarnetPage() { setShowNotes(false); } } else { - // For other folders (Bloc-notes), check if "Untitled" already exists + // For other folders (Bloc-notes), refresh notes list first + await fetchNotes(true); + + // Check if "Untitled" already exists const untitledNote = notes.find(note => { const title = note.title || ''; return title === 'Untitled' || title === '' || title.trim() === ''; @@ -874,9 +906,11 @@ export default function CarnetPage() { return; } - // Create a blank note + // Create a blank note with a temporary unique id to track it + // This id will be used in handleSaveNote to check for duplicates + const tempId = `temp-${Date.now()}`; setSelectedNote({ - id: '', + id: tempId, // Temporary id to track this new note title: '', content: '', lastModified: new Date().toISOString(),