Files
museion/Museion/PostEditorView.swift
AlexKucera 97893147a6 feat(fix-cards): jump to the anchor
Jump on a Fix Card selects the anchor's span in the piece's
editor and makes the main window key (#204). The span is the
card's quote at its 1-based occurrence, resolved against the
LIVE session text so a dirty buffer still lands, and it rides
the reading flip-back's caret rail: caretHint widens from a
(location, token) tuple to FixCardRevealRequest (SwiftLint
large_tuple), one shared token counter so a jump and a flip-back
can never collide, a zero-length range stays a bare caret and a
non-zero range selects. A jump leaves reading mode first
(reading = false, not exitReading, which stamps its own
zero-length hint), writes nothing, and re-fires per click.

The palette offers Jump on every non-stale card that still shows
an action row; stale anchors have nothing to land on. The
landing math is ProseTextView.landingSpan - a bare caret hops
past leading blanks, a span never does (a quote that IS the
leading blanks selects those blanks) - and appliedText now
routes through anchorRange so Apply and Jump share one
occurrence math.

Two review rounds closed the view-layer gaps the pure pins
could not see: a jump dropped in reading mode; a main window
that never became key (NSApp.activate is a no-op once the
palette's click activated the app - the Coordinator makes
tv.window key instead); a cursor record taken before the scroll.

+3 tests (anchorRange occurrence math with a UTF-16 fixture, the
model's reveal stamp, landingSpan), each flip-verified. Rail
732/732; SwiftFormat and SwiftLint clean. DOX: Museion/AGENTS,
MuseionTests/AGENTS, GLOSSARY gains Jump.
2026-12-03 17:48:55 +01:00

668 lines
27 KiB
Swift
Raw Permalink 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)?
/// #109: render the outline editing surface instead of prose.
var outline = false
/// #33 (S6.1): open the Micro.blog publish ask. Nil (default) hides
/// the toolbar button — drafts, the external guest, and previews
/// have nothing to publish.
var publish: (() -> Void)?
@State private var closeObserver: AnyCancellable?
@State private var toggleObserver: AnyCancellable?
/// #77: spellcheck posture (app-scoped, Edit menu) — applied to the live
/// text view on every representable update.
@Environment(AppGateState.self) private var gate
/// #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) and #204 jump span: a zero-length range is a
/// bare caret landing, a non-zero range selects the anchor; the token
/// re-applies repeats. Consumed by ProseTextView's coordinator.
@State private var flipBackCaret: FixCardRevealRequest?
@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) {
if showsToolbar {
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(focusGround)
// #21: ⌘S stays armed in focus too — drafts have no autosave; the
// trigger is invisible either way, so it lives here, not in the
// receding toolbar.
.background {
Button("") { saveNow() }
.keyboardShortcut("s", modifiers: .command)
.opacity(0)
.frame(width: 1, height: 1)
.accessibilityHidden(true)
}
// #21: save failure is LOUD in focus — the full widget floats where
// the toolbar stood. Drafts (no autosave): a muted cue appears once
// there is text to lose; ⌘S stays armed either way (body level).
.overlay(alignment: .top) {
if gate.isFocused {
if session?.saveState == .failed {
focusChip { SaveStateDot(state: .failed) }
} else if session == nil, draftMirror != (draftText ?? "") {
focusChip {
Text("⌘S saves")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
}
}
}
// #204: a Fix Card jump (the palette's Jump) lands here — the model's
// reveal request rides the SAME caret rail as the reading flip-back,
// through the ONE token counter (two counters could collide and a
// jump would silently never land): the span selected, revealed, and
// the main window made key so the writer can type where the card
// pointed (the coordinator does that — it owns tv.window). A jump
// while READING leaves reading first — plain `reading = false`, not
// exitReading (which would stamp its own zero-length hint over the
// jump); the remounted coordinator applies the jump after the load.
// Outline pieces have no prose surface — the request is dropped.
.onChange(of: gate.posts.revealRequest) { _, request in
guard let request, !outline else { return }
flipToken += 1
flipBackCaret = FixCardRevealRequest(range: request.range, token: flipToken)
reading = false
}
.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("\(session?.fileURL?.lastPathComponent ?? "post.md") changed outside Museion. "
+ "Reload discards your unsaved edits; Keep Local overwrites the file on the next save.")
}
}
/// #21: the toolbar row recedes in focus — the floating chip above is
/// the failure surface there (never both at once).
private var showsToolbar: Bool {
!gate.isFocused
}
/// The floating focus-mode chip: pill background + top-edge transition.
private func focusChip(@ViewBuilder _ content: () -> some View) -> some View {
content()
.padding(.horizontal, 14)
.padding(.vertical, 7)
.background(DesignTokens.surface.opacity(0.96), in: RoundedRectangle(cornerRadius: DesignTokens.radius))
.transition(.move(edge: .top).combined(with: .opacity))
}
/// #21: focus runs on the workspace background, not the surface card —
/// the centered measure on the workspace ground is all that remains.
private var focusGround: Color {
gate.isFocused ? DesignTokens.background : DesignTokens.surface
}
/// 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 outline {
// #109: the outliner — same session/draft duality as prose.
// Draft mode keeps the mirror current via draftEdited so the
// reading surface renders the serialized outline; the outline
// view seeds from draftText once and owns the tree after.
OutlineEditorView(
session: session,
onDraftEdit: session == nil ? { draftMirror = $0; draftEdited?($0) } : nil,
draftText: session == nil ? draftText : nil,
)
} else if let session {
ProseTextView(
session: session,
spellChecking: gate.spellChecking,
focused: gate.isFocused,
caretHint: flipBackCaret,
dropBridge: gate.proseDrop,
routeDrop: { gate.routeFileDrop($0) },
// #162: the Cold Turkey word feed.
onTextChange: { gate.writingLock.feed(text: $0) },
)
} else {
ProseTextView(
draft: draftMirror,
spellChecking: gate.spellChecking,
focused: gate.isFocused,
onEdit: { newText in
draftMirror = newText
draftEdited?(newText)
},
caretHint: flipBackCaret,
dropBridge: gate.proseDrop,
routeDrop: { gate.routeFileDrop($0) },
// #162: the Cold Turkey word feed.
onTextChange: { gate.writingLock.feed(text: $0) },
)
}
}
// 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 = FixCardRevealRequest(range: NSRange(location: caret ?? readingState.topSourceLocation ?? 0, length: 0), token: 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 {
// #ui-r6 (mercury#51): one 10pt rhythm across the fixed pairs —
// Read→crumb read ~7 (default stack spacing) against Publish→
// Saved's ~18 (spacing + the old trailing padding); the spacer
// stays the only flexible gap.
HStack(spacing: 10) {
// #68: labeled toggle, far left, before the crumb.
// #ui-r5 (mercury#22): same geometry family as Publish —
// BorderedSecondaryButtonStyle(28): one height (28) and one
// corner radius (8) across the editor toolbar; content is the
// only difference. (Run Pass lives in MentorPaneView —
// cross-file, intentionally untouched; its 28pt height now
// matches, its accent fill marks the primary action.)
Button(reading ? "Edit" : "Read") { toggleReading() }
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
.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()
// #33 (S6.1): the publish entry — draft first, then publish.
if let publish {
// #ui-r4 (argon#46): the bordered mono-11 pill — the action
// reads distinct from the passive "Saved" status beside it.
// #ui-r6: no trailing padding — the stack's 10pt spacing is
// the whole Publish→Saved gap (was 10+8 ≈ 18).
Button("Publish") { publish() }
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
.help("Send to Micro.blog — draft first, then publish")
}
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)
}
}
.padding(.horizontal, 16)
// #90: align with the Posts header and mentor header at the
// export's 52px pane-head height.
.frame(minHeight: 52)
}
private func saveNow() {
if let session {
session.flush()
} else {
draftSave?()
}
}
private var crumb: String {
if let session {
if let fileURL = session.fileURL {
// #92: the external guest — the crumb shows the file name in
// the same muted mono style.
return fileURL.lastPathComponent
}
if session.postID != nil {
return "\(session.folderURL.pathComponents.suffix(4).joined(separator: " / "))"
}
}
return "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 .changed: "Changed"
case .failed: "Save failed"
}
}
}
// MARK: - TextKit2 surface (the lifted spike pane)
/// #141: the window-level SwiftUI destination's handle down to the live
/// prose text view (weak — dies with the editor surface).
@MainActor
final class ProseDropBridge {
weak var textView: ProseListTextView?
}
/// 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/#204: `caretHint` (range + token) lands a bare caret after a flip
/// back from reading or SELECTS a card's anchor span after a Jump — applied
/// once per token, after any generation load.
struct ProseTextView: NSViewRepresentable {
var session: EditorSession?
var draft: String?
var onEdit: ((String) -> Void)?
/// #162: the Cold Turkey feed — whole-document text on every edit,
/// both modes (session + draft). No-op at rest; the lock's word
/// count rides the same keystroke the editor already emits.
var onTextChange: ((String) -> Void)?
var spellChecking = false
/// #21: focus mode — the text ground joins the workspace background.
var focused = false
var caretHint: FixCardRevealRequest?
/// #141: the piece folder dropped images ingest into — saved posts
/// only (drafts have no folder until first save; the external guest
/// isn't a piece). Nil = image drags refuse loudly.
var ingestFolder: URL?
/// #141: the window-level SwiftUI destination's handle to the live
/// view (drops landing OUTSIDE the editor); the gate's router for drops
/// landing ON it — both handed down from the gate at both call sites.
var dropBridge: ProseDropBridge
var routeDrop: ([URL]) -> Bool
init(
session: EditorSession,
spellChecking: Bool = false,
focused: Bool = false,
caretHint: FixCardRevealRequest? = nil,
dropBridge: ProseDropBridge,
routeDrop: @escaping ([URL]) -> Bool,
onTextChange: ((String) -> Void)? = nil,
) {
self.session = session
self.spellChecking = spellChecking
self.focused = focused
self.caretHint = caretHint
self.onTextChange = onTextChange
ingestFolder = session.postID != nil ? session.folderURL : nil
self.dropBridge = dropBridge
self.routeDrop = routeDrop
}
init(
draft: String,
spellChecking: Bool = false,
focused: Bool = false,
onEdit: @escaping (String) -> Void,
caretHint: FixCardRevealRequest? = nil,
dropBridge: ProseDropBridge,
routeDrop: @escaping ([URL]) -> Bool,
onTextChange: ((String) -> Void)? = nil,
) {
self.draft = draft
self.spellChecking = spellChecking
self.focused = focused
self.onEdit = onEdit
self.caretHint = caretHint
self.onTextChange = onTextChange
self.dropBridge = dropBridge
self.routeDrop = routeDrop
}
/// 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
}
/// #ui-r1 (sol#14/argon#28): a document may open with leading blank
/// lines (Post.scan's title rule skips them) — a programmatic caret at
/// location 0 then rests inside the invisible 9pt blank fragment ABOVE
/// the title, rendering as a detached terracotta stroke at the canvas
/// top. Programmatic landings (cursor restore, reading flip-back) hop
/// over leading blanks to the first content line — zero-length landings
/// only, a #204 span never hops (`landingSpan`); interactive placements
/// (click, drag, typing) never route through here.
static func caretPastLeadingBlanks(_ location: Int, in text: String) -> Int {
max(location, ProsePresenter.firstContentLocation(text as NSString) ?? location)
}
/// Where a caret-hint lands, clamped to the text: a zero-length range
/// (#71 flip-back) is a bare caret and hops past leading blanks; a
/// non-zero range (#204 jump) SELECTS the anchor exactly where it
/// resolved — a quote that IS the leading blanks selects those blanks,
/// never the title (the load restore gates its hop the same way).
static func landingSpan(for hint: FixCardRevealRequest, in text: String) -> NSRange {
let length = (text as NSString).length
let start = hint.range.length == 0 ? caretPastLeadingBlanks(max(0, hint.range.location), in: text) : max(0, hint.range.location)
let loc = min(start, length)
return NSRange(location: loc, length: min(max(0, hint.range.length), length - loc))
}
func makeNSView(context: Context) -> NSScrollView {
let tv = ProseListTextView() // #115: list shortcuts + folds on the plain surface
tv.ingestFolder = ingestFolder // #141: image-drop ingest (nil on drafts/guests)
dropBridge.textView = tv // #141: the window destination's handle
tv.onFileDrop = routeDrop // #141: the view's own drag handlers route here
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
// #77: squiggles follow the posture toggle (default off).
tv.isContinuousSpellCheckingEnabled = spellChecking
tv.usesFindBar = true
// #21/#89: page ground — surface (cream page) unfocused, chrome in
// focus. One editing color + one focus color, nothing hardcoded.
tv.backgroundColor = focused ? NSColor(DesignTokens.background) : NSColor(DesignTokens.surface)
// #89: accent caret — findable, matches the app's rust.
tv.insertionPointColor = NSColor(DesignTokens.accent)
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
// #ui-r2 (sol#10/argon#19): top padding so the title anchors the
// page instead of floating against the chrome (r1: 20, r2: 40;
// #ui-r4 mercury#24: 46 — ~6pt more clearance from the toolbar
// hairline). The typewriter inset machinery overwrites this on
// its own syncs — that stays untouched; this is the open-state
// anchor.
tv.textContainerInset = NSSize(width: 0, height: 46)
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 = focused ? NSColor(DesignTokens.background) : NSColor(DesignTokens.surface)
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? ProseListTextView else { return }
// #77: posture toggle while editing — cheap idempotent set.
tv.isContinuousSpellCheckingEnabled = spellChecking
tv.ingestFolder = ingestFolder // #141: cheap idempotent set
dropBridge.textView = tv // #141: idempotent re-point
tv.onFileDrop = routeDrop // #141: idempotent re-point
// #21: the ground follows focus in/out without a remount.
let ground = focused ? NSColor(DesignTokens.background) : NSColor(DesignTokens.surface)
tv.backgroundColor = ground
scroll.backgroundColor = ground
// #21 calibration amendment: typewriter inset is editor-wide now —
// every editing surface gets the breathing room, focus or not.
CaretCentering.syncTypewriterInset(textView: tv)
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)
tv.refreshFolds() // #115: re-key folds over the swapped content
// #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)
// #ui-r1: a caret restored into leading blanks renders as the
// detached stroke above the title — hop to the first content line.
if cursor.selectionLength == 0 {
cursor.selectionLocation = Self.caretPastLeadingBlanks(cursor.selectionLocation, in: tv.string)
}
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))
tv.refreshFolds() // #115: re-key folds over the swapped content
}
// #71 flip-back caret / #204 jump span — apply once per token, after any load above.
if let hint = caretHint, context.coordinator.appliedCaretToken != hint.token {
context.coordinator.applyCaretHint(hint, tv: tv, session: session)
}
}
func makeCoordinator() -> Coordinator {
Coordinator(representable: self)
}
final class Coordinator: NSObject, NSTextViewDelegate {
let onEdit: ((String) -> Void)?
/// #162: the Cold Turkey feed (see the representable's property).
let onTextChange: ((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
onTextChange = representable.onTextChange
}
/// The caret rail's landing (#71 flip-back, #204 jump). Called by the
/// representable once per token.
func applyCaretHint(_ hint: FixCardRevealRequest, tv: NSTextView, session: EditorSession?) {
appliedCaretToken = hint.token
let landing = ProseTextView.landingSpan(for: hint, in: tv.string)
tv.setSelectedRange(landing)
// ponytail: same layout race as the cursor-restore scroll — 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
guard let tv else { return }
// #204: a jump (span > 0) comes from the palette window, which
// holds key after the click — make the main window key or the
// first responder never sees keystrokes. The #71 flip-back
// (span 0) is already in the key window; untouched.
if landing.length > 0 {
tv.window?.makeKeyAndOrderFront(nil)
}
tv.scrollRangeToVisible(landing)
tv.window?.makeFirstResponder(tv)
// Recorded AFTER the scroll: the sidecar's scrollOffset must be
// the landed one, or a reopen restores an off-screen selection.
session?.cursorUpdate(ProseTextView.cursorState(of: tv))
}
}
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
// #21: soft caret centering — typing only, never scrollback or
// drag-selection (the reader never gets fought). Calibration
// amendment: editor-wide, no longer focus-gated.
CaretCentering.centerCaretWhileTyping(textView: tv)
if let sessionRef {
sessionRef.edit(storage.string)
} else {
onEdit?(storage.string)
}
// #162: the lock's word count rides the same keystroke.
onTextChange?(storage.string)
// #115: fold maintenance LAST — hidden styling over the refreshed presentation.
(tv as? ProseListTextView)?.refreshFolds()
}
func textViewDidChangeSelection(_ notification: Notification) {
guard let tv = notification.object as? NSTextView, let sessionRef else { return }
sessionRef.cursorUpdate(ProseTextView.cursorState(of: tv))
}
}
}