Save note content when editor disappears

Extract persistNote() from saveNote() to allow saving without closing
  the editor. Call persistNote() from onDisappear (when notch retracts)
  and cancelEdit() so user changes are never silently discarded.
  Empty new notes (no title, no content, no image) are skipped.
This commit is contained in:
SSylvain1989 2026-03-03 21:27:46 +01:00
commit c385eae0c7

View file

@ -102,6 +102,9 @@ struct NotchNotesView: View {
updateLayoutState() updateLayoutState()
} }
.onDisappear { .onDisappear {
if isEditingNewNote || selectedNoteId != nil {
persistNote()
}
coordinator.notesLayoutState = .list coordinator.notesLayoutState = .list
} }
.onChange(of: isEditingNewNote) { _, _ in .onChange(of: isEditingNewNote) { _, _ in
@ -197,12 +200,17 @@ struct NotchNotesView: View {
isEditingNewNote = false isEditingNewNote = false
} }
private func saveNote() { private func persistNote() {
guard let id = editorNoteId else { return }
let isExistingNote = savedNotes.contains(where: { $0.id == id })
if !isExistingNote && editorTitle.isEmpty && editorContent.isEmpty && editorImageData == nil {
return
}
var notes = savedNotes var notes = savedNotes
let now = Date() let now = Date()
if let id = editorNoteId {
// Priority: Save image to disk if it exists
var fileName: String? = nil var fileName: String? = nil
if let data = editorImageData { if let data = editorImageData {
let name = "note_image_\(id.uuidString).png" let name = "note_image_\(id.uuidString).png"
@ -213,7 +221,6 @@ struct NotchNotesView: View {
if let index = notes.firstIndex(where: { $0.id == id }) { if let index = notes.firstIndex(where: { $0.id == id }) {
// Update // Update
// If there was an old image and it's being replaced or removed, delete old file
if let oldFileName = notes[index].imageFileName, oldFileName != fileName { if let oldFileName = notes[index].imageFileName, oldFileName != fileName {
let oldFileURL = NoteItem.noteImageDataDirectory.appendingPathComponent(oldFileName) let oldFileURL = NoteItem.noteImageDataDirectory.appendingPathComponent(oldFileName)
try? FileManager.default.removeItem(at: oldFileURL) try? FileManager.default.removeItem(at: oldFileURL)
@ -236,9 +243,12 @@ struct NotchNotesView: View {
) )
notes.insert(newNote, at: 0) notes.insert(newNote, at: 0)
} }
savedNotes = notes // Persistence fix: save back to @Default
savedNotes = notes
} }
private func saveNote() {
persistNote()
closeEditor() closeEditor()
} }
@ -311,6 +321,7 @@ struct NotchNotesView: View {
} }
private func cancelEdit() { private func cancelEdit() {
persistNote()
closeEditor() closeEditor()
} }