Skip to content

Commit

Permalink
fix: Don't save empty notes
Browse files Browse the repository at this point in the history
  • Loading branch information
jbmorley committed Jan 29, 2024
1 parent d4141ce commit 2a3a1dc
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
9 changes: 8 additions & 1 deletion Thoughts/Model/ComposeModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,14 @@ class ComposeModel: ObservableObject {
.debounce(for: .seconds(0.1), scheduler: DispatchQueue.main)
.sink { document in
do {
try document.save()
if document.isEmpty {
let fileManager = FileManager.default
if fileManager.fileExists(atPath: document.url.path) {
try fileManager.removeItem(at: document.url)
}
} else {
try document.save()
}
} catch {
self.error = error
}
Expand Down
13 changes: 8 additions & 5 deletions Thoughts/Model/Document.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,24 +29,27 @@ struct Document {
return "---\ndate: \(dateString)\n---\n\n"
}

static func url(for timestamp: Date) -> URL {
var date: Date
var content: String

var url: URL {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd-HH-mm-ss"
formatter.timeZone = .gmt
let filename = formatter.string(from: timestamp)
let filename = formatter.string(from: date)
return ApplicationModel.folderURL.appendingPathComponent(filename).appendingPathExtension("md")
}

var date: Date
var content: String
var isEmpty: Bool {
return content.isEmpty
}

init(date: Date = Date()) {
self.date = date
self.content = ""
}

func save() throws {
let url = Self.url(for: date)
let content = Self.header(for: date) + self.content
try content.write(to: url, atomically: true, encoding: .utf8)
}
Expand Down

0 comments on commit 2a3a1dc

Please sign in to comment.