Map #20 execution child, built per decisions #68/#69/#70: - ReadingPresenter: block-aware renderer (ADR-0010 stance) — blank-line split, one block per chunk; lists (bullets + ordered + nesting + auto-renumber via per-level counters — one rendering path), headings by level (h1 = slot size, h2 = 0.77x, ### = body+1, #### floors at bold body), HR via the editing syntaxOnly predicate, fenced code, blockquotes (QuoteTextBlock hairline), tables (NSTextTable 1px border, delimiter-row alignment), images (hover payload), links styled + retained. Footnotes stay fallback. Source ranges ride every block (click→edit map). - ReadingSurface: read-only selectable NSTextView canvas (#68: a presentation of the same TextKit2 document). Tap with no selection after mouseDown returns = edit intent at the clicked block (the tracking-loop fix); ⌘-click opens links; scroll tracking feeds the flip-back caret; image hover NSPopover loads off-main. - ProseTypography (#70): three role slots — Body / Headings / Code — each {face, size}, UserDefaults six values, member-based font resolution (family+weight lookup misresolves Concourse Book→Thin), silent system fallback; both prose surfaces read them; editing presenter's headings + dimmed syntax rewired through the slots. - PostEditorView: Read⇄Edit toolbar button (far left) + View menu "Toggle Reading Mode" + ⌘R; reading state transient per open; drafts included (draft mirror); flip-back caret hint applied once per token. - SettingsPaneView: Typography section — three slot rows (family picker incl. current face not in the installed list + size field). - kitchen-sink.md (+png): corpus piece exercising constructs absent from the eight posts, per #69. Verified: 94 unit tests (renderer classification, renumbering, source ranges, fallbacks) + UI smoke; PERF-3k renders 128 blocks in ~17 ms; live-app probe — Read renders kitchen-sink markers-hidden, renumbered, byte-stable file after full round-trip; click-to-edit flips at the clicked paragraph; typography ladder pixel-verified (20/15 ink px).
166 lines
5.4 KiB
Swift
166 lines
5.4 KiB
Swift
//
|
|
// 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
|
|
|
|
/// The post's folder (`<home>/posts/<id>`) — reading resolves relative
|
|
/// image URLs against it (#71).
|
|
var folderURL: URL {
|
|
home.appendingPathComponent("posts", isDirectory: true)
|
|
.appendingPathComponent(postID, isDirectory: true)
|
|
}
|
|
|
|
/// 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
|
|
}
|
|
}
|