feat(editor): land editor core — open, edit, autosave (S1.2)
CI / ci (push) Canceled after 0s

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
This commit is contained in:
AlexKucera committed 2026-10-05 10:56:33 +02:00
1 parent 530f852f75
commit f2953ee07e
13 files changed
+893 -87

No files matched your search

+3 -3
View File
@@ -21,11 +21,11 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- `DesignTokens.swift` — palette/geometry from the design contract (`ref/Web-Prototype/museion-workspace.html` `:root` + grid): background/surface/foreground/muted/border/accent colors, radius 10, column widths (rail 56, library 232, mentor 356; the export's editor min 420 lands with #19's editor column), serif/mono font designs. Light-only — the export defines one palette.
- `WorkspaceView.swift` — post-gate main surface (replaces the M0 mentor pane as root): nav rail (Posts/Sessions/Learnings + Settings at bottom) + active pane. `RailButton` per the export (44×44, muted icon, hover wash, surface card + 2px edge bar when current). Sessions/Learnings are honest placeholders until #28/#26. Posts renders the full grid; **column collapse mirrors the export's media queries** (library hides < 1100 px, mentor hides < 920 px budget) as macOS pane collapse — never a fixed four-column minWidth that clips. `PaneHeader` = 52pt serif-15 title row + border.
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column, mentor column (`MentorPaneView`, fixed 356). Selecting a post renders it in the editor stub; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`).
- `PostsPaneView.swift` — Posts destination: library column (Pass State groups in mono-11 uppercase labels, post rows with title + passState/origin meta), empty state, editor column (`PostEditorView`), mentor column (`MentorPaneView`, fixed 356). Selecting a post opens an editing session; `PaneHeader` carries the New Post button (export `.pane-head .icon-btn`).
- `PostLibrary.swift` — `Post` (nonisolated: id/title/passState/origin) + `Post.scan(home:) -> [Post]`: reads `posts/<id>/post.md`, skips dirs without post.md (lazy folders), loose files, hidden dirs (dot-prefix), and symlinked dirs; Title = first non-empty line after frontmatter (`untitled` on blank, marker-only, or unterminated-frontmatter bodies); `pass_state`/`origin` frontmatter keys read leniently (First Draft/writer defaults, quoted YAML values unquoted, leading blank line before `---` tolerated). Scan runs off-main (bind/rescan in PostsModel).
- `PostStore.swift` — #18 write side (nonisolated): the shared slug function (#60: lowercase, diacritic-fold, strip punctuation, whitespace→hyphens, keep CJK, 80-char cap, `untitled` fallback), `availableSlug` collision suffixes `-2`/`-3`…, `writeNew` (lazy folder + #59 stamp `pass_state: First Draft` / `origin: writer` — the only values #18 writes), `overwrite` (preserves existing pass_state/origin, normalizes bare posts on save), `rename` = retitle + move (rewrites/inserts `# Title` as first non-empty body line, moves the folder, file stays `post.md`; a title slugging to the current id only retitles), `trash` (`FileManager.trashItem` — recoverable), `readBody` (frontmatter stripped for editing).
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save); recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on `posts/`, rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan); `bind(home:)` from `.task(id: home)` creates `posts/` if missing + rebinds on repoint; `shutdown()` tears the watcher down on quit (main actor); selecting a post abandons an unsaved draft; lifecycle ops (`saveDraft`/`saveSelected`/`rename`/`trash`) set `lastError` on failure, never alert.
- Editor stub (`EditorStub` in PostsPaneView, #62): plain `TextEditor`, ⌘S triggers save (first write fires lazy folder + slug + stamp); typed text is local `@State` keyed by `.id(post.id)`/`.id("draft")` — disk read at init, write on save only. Explicitly throwaway at the view layer: #19's TextKit2 editor replaces it in place; the lifecycle machinery below the view survives the swap. Rename sheet asks the new Title; delete via context menu → Trash.
- `PostsModel.swift` — `PostsModel` (@MainActor @Observable, app-scoped via `AppGateState.posts`): posts list + selection + New Post draft (`PostDraft`, in-memory, no folder until first save); the open post's `EditorSession` (#19) — `select(_:home:)` ends the prior session with a flush and opens a new one, rename/trash of the open post drops the session, `shutdown()` flushes on app quit; recursive FSEvents stream (`kFSEventStreamCreateFlagFileEvents`, 0.5 s latency — the debounce; file-level so nested `post.md` edits fire) on `posts/`, rescan reusing `Post.scan` off-main (#61 — own ops route through the same rescan; the rescan also hands the session the open post's disk text — the #67 external-change check, watcher-echo suppressed by equality with the session's last-flushed text); `bind(home:)` from `.task(id: home)` creates `posts/` if missing + rebinds on repoint; lifecycle ops (`saveDraft`/`rename`/`trash`) set `lastError` on failure, never alert; the session's `onError` routes save failures into the same strip.
- Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — the lifted spike presenter: line-kind → attributes map (Iowan Old Style 17 body, 26/20 bold headings, quote spacing, `***`-rule syntaxOnly), dimmed syntax (marker prefixes + inline marks, mono 13 at 0.55 white), pure functions; full-doc `attribute` on load, per-paragraph `reattribute` on edit. `EditorSession.swift` — @MainActor @Observable session per open post: `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` writes `PostStore.overwrite` + the cursor sidecar, tracks `saveState` Saved→Saving…→Saved (+ Save failed in accent, #65, routed to `lastError` too); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local; `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads the sidecar; `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in `posts/<id>/.museion-state.json` — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save).
- `SettingsPaneView.swift` — Home control (NSOpenPanel folder pick; files/canCreate on). Repoint-only semantics stated in-UI.
- `AppGateState.museionHome` — app-scoped Home (UserDefaults `museionHome`, default `~/Documents/Museion` = `defaultMuseionHome`; non-file URLs read back as nil — the Home is always a folder). Explicit init: `Self` in a stored-property initializer breaks `@ObservationTracked` (covariant-Self error).
- `MentorPaneView` no longer carries a root min-frame — it lives in the 356pt mentor column.
+158
View File
@@ -0,0 +1,158 @@
//
// EditorSession.swift
// Museion
//
// #19 (S1.2): the editor's write-behind machinery — debounced autosave (#64),
// save-state dot (#65), cursor-state sidecar (#66), external-change conflict
// rule (#67). One session per open post, owned by PostsModel. Drafts stay
// #62's explicit-⌘S path (PostsModel.saveDraft) — no session, no autosave.
//
import Foundation
import Observation
/// The save-state indicator (#65): Saved → Saving… → Saved, plus Save failed
/// in accent on write error. Never silent, never modal.
enum SaveState: Equatable {
case saved
case saving
case failed
}
/// One open post's editing session (@MainActor @Observable, the PostsModel
/// pattern). Born from a disk read; writes go out after the #64 debounce.
@MainActor
@Observable
final class EditorSession {
let postID: String
private let home: URL
private let debounce: Duration
/// Current body text (live, per keystroke).
private(set) var text: String
/// The save-state indicator (#65).
private(set) var saveState: SaveState = .saved
/// #67: external change detected → the surface presents the alert.
private(set) var conflictAlert = false
/// Load plumbing for the editor surface: `loadText` changes only at open
/// and Yes-reload (a `loadGeneration` bump) — never per keystroke.
private(set) var loadGeneration = 0
private(set) var loadText: String
/// Cursor state restored from the sidecar (#66); the surface applies it
/// (clamped) on load.
private(set) var restoreCursor: PostStore.CursorState?
/// Live cursor state pushed by the surface; written to the sidecar on
/// each flush.
private(set) var cursor = PostStore.CursorState()
/// Text at last flush (or open). The watcher-echo check compares disk
/// against this — an exact, timer-free suppression of our own writes.
private var lastFlushedText: String
private var debounceTask: Task<Void, Never>?
/// Failure text for the owner's lastError strip; nil clears it (#65).
var onError: (@MainActor @Sendable (String?) -> Void)?
init(postID: String, home: URL, debounce: Duration = .seconds(1)) {
self.postID = postID
self.home = home
self.debounce = debounce
let body = PostStore.readBody(id: postID, home: home) ?? ""
text = body
loadText = body
lastFlushedText = body
restoreCursor = PostStore.readCursor(id: postID, home: home)
}
// MARK: Edit + debounce (#64)
/// Keystroke from the editor surface; re-arms the ~1 s idle debounce.
func edit(_ newText: String) {
text = newText
debounceTask?.cancel()
debounceTask = Task { [debounce] in
try? await Task.sleep(for: debounce)
guard !Task.isCancelled else { return }
// #67: never autosave over an external change while its alert is
// unanswered — the alert promises the writer chooses. ⌘S (flush)
// stays explicit.
guard !conflictAlert else { return }
flush()
}
}
/// Live cursor state from the surface (selection + scroll).
func cursorUpdate(_ state: PostStore.CursorState) {
cursor = state
}
// MARK: Flush (#64/#65/#66)
/// Write body + sidecar now. ⌘S, debounce fire, selection change, window
/// close, and app quit all land here. No-op when clean.
func flush() {
debounceTask?.cancel()
guard text != lastFlushedText else { return }
saveState = .saving
do {
try PostStore.overwrite(id: postID, body: text, home: home)
lastFlushedText = text
saveState = .saved
onError?(nil)
// Sidecar best-effort: the content write is what matters; a failed
// cursor write must never read as a failed save.
PostStore.writeCursor(cursor, id: postID, home: home)
} catch {
saveState = .failed
onError?(error.localizedDescription)
}
}
// MARK: External change (#67)
/// Owner teardown when the post leaves the editor (rename away, trash,
/// vanished on disk). `flushFirst` writes pending edits (rename reads the
/// file from disk, so unflushed text would be lost); otherwise the armed
/// debounce is cancelled so it can't fire at a dead path and report a
/// spurious failure.
func teardown(flushFirst: Bool) {
if flushFirst {
flush()
}
debounceTask?.cancel()
}
/// The owner's rescan calls this with the open post's current disk text.
/// Equality against `lastFlushedText` suppresses our own write's watcher
/// echo exactly — no suppression timers.
func diskDidChange(diskText: String) {
guard diskText != lastFlushedText, diskText != text else { return }
conflictAlert = true
}
/// #67 Yes: reload from disk; cursor restored from the sidecar where
/// still valid (the surface clamps).
func reloadFromDisk() {
guard conflictAlert else { return }
conflictAlert = false
guard let disk = PostStore.readBody(id: postID, home: home) else { return }
text = disk
loadText = disk
loadGeneration += 1
lastFlushedText = disk
restoreCursor = PostStore.readCursor(id: postID, home: home)
saveState = .saved
}
/// #67 No: keep local — the next autosave overwrites disk (the writer's
/// explicit choice). Marks the disk state as seen so the same external
/// content doesn't re-alert on every watcher tick; a new external write
/// still does.
func keepLocal() {
guard conflictAlert else { return }
conflictAlert = false
lastFlushedText = PostStore.readBody(id: postID, home: home) ?? text
}
}
+266
View File
@@ -0,0 +1,266 @@
//
// PostEditorView.swift
// Museion
//
// #19 (S1.2): the TextKit2 editing surface (ADR-0010 mode B) — the spike's
// EditorPane lifted: plain `isRichText = false` store, presentation-only
// attributes re-applied per edited paragraph; native undo/IME/find. Session
// mode autosaves via EditorSession (#64–#67); draft mode stays #62's
// explicit-⌘S path. The #18 stub's Save button died here (#65).
//
import AppKit
import Combine
import SwiftUI
/// Editor column content: toolbar row (crumb + save-state widget) + surface.
/// `session` nil = draft mode (crumb + ⌘S first-write, no autosave, no dot).
struct PostEditorView: View {
let session: EditorSession?
/// Draft mode: initial text + keystroke/⌘S callbacks (model boundary).
let draftText: String?
var draftEdited: ((String) -> Void)?
var draftSave: (() -> Void)?
@State private var closeObserver: AnyCancellable?
var body: some View {
VStack(spacing: 0) {
toolbar
Rectangle().fill(DesignTokens.border).frame(height: 1)
if let session {
ProseTextView(session: session)
} else {
ProseTextView(draft: draftText ?? "", onEdit: { draftEdited?($0) })
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(DesignTokens.surface)
// #64: flush on window close (app quit rides willTerminate in MuseionApp).
// ponytail: no object filter — flush is idempotent; any-window close is fine.
.onAppear {
closeObserver = NotificationCenter.default.publisher(
for: NSWindow.willCloseNotification,
).sink { _ in
session?.flush()
}
}
// #67: explicit alert — never silent in either direction.
.alert("File on Disk changed", isPresented: conflictBinding) {
Button("Reload") { session?.reloadFromDisk() }
Button("Keep Local") { session?.keepLocal() }
} message: {
Text("post.md changed outside Museion. Reload discards your unsaved edits; Keep Local overwrites the file on the next save.")
}
}
/// Extracted binding (SwiftFormat/SwiftLint closure_position peace).
/// Dismissal without a button (Esc) = keep-local semantics, same as No.
private var conflictBinding: Binding<Bool> {
guard let session else { return .constant(false) }
return Binding(
get: { session.conflictAlert },
set: {
if !$0 {
session.keepLocal()
}
},
)
}
// MARK: Toolbar
private var toolbar: some View {
HStack {
Text(crumb)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.lineLimit(1)
.truncationMode(.head)
Spacer()
if let session {
SaveStateDot(state: session.saveState)
} else {
// Draft (#62): ⌘S = first write (lazy folder). No visible Save
// button — the stub's died (#65); the crumb carries the hint.
Text("⌘S saves")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
// #64: ⌘S stays immediate in both modes — invisible trigger.
Button("") { saveNow() }
.keyboardShortcut("s", modifiers: .command)
.opacity(0)
.frame(width: 1, height: 1)
.accessibilityHidden(true)
}
.padding(.horizontal, 16)
.frame(minHeight: 40)
}
private func saveNow() {
if let session {
session.flush()
} else {
draftSave?()
}
}
private var crumb: String {
if let session {
"posts / \(session.postID) / post.md"
} else {
"unsaved draft — no folder until first save"
}
}
}
/// The save-state widget (#65, export line 453): 6px dot + label, role=status,
/// aria-live=polite → accessibilityLabel on the element. Failed shows in accent.
private struct SaveStateDot: View {
let state: SaveState
var body: some View {
HStack(spacing: 7) {
Circle()
.fill(state == .failed ? DesignTokens.accent : DesignTokens.muted)
.frame(width: 6, height: 6)
Text(label)
}
.font(.system(size: 12))
.foregroundStyle(state == .failed ? DesignTokens.accent : DesignTokens.muted)
.accessibilityElement(children: .ignore)
.accessibilityLabel("Save state: \(label)")
}
private var label: String {
switch state {
case .saved: "Saved"
case .saving: "Saving…"
case .failed: "Save failed"
}
}
}
// MARK: - TextKit2 surface (the lifted spike pane)
/// NSTextView in a scroll view; attributes are presentation-only over a plain
/// store. Session mode: edits → session.edit (debounce), cursor → session,
/// loads keyed by generation (open + Yes-reload). Draft mode: edits → onEdit.
struct ProseTextView: NSViewRepresentable {
var session: EditorSession?
var draft: String?
var onEdit: ((String) -> Void)?
init(session: EditorSession) {
self.session = session
}
init(draft: String, onEdit: @escaping (String) -> Void) {
self.draft = draft
self.onEdit = onEdit
}
/// Cursor state snapshot from the live view (#66).
static func cursorState(of tv: NSTextView) -> PostStore.CursorState {
let sel = tv.selectedRange()
var state = PostStore.CursorState()
state.selectionLocation = max(0, sel.location)
state.selectionLength = max(0, sel.length)
state.scrollOffset = Double(tv.enclosingScrollView?.contentView.bounds.origin.y ?? 0)
return state
}
func makeNSView(context: Context) -> NSScrollView {
let tv = NSTextView()
tv.isRichText = false // plain source of truth; attributes are presentation
tv.allowsUndo = true
tv.isAutomaticQuoteSubstitutionEnabled = false
tv.isAutomaticDashSubstitutionEnabled = false
tv.isAutomaticTextReplacementEnabled = false
tv.isAutomaticSpellingCorrectionEnabled = false
tv.usesFindBar = true
tv.backgroundColor = NSColor.white
tv.typingAttributes = ProsePresenter.bodyAttributes
tv.delegate = context.coordinator
tv.layoutManager?.allowsNonContiguousLayout = true
tv.minSize = NSSize(width: 0, height: 0)
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
tv.isVerticallyResizable = true
tv.isHorizontallyResizable = false
tv.autoresizingMask = [.width]
tv.textContainer?.containerSize = NSSize(width: 640, height: CGFloat.greatestFiniteMagnitude)
tv.textContainer?.widthTracksTextView = false
tv.textContainer?.lineFragmentPadding = 12
tv.textContainerInset = NSSize(width: 0, height: 20)
let scroll = NSScrollView()
scroll.documentView = tv
scroll.hasVerticalScroller = true
scroll.autohidesScrollers = true
scroll.drawsBackground = true
scroll.backgroundColor = NSColor.white
context.coordinator.textView = tv
context.coordinator.sessionRef = session // strong: both die with the editor
return scroll
}
func updateNSView(_ scroll: NSScrollView, context: Context) {
guard let tv = scroll.documentView as? NSTextView else { return }
if let session {
context.coordinator.sessionRef = session
// Load only when the generation moved (open, Yes-reload) — never
// per keystroke: the text view owns the live text.
if context.coordinator.loadedGeneration != session.loadGeneration {
context.coordinator.loadedGeneration = session.loadGeneration
tv.textStorage?.setAttributedString(ProsePresenter.attribute(session.loadText))
// #66: restore cursor (clamped) + scroll.
let length = (tv.string as NSString).length
var cursor = session.restoreCursor ?? PostStore.CursorState()
cursor.selectionLocation = min(max(0, cursor.selectionLocation), length)
cursor.selectionLength = min(max(0, cursor.selectionLength), length - cursor.selectionLocation)
tv.setSelectedRange(NSRange(location: cursor.selectionLocation, length: cursor.selectionLength))
tv.scroll(NSPoint(x: 0, y: max(0, cursor.scrollOffset)))
tv.window?.makeFirstResponder(tv)
session.cursorUpdate(cursor)
}
} else if let draft, tv.string != draft {
// Echo guard: our own keystroke round-trips through the model —
// only reload when the textview genuinely diverges (new draft).
tv.textStorage?.setAttributedString(ProsePresenter.attribute(draft))
}
}
func makeCoordinator() -> Coordinator {
Coordinator(representable: self)
}
final class Coordinator: NSObject, NSTextViewDelegate {
let onEdit: ((String) -> Void)?
weak var textView: NSTextView?
var sessionRef: EditorSession?
var loadedGeneration = -1
init(representable: ProseTextView) {
onEdit = representable.onEdit
}
func textDidChange(_ notification: Notification) {
guard let tv = notification.object as? NSTextView, let storage = tv.textStorage else { return }
let sel = tv.selectedRange()
// Re-attribute the paragraph(s) touching the selection — one pass.
let paragraphRange = (storage.string as NSString).paragraphRange(for: sel)
ProsePresenter.reattribute(storage as NSMutableAttributedString, paragraphRange: paragraphRange)
tv.typingAttributes = ProsePresenter.bodyAttributes
if let sessionRef {
sessionRef.edit(storage.string)
} else {
onEdit?(storage.string)
}
}
func textViewDidChangeSelection(_ notification: Notification) {
guard let tv = notification.object as? NSTextView, let sessionRef else { return }
sessionRef.cursorUpdate(ProseTextView.cursorState(of: tv))
}
}
}
+28
View File
@@ -115,6 +115,34 @@ nonisolated enum PostStore {
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.
+61 -20
View File
@@ -78,6 +78,10 @@ final class PostsModel {
/// The in-memory draft for New Post (#62): no folder until first save.
private(set) var draft: PostDraft?
/// #19: the open post's editing session; nil while a draft is open or
/// nothing is selected.
private(set) var session: EditorSession?
/// Last failed-op message surfaced in the editor (nil = clean).
private(set) var lastError: String?
@@ -112,11 +116,27 @@ final class PostsModel {
/// 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
// Scan + the #67 disk read both run off-main (a synced large post.md
// must never stall the UI on a watcher burst).
let openPostID = session?.postID
let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) {
let posts = Post.scan(home: home)
let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) }
return (posts, disk)
}.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)
if let open = session, open.postID == id {
open.teardown(flushFirst: false) // post is gone; cancel the debounce
self.session = nil
}
}
// #67: watcher echo check on the open post — equality against the
// session's lastFlushedText suppresses our own writes exactly.
if let session, let openDiskText {
session.diskDidChange(diskText: openDiskText)
}
}
@@ -127,37 +147,33 @@ final class PostsModel {
// 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.
/// deinit of a @MainActor-held object may run elsewhere. #64: app quit
/// flushes the open session first (sidecar rides along).
func shutdown() {
session?.flush()
watcher.stop()
}
/// New Post (#62): fresh in-memory draft, no folder, editor takes it.
func newPost() {
session?.teardown(flushFirst: true) // #64: selection change flushes
session = nil
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).
/// here. The saved post opens straight into an editing session — the
/// writer keeps typing where they were. 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)
session = EditorSession(postID: post.id, home: home)
wireSession()
lastError = nil
Task { await rescan() }
} catch {
@@ -167,23 +183,43 @@ final class PostsModel {
/// 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) {
/// selecting away). #19: opening a post ends the previous session
/// (flush-on-selection-change, #64) and starts a new one.
func select(_ id: String, home: URL) {
if let session, session.postID != id {
session.teardown(flushFirst: true)
}
session = id == session?.postID ? session : EditorSession(postID: id, home: home)
draft = nil
selectedPostID = id
wireSession()
}
/// Draft typing from the editor stub (private(set) barrier).
private func wireSession() {
session?.onError = { [weak self] message in self?.lastError = message }
}
/// Draft typing from the editor (private(set) barrier).
func updateDraft(_ text: String) {
draft?.text = text
}
/// Explicit Rename = retitle + move (#60). Sets lastError on failure.
/// Explicit Rename = retitle + move (#60). Renaming the open post flushes
/// first (rename reads the file from disk — unflushed edits must land
/// before the move), then reopens a session at the new id. Sets lastError
/// on failure.
func rename(_ post: Post, to title: String, home: URL) {
if let session, session.postID == post.id {
session.flush() // before PostStore.rename reads the old file
}
do {
let moved = try PostStore.rename(post, to: title, home: home)
if selectedPostID == post.id {
selectedPostID = moved.id
if session?.postID == post.id {
session = EditorSession(postID: moved.id, home: home)
wireSession()
}
}
lastError = nil
Task { await rescan() }
@@ -193,12 +229,17 @@ final class PostsModel {
}
/// Delete a Post (Trash, recoverable — #18 AC). Clears selection if it
/// was the post.
/// was the post; the session is torn down (cancel only — the folder is
/// leaving, a flush would resurrect nothing but churn the watcher).
func trash(_ post: Post, home: URL) {
do {
try PostStore.trash(post, home: home)
if selectedPostID == post.id {
selectedPostID = nil
if let open = session, open.postID == post.id {
open.teardown(flushFirst: false)
self.session = nil
}
}
lastError = nil
Task { await rescan() }
+12 -64
View File
@@ -4,7 +4,8 @@
//
// #17 (S1.1): the Posts pane — library column mirroring the Home's posts/
// on disk. #18: lifecycle — New Post draft, ⌘S first-write/save, rename,
// trash; TextEditor stub until #19–#21, mentor column (#14).
// trash. #19: the TextKit2 editor core (PostEditorView) replaces the stub;
// mentor column (#14).
//
import SwiftUI
@@ -92,7 +93,7 @@ struct PostsPaneView: View {
.padding(.bottom, 7)
ForEach(grouped) { post in
PostRow(post: post, selected: post.id == model.selectedPostID) {
model.select(post.id)
model.select(post.id, home: home)
}
.contextMenu {
Button("Rename…") { renamingPost = post }
@@ -124,29 +125,23 @@ struct PostsPaneView: View {
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
// MARK: Editor column (stub until #19)
// MARK: Editor column (#19: TextKit2 editor core)
private var editorColumn: some View {
VStack(spacing: 0) {
if let draft = model.draft {
EditorStub(
initialText: draft.text,
crumb: "unsaved draft — no folder until first save",
save: { text in
model.updateDraft(text)
PostEditorView(
session: nil,
draftText: draft.text,
draftEdited: { model.updateDraft($0) },
draftSave: {
model.saveDraft(home: home)
},
)
.id("draft")
} else if let post = model.posts.first(where: { $0.id == model.selectedPostID }) {
// ponytail: readBody is one small file, sync, per selection
// change — #19's editor owns async loading when it lands.
EditorStub(
initialText: PostStore.readBody(id: post.id, home: home) ?? "",
crumb: "posts / \(post.id) / post.md",
save: { text in model.saveSelected(body: text, home: home) },
)
.id(post.id)
} else if let session = model.session, session.postID == model.selectedPostID {
PostEditorView(session: session, draftText: nil)
.id(session.postID)
} else {
VStack(spacing: 10) {
Image(systemName: "square.and.pencil")
@@ -175,53 +170,6 @@ struct PostsPaneView: View {
}
}
/// #18 stub editor (#62): plain TextEditor in the placeholder slot; ⌘S is
/// the first-write trigger (lazy folder + slug + stamp). Throwaway at the
/// view layer — #19's TextKit2 editor replaces it in place; the lifecycle
/// machinery lives in PostsModel/PostStore and survives the swap.
private struct EditorStub: View {
/// Typed text is local @State — disk is written only on save; `.id()` at
/// the call site swaps identity (and thus reloads) per post/draft.
let crumb: String
let save: (String) -> Void
@State private var text: String
init(
initialText: String,
crumb: String,
save: @escaping (String) -> Void,
) {
self.crumb = crumb
self.save = save
_text = State(initialValue: initialText)
}
var body: some View {
VStack(spacing: 0) {
HStack {
Text(crumb)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.lineLimit(1)
.truncationMode(.head)
Spacer()
Button("Save") { save(text) }
.keyboardShortcut("s", modifiers: .command)
}
.padding(.horizontal, 16)
.frame(minHeight: 40)
.overlay(alignment: .bottom) {
Rectangle().fill(DesignTokens.border).frame(height: 1)
}
TextEditor(text: $text)
.font(.system(size: 15, design: DesignTokens.serif))
.scrollContentBackground(.hidden)
.padding(EdgeInsets(top: 20, leading: 24, bottom: 20, trailing: 24))
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
/// #60: Explicit Rename dialog — asks the new Title (not a slug).
private struct RenamePostSheet: View {
let rename: (String) -> Void
+127
View File
@@ -0,0 +1,127 @@
//
// ProsePresenter.swift
// Museion
//
// #19 (S1.2): line-based markdown presentation for the editor — lifted from
// the proven spike (spike/textkit2, ADR-0010: ≤1.1 ms full-doc attribute load
// on PERF-3k). Presentation-only: the plain `isRichText = false` store stays
// the source of truth; attributes ride on top and re-apply per edited
// paragraph. The Fix-Card anchor search stays with M2 (#25) — not lifted.
//
import AppKit
/// Styled-source presentation (ADR-0010 mode B): variable heading sizes,
/// paragraph spacing, dimmed syntax. Pure functions over text; no AppKit view
/// state. Colors are the spike's proven values (foreground ≈ DesignTokens
/// foreground; the 0.55 syntax dim is deliberately lighter than muted).
nonisolated enum ProsePresenter {
enum LineKind { case heading1, heading2, quote, syntaxOnly, body }
static func lineKind(_ line: String) -> LineKind {
let trimmedLine = line.drop(while: { $0 == " " })
if trimmedLine.hasPrefix("## ") {
return .heading2
}
if trimmedLine.hasPrefix("# ") {
return .heading1
}
if trimmedLine.hasPrefix("> ") {
return .quote
}
if !trimmedLine.isEmpty, trimmedLine.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) {
return .syntaxOnly
}
return .body
}
static let inlineSyntax: Set<Character> = ["*", "_", "`", "[", "]", "(", ")", "!", "<", ">"]
/// Paragraph spacing per line kind, applied via NSParagraphStyle.
/// ponytail: quote rides body spacing — attributes(for:) styles quotes
/// as body anyway; dedicated quote spacing waits for #20's polish pass.
static func paragraph(_ kind: LineKind) -> NSParagraphStyle {
let style = NSMutableParagraphStyle()
switch kind {
case .heading1: style.paragraphSpacing = 18; style.paragraphSpacingBefore = 26
case .heading2: style.paragraphSpacing = 12; style.paragraphSpacingBefore = 20
case .quote, .syntaxOnly, .body: style.paragraphSpacing = 10
}
return style
}
/// Attribute a whole text (initial load). Headings/body/quote styling + dimmed syntax.
static func attribute(_ text: String) -> NSAttributedString {
let out = NSMutableAttributedString(string: text, attributes: bodyAttributes)
let nsText = text as NSString
nsText.enumerateSubstrings(in: NSRange(location: 0, length: nsText.length), options: [.byLines]) { line, range, _, _ in
guard let line else { return }
let kind = lineKind(line)
out.setAttributes(Self.attributes(for: kind), range: range)
dimSyntax(in: out, range: range)
}
return out
}
/// Attribute one paragraph (editing-time re-apply). Cheap: one line, one pass.
static func reattribute(_ out: NSMutableAttributedString, paragraphRange: NSRange) {
let line = (out.string as NSString).substring(with: paragraphRange)
let kind = lineKind(line)
out.setAttributes(Self.attributes(for: kind), range: paragraphRange)
dimSyntax(in: out, range: paragraphRange)
}
// Typography: Iowan Old Style prose stance (the export's stack), 17pt body,
// scaled headings.
static var bodyFont: NSFont {
NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17)
?? NSFont.systemFont(ofSize: 17)
}
static var bodyAttributes: [NSAttributedString.Key: Any] {
[
.font: bodyFont,
.paragraphStyle: paragraph(.body),
.foregroundColor: NSColor(red: 0.10, green: 0.10, blue: 0.09, alpha: 1),
]
}
static func attributes(for kind: LineKind) -> [NSAttributedString.Key: Any] {
func headingFont(size: CGFloat, weight: Int) -> NSFont {
NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [.boldFontMask], weight: weight, size: size)
?? .boldSystemFont(ofSize: size)
}
switch kind {
case .heading1: return [.font: headingFont(size: 26, weight: 9), .paragraphStyle: paragraph(.heading1)]
case .heading2: return [.font: headingFont(size: 20, weight: 8), .paragraphStyle: paragraph(.heading2)]
case .quote, .syntaxOnly, .body: return bodyAttributes
}
}
/// Dim markdown syntax characters within a line range (marker prefixes + inline marks).
static func dimSyntax(in out: NSMutableAttributedString, range: NSRange) {
let nsText = out.string as NSString
guard range.length > 0 else { return }
let line = nsText.substring(with: range)
let kind = lineKind(line)
// prefix markers
let markerLen = switch kind {
case .heading1: 2
case .heading2: 3
case .quote: 2
default: 0
}
let dim: [NSAttributedString.Key: Any] = [.foregroundColor: NSColor(white: 0.55, alpha: 1), .font: NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)]
if markerLen > 0 {
out.addAttributes(dim, range: NSRange(location: range.location, length: min(markerLen, range.length)))
}
// inline marks in body/quote
if kind == .body || kind == .quote {
for (offset, codeUnit) in line.utf16.enumerated() {
if let scalar = Unicode.Scalar(codeUnit).map({ Character($0) }), inlineSyntax.contains(scalar) {
out.addAttributes(dim, range: NSRange(location: range.location + offset, length: 1))
}
}
}
}
}