90 lines
3.2 KiB
Swift
90 lines
3.2 KiB
Swift
import Foundation
|
|
import Observation
|
|
import PlakCore
|
|
|
|
public enum PageStoreError: Error, Equatable {
|
|
/// The page file exists but cannot be read as UTF-8; saving over it would lose the page.
|
|
case unreadable(path: String)
|
|
}
|
|
|
|
/// Reads the page file at launch and keeps it in step with the page.
|
|
///
|
|
/// Every `changed()` schedules one save after the debounce; a failed save keeps the page in
|
|
/// memory, sets `saveError`, and is tried again on the next change or `flush()`.
|
|
@MainActor
|
|
@Observable
|
|
public final class PageStore {
|
|
public nonisolated static var defaultURL: URL {
|
|
FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
|
|
.appendingPathComponent("plak", isDirectory: true)
|
|
.appendingPathComponent("page.md")
|
|
}
|
|
|
|
/// The page file as read at launch; an empty page when there was no file.
|
|
public let loaded: PageFile
|
|
|
|
/// Makes the page file text when a save runs, so a keystroke costs no conversion; nil writes nothing.
|
|
@ObservationIgnored public var contents: () -> String? = { nil }
|
|
|
|
/// The message of the last failed save; nil once a save succeeds.
|
|
public private(set) var saveError: String?
|
|
|
|
public let url: URL
|
|
private let debounce: Duration
|
|
private let write: @Sendable (Data, URL) throws -> Void
|
|
@ObservationIgnored private var pending: Task<Void, Never>?
|
|
@ObservationIgnored private var isDirty = false
|
|
|
|
/// Reads the page file; a missing file gives an empty page.
|
|
/// - Throws: `PageStoreError.unreadable` when the file exists but cannot be read.
|
|
public init(
|
|
url: URL = PageStore.defaultURL,
|
|
debounce: Duration = .milliseconds(500),
|
|
write: @escaping @Sendable (Data, URL) throws -> Void = PageStore.writeAtomically
|
|
) throws {
|
|
self.url = url
|
|
self.debounce = debounce
|
|
self.write = write
|
|
if FileManager.default.fileExists(atPath: url.path) {
|
|
guard let data = try? Data(contentsOf: url), let text = String(data: data, encoding: .utf8) else {
|
|
throw PageStoreError.unreadable(path: url.path)
|
|
}
|
|
loaded = PageFile(text: text)
|
|
} else {
|
|
loaded = PageFile()
|
|
}
|
|
}
|
|
|
|
/// Marks the page as changed; the save follows after the debounce.
|
|
public func changed() {
|
|
isDirty = true
|
|
pending?.cancel()
|
|
let delay = debounce
|
|
pending = Task { [weak self] in
|
|
try? await Task.sleep(for: delay)
|
|
guard !Task.isCancelled else { return }
|
|
self?.flush()
|
|
}
|
|
}
|
|
|
|
/// Writes a pending change now, as on quit.
|
|
public func flush() {
|
|
pending?.cancel()
|
|
pending = nil
|
|
guard isDirty, let text = contents() else { return }
|
|
do {
|
|
try write(Data(text.utf8), url)
|
|
isDirty = false
|
|
saveError = nil
|
|
} catch {
|
|
saveError = error.localizedDescription
|
|
}
|
|
}
|
|
|
|
/// Creates the folder when needed and replaces the file in one step.
|
|
public nonisolated static func writeAtomically(_ data: Data, to url: URL) throws {
|
|
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
|
try data.write(to: url, options: .atomic)
|
|
}
|
|
}
|