Files
museion/Museion/PostEditorView.swift
T
AlexKucera 1f7557a2ed fix(editor): audit fixes — fence staleness, font caching, lint shrink (#77)
- HIGH: fence delimiter edits now restyle the whole document (delimiter
  count fingerprint in the coordinator; count moved = full re-attribute,
  caret preserved) — typing/deleting a ``` flipped every line until
  the match before
- derived fonts + measureWidth cached as nonisolated(unsafe) static let
  (were NSFontManager.convert per line per pass)
- h2/h3/h4 line height calibrated from their own face's metrics
- 7+ hashes fall to body (CommonMark cap); tab-indented heading marker
  dims the hash, not the tab
- intraword _ spans unclaim on reject so the fallback char-dim takes them
- shrink: fenceState reuses contentLines+classify (isDelim deleted),
  marker regexes as literals (helper + 2 lint disables deleted),
  charBefore/After via NSString, dead colors + forwarders deleted
- vacuous retrofit test replaced with a real one + fenceDelimCount test
2026-10-08 14:11:47 +02:00

410 lines
15 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// 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).
// #71 (map #20): the reading toggle (#68) — Read⇄Edit toolbar button (far
// left, before the crumb) + View menu item + ⌘R; reading renders
// ReadingPresenter output in a read-only canvas; a tap with no selection
// drops to editing at that paragraph; drafts included; no persistence —
// every fresh open lands in editing.
//
import AppKit
import Combine
import SwiftUI
extension Notification.Name {
/// #68: the View menu's "Toggle Reading Mode" item — the visible editor
/// listens (one editor column exists at a time).
static let toggleReadingMode = Notification.Name("museion.toggleReadingMode")
}
/// 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?
@State private var toggleObserver: AnyCancellable?
/// #68: reading is a transient act of inspection — no persistence; a
/// fresh open always lands in editing.
@State private var reading = false
/// Flip-back caret (#68): source location + a token so repeated flips to
/// the same location re-apply. Consumed by ProseTextView's coordinator.
@State private var flipBackCaret: (location: Int, token: Int)?
@State private var flipToken = 0
/// Reading scroll state (#68 mapping): entry caret + live top block.
@State private var readingState = ReadingStateBox()
/// Draft text mirror — reading renders it; edits flow back via onEdit.
@State private var draftMirror = ""
var body: some View {
VStack(spacing: 0) {
toolbar
Rectangle().fill(DesignTokens.border).frame(height: 1)
if reading {
ReadingSurface(
text: renderText,
generation: session?.loadGeneration ?? 0,
postFolder: session?.folderURL,
entryCaretLocation: readingState.entryLocation,
onEditIntent: { loc in exitReading(caret: loc) },
stateBox: readingState,
)
} else {
// #77: editor measure — reading.css --measure 66ch. The scroll
// view fills the column; the text container centers at the
// measured width so wide columns match the reading surface.
editingSurface
.frame(maxWidth: ProseTypography.measureWidth)
.frame(maxWidth: .infinity)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(DesignTokens.surface)
.onAppear {
if draftMirror.isEmpty {
draftMirror = draftText ?? ""
}
closeObserver = NotificationCenter.default.publisher(
for: NSWindow.willCloseNotification,
).sink { _ in
session?.flush()
}
// #68: View menu / ⌘R reaches the visible editor.
toggleObserver = NotificationCenter.default.publisher(
for: .toggleReadingMode,
).sink { [weak session] _ in
toggleReading()
_ = session
}
}
// #67: explicit alert — never silent in either direction. It hangs
// above the surface swap, so it shows while reading too; Yes-reload
// bumps loadGeneration and the reading surface re-renders (#68 Q6).
.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.")
}
}
/// The text reading renders: live session text or the draft mirror.
private var renderText: String {
session?.text ?? draftMirror
}
@ViewBuilder
private var editingSurface: some View {
if let session {
ProseTextView(session: session, caretHint: flipBackCaret)
} else {
ProseTextView(draft: draftMirror, onEdit: { newText in
draftMirror = newText
draftEdited?(newText)
}, caretHint: flipBackCaret)
}
}
// MARK: Reading toggle (#68)
private func toggleReading() {
if reading {
exitReading(caret: nil)
} else {
// Entry mapping: the editing caret's block scrolls to the top.
readingState.entryLocation = session?.cursor.selectionLocation
reading = true
}
}
private func exitReading(caret: Int?) {
flipToken += 1
// Toggle-back maps the reading scroll back (top visible block);
// click-to-edit lands at the clicked paragraph (survives always).
flipBackCaret = (caret ?? readingState.topSourceLocation ?? 0, flipToken)
reading = false
}
/// 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 {
// #68: labeled toggle, far left, before the crumb.
Button(reading ? "Edit" : "Read") { toggleReading() }
.help(reading ? "Return to editing (⌘R)" : "Render this post (⌘R)")
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.
/// #71: `caretHint` (location + token) lands the caret after a flip back
/// from reading — applied once per token, after any generation load.
struct ProseTextView: NSViewRepresentable {
var session: EditorSession?
var draft: String?
var onEdit: ((String) -> Void)?
var caretHint: (location: Int, token: Int)?
init(session: EditorSession, caretHint: (location: Int, token: Int)? = nil) {
self.session = session
self.caretHint = caretHint
}
init(
draft: String,
onEdit: @escaping (String) -> Void,
caretHint: (location: Int, token: Int)? = nil,
) {
self.draft = draft
self.onEdit = onEdit
self.caretHint = caretHint
}
/// 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 = ProseTypography.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]
// Wrap to the editor column (#71 fix): the container tracks the view
// width — the fixed 640pt measure clipped in narrower columns.
tv.textContainer?.containerSize = NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude)
tv.textContainer?.widthTracksTextView = true
tv.textContainer?.lineFragmentPadding = 24
tv.textContainerInset = NSSize(width: 0, height: 20)
let scroll = NSScrollView()
scroll.documentView = tv
scroll.hasVerticalScroller = true
scroll.autohidesScrollers = true
// #77: overlay style — the knob appears during scrolling and fades
// out at rest (iOS-like), instead of always occupying the right edge.
scroll.scrollerStyle = .overlay
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
// Seed from session.text (LIVE), not session.loadText (the
// open-time snapshot): the representable is recreated on the
// reading⇄editing swap, and seeding from the snapshot showed
// pre-edit text — then session.edit on the stale view would
// have flushed it over the user's real content (#71 fix).
tv.textStorage?.setAttributedString(ProsePresenter.attribute(session.text))
context.coordinator.fenceDelims = ProsePresenter.fenceDelimCount(session.text)
// #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))
// ponytail: TextKit lays out async — a sync scroll on a fresh mount
// lands short of the target (clamps to what's laid out). One runloop
// hop lets layout finish; verified against a 3000-para doc offscreen.
DispatchQueue.main.async { [weak tv] in
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))
}
// #71: flip-back caret — apply once per token, after any load above.
if let hint = caretHint, context.coordinator.appliedCaretToken != hint.token {
context.coordinator.appliedCaretToken = hint.token
let length = (tv.string as NSString).length
let loc = min(max(0, hint.location), length)
tv.setSelectedRange(NSRange(location: loc, length: 0))
// ponytail: same layout race as the cursor-restore scroll above —
// this was the click-to-edit "always lands at top" defect: the sync
// scrollRangeToVisible fired before the target region was laid out.
// One runloop hop fixes it (offscreen-verified, 3000-para doc).
DispatchQueue.main.async { [weak tv] in
tv?.scrollRangeToVisible(NSRange(location: loc, length: 0))
tv?.window?.makeFirstResponder(tv)
}
if let session {
session.cursorUpdate(ProseTextView.cursorState(of: tv))
}
}
}
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
var appliedCaretToken = -1
/// #77: fence delimiter count — the cross-paragraph fence state
/// fingerprint. A moved count means a ``` was typed/deleted and every
/// line until the matching delimiter changed kind.
var fenceDelims = 0
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()
let delims = ProsePresenter.fenceDelimCount(storage.string)
if delims == fenceDelims {
// 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)
} else {
// Delimiter typed/deleted: fence state flipped downstream —
// restyle the whole document, keeping the caret put.
fenceDelims = delims
let selected = tv.selectedRange()
tv.textStorage?.setAttributedString(ProsePresenter.attribute(storage.string))
tv.setSelectedRange(selected)
}
tv.typingAttributes = ProseTypography.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))
}
}
}