restores Helder in all its glory
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
import Foundation
|
||||
import HelderServices
|
||||
import Observation
|
||||
|
||||
@Observable
|
||||
@MainActor
|
||||
public final class NoteStore {
|
||||
public static let fileName = NotesService.fileName
|
||||
|
||||
public var text = ""
|
||||
/// What is on disk, so a save without edits does not touch the file and wake the watcher.
|
||||
public private(set) var savedText = ""
|
||||
|
||||
/// Raises a toast; the model wires it to `ToastStore`.
|
||||
@ObservationIgnored public var notify: ((String, String?) -> Void)?
|
||||
@ObservationIgnored private let notes: NotesServicing
|
||||
|
||||
public init(notes: NotesServicing) {
|
||||
self.notes = notes
|
||||
}
|
||||
|
||||
public var isDirty: Bool { text != savedText }
|
||||
|
||||
public var characterCount: Int { text.count }
|
||||
|
||||
public func load() async {
|
||||
let loaded = await notes.read()
|
||||
text = loaded
|
||||
savedText = loaded
|
||||
}
|
||||
|
||||
/// Picks up an outside edit of the note file; unsaved typing always wins.
|
||||
public func reloadIfClean() async {
|
||||
guard !isDirty else { return }
|
||||
let loaded = await notes.read()
|
||||
guard !isDirty, loaded != savedText else { return }
|
||||
text = loaded
|
||||
savedText = loaded
|
||||
}
|
||||
|
||||
/// Saves when the text changed; called on window blur, on close and when the overlay closes.
|
||||
/// Returns false when the write failed.
|
||||
@discardableResult
|
||||
public func save() async -> Bool {
|
||||
guard isDirty else { return true }
|
||||
let snapshot = text
|
||||
// Marked saved before the write, so a second blur during the write does not write again.
|
||||
let previous = savedText
|
||||
savedText = snapshot
|
||||
do {
|
||||
try await notes.write(snapshot)
|
||||
return true
|
||||
} catch {
|
||||
if savedText == snapshot { savedText = previous }
|
||||
Log.error("notes", "save failed: \(error.localizedDescription)")
|
||||
notify?("Save failed", Self.fileName)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// The trimmed note for ⌘P, or nil when it is empty.
|
||||
public var passableText: String? {
|
||||
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return trimmed.isEmpty ? nil : trimmed
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user