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

+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))
}
}
}