Files
museion/Museion/PostsModel.swift
T
AlexKucera 530f852f75
CI / ci (push) Canceled after 0s
feat(workspace): land Post lifecycle (S1.1)
Posts become writable end to end per the #18 map decisions:
New Post holds an in-memory draft (folder appears only on first
save), first save stamps the flat frontmatter block the #17
reader already parses (pass_state First Draft, origin writer,
immutable after stamping), and the Post ID is the Title slug with
case-insensitive collision suffixes. Explicit Rename retitles the
# Title line and moves the folder (post.md stays); Delete goes to
Trash. A recursive FSEvents stream keeps the list mirroring
posts/ — external Finder edits included.

Editor is a deliberate TextEditor stub; #19's TextKit2 editor
replaces it in place while the lifecycle machinery below the view
survives the swap.

Two review rounds (standards/spec + finish-audit fanout) fixed:
watcher start-order bug, writeNew clobber race, overwrite
resurrecting vanished posts with reset origin, rename destroying
non-heading first lines, draft hijacking the editor, debounce
starvation under churn.

Tests: 75/75 (17 new). Closes #18.
2026-10-03 13:34:00 +02:00

210 lines
6.4 KiB
Swift

//
// PostsModel.swift
// Museion
//
// #18 (S1.1): the Posts pane's write side — FSEvents watcher on posts/ with
// a ~0.5 s debounced rescan (#61), selection, and the New Post draft
// lifecycle (#62). Own ops route through the same rescan: one path.
//
import CoreServices
import Foundation
import Observation
/// The New Post draft: body text only, no folder until first save (#62).
struct PostDraft {
var text = "# Untitled\n\n"
}
/// Recursive FSEvents stream on one directory (#61): file-level events, so
/// nested `posts/<id>/post.md` edits from Finder fire too — a plain dir-FD
/// dispatch source only sees direct children and misses them.
final nonisolated class PostsWatcher: @unchecked Sendable {
/// Fired on the main actor when anything under the watched path changes.
var onEvent: (@MainActor @Sendable () -> Void)?
private var stream: FSEventStreamRef?
func start(url: URL) {
stop()
var context = FSEventStreamContext(
version: 0,
info: Unmanaged.passUnretained(self).toOpaque(),
retain: nil,
release: nil,
copyDescription: nil,
)
// C function pointer — no captures; `self` rides the info pointer.
let callback: FSEventStreamCallback = { _, info, _, _, _, _ in
let watcher = Unmanaged<PostsWatcher>.fromOpaque(info!).takeUnretainedValue()
Task { @MainActor in watcher.onEvent?() }
}
guard let stream = FSEventStreamCreate(
kCFAllocatorDefault,
callback,
&context,
[url.path] as CFArray,
FSEventStreamEventId(kFSEventStreamEventIdSinceNow),
0.5, // seconds; FSEvents coalesces within this latency (the #61 window)
FSEventStreamCreateFlags(kFSEventStreamCreateFlagFileEvents),
) else { return }
FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
FSEventStreamStart(stream)
self.stream = stream
}
func stop() {
guard let stream else { return }
FSEventStreamStop(stream)
FSEventStreamInvalidate(stream)
FSEventStreamRelease(stream)
self.stream = nil
}
deinit { stop() }
}
/// App-scoped Posts state (@MainActor @Observable, the AppGateState pattern).
/// The watcher runs while the workspace is open (app-scoped, #61).
@MainActor
@Observable
final class PostsModel {
/// The scanned, title-sorted list — mirrors `posts/` at all times.
private(set) var posts: [Post] = []
/// The selected Post's id; nil = nothing selected (empty editor).
private(set) var selectedPostID: String?
/// The in-memory draft for New Post (#62): no folder until first save.
private(set) var draft: PostDraft?
/// Last failed-op message surfaced in the editor (nil = clean).
private(set) var lastError: String?
/// Home the watcher is bound to; also the rescan target.
private var watchedHome: URL?
private var watcher = PostsWatcher()
/// Bind a Home: ensure `posts/` exists (FSEvents on a missing path is
/// unreliable; the AC's lazy rule is about post folders, not this root),
/// initial scan + start (or restart) the watcher. Called from
/// `.task(id: home)` — re-fires on Home repoint.
func bind(home: URL) {
startWatching(home: home)
Task { await rescan() }
}
// MARK: Watcher (#61)
private func startWatching(home: URL) {
guard watchedHome != home else { return }
watchedHome = home
try? FileManager.default.createDirectory(
at: home.appendingPathComponent("posts", isDirectory: true),
withIntermediateDirectories: true,
)
watcher.onEvent = { [weak self] in Task { await self?.rescan() } }
watcher.start(url: home.appendingPathComponent("posts", isDirectory: true))
}
/// Off-main scan; keeps selection valid across the fresh refresh.
/// FSEvents already coalesces bursts within its 0.5 s latency window —
/// no second debounce on top.
private func rescan() async {
guard let home = watchedHome else { return }
let scanned = await Task.detached(priority: .userInitiated) { Post.scan(home: home) }.value
guard !Task.isCancelled else { return }
posts = scanned
if let id = selectedPostID, !posts.contains(where: { $0.id == id }) {
selectedPostID = nil // the post vanished (deleted in Finder or here)
}
}
// MARK: Own ops (route through the same rescan, #61)
// ponytail: the PostStore calls here run on MainActor — small single-file
// writes and same-volume moves; if a big Home ever stalls the UI, wrap
// them in Task.detached like rescan.
/// Tear the watcher down on the main actor (its scheduling thread) —
/// deinit of a @MainActor-held object may run elsewhere.
func shutdown() {
watcher.stop()
}
/// New Post (#62): fresh in-memory draft, no folder, editor takes it.
func newPost() {
draft = PostDraft()
selectedPostID = nil
}
/// First save of the draft (#62): lazy folder, slug, #59 stamp all fire
/// here. Rescans immediately (the watcher would too, after its window).
func saveDraft(home: URL) {
guard let draft else { return }
do {
let post = try PostStore.writeNew(body: draft.text, home: home)
self.draft = nil
selectedPostID = post.id
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
/// Save an edited body for the selected post (preserves its frontmatter).
func saveSelected(body: String, home: URL) {
guard let id = selectedPostID else { return }
do {
try PostStore.overwrite(id: id, body: body, home: home)
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
/// Select a Post; selecting anything abandons an unsaved draft (the
/// draft otherwise hijacks the editor — its only exits are save or
/// selecting away).
func select(_ id: String) {
draft = nil
selectedPostID = id
}
/// Draft typing from the editor stub (private(set) barrier).
func updateDraft(_ text: String) {
draft?.text = text
}
/// Explicit Rename = retitle + move (#60). Sets lastError on failure.
func rename(_ post: Post, to title: String, home: URL) {
do {
let moved = try PostStore.rename(post, to: title, home: home)
if selectedPostID == post.id {
selectedPostID = moved.id
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
/// Delete a Post (Trash, recoverable — #18 AC). Clears selection if it
/// was the post.
func trash(_ post: Post, home: URL) {
do {
try PostStore.trash(post, home: home)
if selectedPostID == post.id {
selectedPostID = nil
}
lastError = nil
Task { await rescan() }
} catch {
lastError = error.localizedDescription
}
}
}