Files
museion/Museion/PostStore.swift
T
AlexKucera f2953ee07e
CI / ci (push) Canceled after 0s
feat(editor): land editor core — open, edit, autosave (S1.2)
Posts open into the TextKit2 surface (ADR-0010 mode B) lifted from
the proven spike: styled source, scaled headings, dimmed syntax,
native undo/IME. One EditorSession per open post drives a ~1 s
debounced autosave (flush on selection change, window close, app
quit; ⌘S immediate), the Saved/Saving/Failed dot, and the per-post
.museion-state.json cursor sidecar that dies with the folder.
External edits raise an explicit Reload/Keep-Local alert — the
debounce never answers it for the writer, and drafts keep the
lazy-folder first-⌘S rule (#62).

Reviewer fanout fixes folded in: session teardown at every lifecycle
exit (rename flushes before the folder move; trash cancels the
debounce), draft ⌘S continues in place, conflict holds the debounce,
rescan's disk read off-main, ~35 lines of dead code out.

Closes #19
2026-10-05 10:56:33 +02:00

213 lines
9.3 KiB
Swift

//
// PostStore.swift
// Museion
//
// #18 (S1.1): the write side of the Post lifecycle — slug naming, lazy folder
// materialization on first write, frontmatter stamping (#59), Explicit Rename
// = retitle + move (#60), Trash delete. Pure disk operations, no UI state.
//
import Foundation
/// Write-side Post lifecycle (#18 map decisions #59/#60). One canonical write
/// path: every file that leaves here carries the flat frontmatter block the
/// #17 reader already parses.
nonisolated enum PostStore {
/// The shared slug function (#60): lowercase, diacritic-fold, strip
/// punctuation, whitespace runs → single hyphens, keep CJK, cap 80.
/// A slugless title (blank, punctuation-only) is `untitled` (CONTEXT.md).
static func slug(from title: String) -> String {
let folded = title
.folding(options: .diacriticInsensitive, locale: Locale(identifier: "en_US_POSIX"))
.lowercased()
var result = ""
var lastWasHyphen = true // swallows leading hyphens
for scalar in folded.unicodeScalars {
if CharacterSet.whitespacesAndNewlines.contains(scalar) {
if !lastWasHyphen {
result.append("-"); lastWasHyphen = true
}
} else if CharacterSet.alphanumerics.contains(scalar) {
result.unicodeScalars.append(scalar)
lastWasHyphen = false
}
// Everything else (punctuation, symbols) is dropped.
}
result = String(result.prefix(80))
while result.hasSuffix("-") {
result.removeLast()
}
return result.isEmpty ? "untitled" : result
}
/// First free slug for a title: base slug, then `-2`, `-3`… (#60).
/// Case-insensitive existence check (#60): enumerates `posts/` and
/// compares lowercased — independent of the volume's case sensitivity.
/// `excluding` skips a folder (the renamer's own, still present).
static func availableSlug(for title: String, in postsRoot: URL, excluding ownID: String? = nil) -> String {
let taken = Set(
((try? FileManager.default.contentsOfDirectory(atPath: postsRoot.path)) ?? [])
.map { $0.lowercased() },
)
let base = slug(from: title) // slug() is already lowercase
if !taken.contains(base) || base == ownID?.lowercased() {
return base
}
var suffix = 2
while taken.contains("\(base)-\(suffix)") {
suffix += 1
}
return "\(base)-\(suffix)"
}
/// First write (#62): lazily materialize `posts/<slug>/post.md` with the
/// #59 block stamped. Pass State First Draft, origin writer — the only
/// values #18 writes; the folder appears here, never on New Post.
static func writeNew(body: String, home: URL) throws -> Post {
let postsRoot = home.appendingPathComponent("posts", isDirectory: true)
try FileManager.default.createDirectory(at: postsRoot, withIntermediateDirectories: true)
let title = Post.title(of: body)
let id = availableSlug(for: title, in: postsRoot)
let dir = postsRoot.appendingPathComponent(id, isDirectory: true)
let fileURL = dir.appendingPathComponent("post.md")
// TOCTOU guard (audit): a folder appearing between slug pick and write
// must fail loudly, never clobber another post's content.
guard !FileManager.default.fileExists(atPath: fileURL.path) else {
throw CocoaError(.fileWriteFileExists)
}
do {
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
try stamped(body: body, passState: .firstDraft, origin: .writer)
.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
// Don't strand an empty slug folder on partial failure (it would
// occupy the slug and push the retry to -2).
if !FileManager.default.fileExists(atPath: fileURL.path) {
try? FileManager.default.removeItem(at: dir)
}
throw error
}
return Post(id: id, title: title, passState: .firstDraft, origin: .writer)
}
/// Save an existing Post: body-only text in, file normalized out. The
/// file's present `pass_state`/`origin` are preserved (origin immutable,
/// CONTEXT.md; bare corpus posts normalize on save, #59). A vanished
/// post throws — `writeNew` is the only creator; saving must never
/// resurrect a deleted post with reset metadata.
static func overwrite(id: String, body: String, home: URL) throws {
let fileURL = home.appendingPathComponent("posts/\(id)/post.md")
guard let existing = try? String(contentsOf: fileURL, encoding: .utf8) else {
throw CocoaError(.fileReadNoSuchFile)
}
let matter = Post.frontmatter(of: existing)
let passState = Post.PassState(rawValue: matter["pass_state"] ?? "") ?? .firstDraft
let origin = Post.Origin(rawValue: matter["origin"] ?? "") ?? .writer
try stamped(body: body, passState: passState, origin: origin)
.write(to: fileURL, atomically: true, encoding: .utf8)
}
/// Body text (frontmatter stripped) for editing; nil when unreadable.
/// Bare corpus posts return whole — they normalize on save (#59).
static func readBody(id: String, home: URL) -> String? {
let fileURL = home.appendingPathComponent("posts/\(id)/post.md")
guard let text = try? String(contentsOf: fileURL, encoding: .utf8) else { return nil }
return splitFrontmatter(text).body
}
// MARK: Cursor-state sidecar (#66)
/// Cursor state for one post: selection + scroll, `.museion-state.json`
/// in the post folder — Finder-invisible, human-diffable, dies with the
/// folder on Trash. Drafts skip it (#62).
struct CursorState: Codable, Equatable {
var selectionLocation: Int = 0
var selectionLength: Int = 0
var scrollOffset: Double = 0
}
private static func stateURL(id: String, home: URL) -> URL {
home.appendingPathComponent("posts/\(id)/.museion-state.json")
}
/// Read the sidecar; nil when absent or corrupt (a fresh cursor is fine).
static func readCursor(id: String, home: URL) -> CursorState? {
guard let data = try? Data(contentsOf: stateURL(id: id, home: home)) else { return nil }
return try? JSONDecoder().decode(CursorState.self, from: data)
}
/// Write the sidecar. Best-effort by design — a failed cursor write must
/// never read as a failed content save, so failures are swallowed here.
static func writeCursor(_ state: CursorState, id: String, home: URL) {
guard let data = try? JSONEncoder().encode(state) else { return }
try? data.write(to: stateURL(id: id, home: home), options: .atomic)
}
/// Explicit Rename (#60): rewrite the `# Title` line as the first
/// non-empty body line, then move the folder to the new slug. The file
/// stays `post.md`; a title that slugs to the current id only retitles.
static func rename(_ post: Post, to title: String, home: URL) throws -> Post {
let postsRoot = home.appendingPathComponent("posts", isDirectory: true)
let dir = postsRoot.appendingPathComponent(post.id, isDirectory: true)
let fileURL = dir.appendingPathComponent("post.md")
let text = try String(contentsOf: fileURL, encoding: .utf8)
let (block, body) = splitFrontmatter(text)
try (block + replacingTitleLine(of: body, with: "# \(title)"))
.write(to: fileURL, atomically: true, encoding: .utf8)
// availableSlug excludes our own (still-present) folder: a retitle
// whose slug matches the current id (any case) keeps the clean name
// (no -2 against ourselves); a genuine collision lands on -2 (#60).
let newID = availableSlug(for: title, in: postsRoot, excluding: post.id)
guard newID != post.id else {
return Post(id: post.id, title: title, passState: post.passState, origin: post.origin)
}
try FileManager.default.moveItem(at: dir, to: postsRoot.appendingPathComponent(newID, isDirectory: true))
return Post(id: newID, title: title, passState: post.passState, origin: post.origin)
}
/// Delete = move the Post folder to the Trash (recoverable in Finder) —
/// never permanent removal (#18 AC).
static func trash(_ post: Post, home: URL) throws {
var trashed: NSURL?
try FileManager.default.trashItem(
at: home.appendingPathComponent("posts/\(post.id)", isDirectory: true),
resultingItemURL: &trashed,
)
}
/// The #59 v1 block — flat keys, the exact shape the #17 reader parses.
static func stamped(body: String, passState: Post.PassState, origin: Post.Origin) -> String {
"---\npass_state: \(passState.rawValue)\norigin: \(origin.rawValue)\n---\n" + body
}
/// Splits a file into its verbatim frontmatter block (with both `---`
/// lines) and the body; no block → ("", whole text).
static func splitFrontmatter(_ text: String) -> (block: String, body: String) {
let all = text.split(separator: "\n", omittingEmptySubsequences: false)[...]
guard let open = all.firstIndex(where: { !$0.trimmed().isEmpty }),
all[open].trimmed() == "---",
let close = all[(open + 1)...].firstIndex(where: { $0.trimmed() == "---" })
else { return ("", text) }
let block = all[open ... close].joined(separator: "\n") + "\n"
return (block, all[(close + 1)...].joined(separator: "\n"))
}
/// Replace the body's Title heading with `line`; a body whose first
/// non-empty line is NOT a heading keeps that line (it's content) and
/// gets the heading inserted above it. An empty body becomes just `line`.
private static func replacingTitleLine(of body: String, with line: String) -> String {
var lines = body.split(separator: "\n", omittingEmptySubsequences: false)
if let titleIndex = lines.firstIndex(where: { !$0.trimmed().isEmpty }) {
if lines[titleIndex].trimmed().hasPrefix("#") {
lines[titleIndex] = Substring(line)
} else {
lines.insert(Substring(line), at: titleIndex)
}
} else {
lines = [Substring(line)]
}
return lines.joined(separator: "\n")
}
}