104 lines
3.9 KiB
Swift
104 lines
3.9 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, after the pruning; the first 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 `firstPage`, which the next flush writes unless it is empty.
|
|
///
|
|
/// With `pruneAt`, the old and undated blocks are left out and the page file is written at once when one was.
|
|
/// - 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,
|
|
firstPage: @autoclosure () -> PageFile = WelcomeText.page(createdAt: Date()),
|
|
pruneAt now: Date? = nil
|
|
) 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)
|
|
}
|
|
let read = PageFile(text: text)
|
|
loaded = now.map { read.pruned(now: $0) } ?? read
|
|
if loaded != read {
|
|
do {
|
|
try write(Data(loaded.text().utf8), url)
|
|
} catch {
|
|
saveError = error.localizedDescription
|
|
isDirty = true
|
|
}
|
|
}
|
|
} else {
|
|
loaded = firstPage()
|
|
isDirty = !loaded.lines.isEmpty
|
|
}
|
|
}
|
|
|
|
/// 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)
|
|
}
|
|
}
|