feat(editor): land editor core — open, edit, autosave (S1.2)
CI / ci (push) Canceled after 0s
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:
1 parent
530f852f75
commit
f2953ee07e
13 files changed
+893
-87
No files matched your search
@@ -178,6 +178,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
|
||||
<!-- write-log: window-start -->
|
||||
| Date | Log |
|
||||
|------|-----|
|
||||
| 2026-10-03 | [20261003-issue19-editor-core_log.md](docs/devlog/20261003-issue19-editor-core_log.md) |
|
||||
| 2026-10-03 | [20261003-issue18-post-lifecycle_log.md](docs/devlog/20261003-issue18-post-lifecycle_log.md) |
|
||||
| 2026-10-01 | [20261001-issue17-home-posts-list_log.md](docs/devlog/20261001-issue17-home-posts-list_log.md) |
|
||||
| 2026-10-01 | [20261001-issue55-verdict-substrate-adr-0010_log.md](docs/devlog/20261001-issue55-verdict-substrate-adr-0010_log.md) |
|
||||
|
||||
@@ -6,6 +6,7 @@ All notable changes to this project will be documented in this file. The format
|
||||
|
||||
### Added
|
||||
|
||||
- **editor:** M1 editor core (PRD S1.2) — posts open into a native TextKit2 editing surface (ADR-0010 mode B): styled source with scaled headings, paragraph spacing, and dimmed markdown syntax lifted from the proven spike; ~1 s debounced autosave with flush on selection change, window close, and app quit (⌘S stays immediate); a Saved → Saving… → Saved dot that turns accent on failure; cursor position and scroll restored across restarts via a per-post `.museion-state.json` sidecar that dies with the folder on Trash; and an explicit "File on Disk changed — Reload / Keep Local" alert on external edits, never a silent clobber (issue #19)
|
||||
- **workspace:** M1 Post lifecycle (PRD S1.1) — Posts are now writable end to end: New Post holds an in-memory draft (no folder until first save), ⌘S lazily materializes `posts/<slug>/post.md` stamped with flat frontmatter (`pass_state: First Draft`, `origin: writer`), the slug is the Title's (lowercased, diacritic-folded, CJK-keeping) form with case-insensitive `-2`/`-3` collision suffixes, Explicit Rename retitles the `# Title` line and moves the folder (file stays `post.md`), and Delete moves the folder to the Trash; a recursive FSEvents watcher keeps the list mirroring `posts/` (external Finder edits included), and a plain-TextEditor stub stands in for the S1.2 editor (issue #18)
|
||||
- **workspace:** M1 Home & Posts list (PRD S1.1) — the post-gate main surface is now the workspace shell from the design contract: nav rail (Posts, Sessions, Learnings, Settings), a Posts pane that mirrors the Museion Home's `posts/` folder on disk (Pass State groups, origin meta, empty state, lazy folders skipped), a Settings pane where the Home can be repointed (repoint-only — Museion never moves content; NSOpenPanel picker, UserDefaults persistence, default `~/Documents/Museion`), and placeholder panes for Sessions/Learnings until their milestones; the M0 mentor pane becomes the workspace's fourth column (issue #17)
|
||||
|
||||
|
||||
+3
-3
@@ -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.
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ Owned by the root AGENTS.md contract.
|
||||
- `ProfileProvisionerTests.swift` extends it: the fake creates the profile at `<binaryDir>/profiles/<name>` (self-locating, race-free under parallel tests); payload dirs are built at runtime; the bundled-payload test asserts manifest ↔ payload correspondence. #48 failure-path tests live in `ProfileProvisionerFailureTests.swift` (own file — Not-Now defer + re-fail, config.yaml byte-identity + fresh-profile no-config (mcp_servers negative invariant), state.json engine-gate-only, copy-phase catch branch, path-traversal rejection, orphaned-temp sweep). Shared helpers (`makeFakeHermes`, `makePayload`, `defaultSkills`, `provTempDir`) are internal in `ProfileProvisionerTests.swift`. `ProfileBackupTests.swift` (own helpers `backupTempDir`/`makeProfileFixture`) injects profile/backups roots, a fixed clock, and a `psScan` stub — a dev machine may run the real engine, so the ps scan is never trusted in tests.
|
||||
- `PostLibraryTests.swift` (#17) — throwaway Homes via `makeHome`/`writePost` in temp dirs: bare corpus posts (First Draft/writer defaults), lenient + quoted frontmatter (`pass_state`/`origin`), lazy folders / hidden dirs / symlinks / noise not surfacing, localizedStandardCompare title sort, `untitled` edges (blank, marker-only, unterminated frontmatter), leading-blank-line frontmatter, default Home = `~/Documents/Museion`.
|
||||
- `PostStoreTests.swift` (#18) — write side via `storeHome`/`readPost` (same temp-dir pattern): slug algorithm cases (diacritics, CJK, cap, punctuation-only → untitled), lazy first write + #59 stamp round-trip through `Post.scan`, untitled fallback, case-insensitive collision suffixes, rename (retitle + move, insert-title path, same-slug retitle-only, collision -2), trash removes from posts/, overwrite preservation + bare-post normalization, `readBody` stripping, blocked-posts failure path.
|
||||
- `EditorSessionTests.swift` (#19) — session mechanics via `makeSessionHome`/`seedPost`: debounce → flush + sidecar round-trip, clean-flush no-op + ⌘S immediate, #67 conflict (echo suppressed, Yes-reload, No-keep-local → overwrite), write failure → `.failed` + retry.
|
||||
|
||||
## Verification
|
||||
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
//
|
||||
// EditorSessionTests.swift
|
||||
// Museion
|
||||
//
|
||||
// #19 (S1.2): one runnable check per piece of session logic — debounce →
|
||||
// flush, save-state transitions, sidecar round-trip + Trash death, conflict
|
||||
// alert (echo suppression, Yes-reload, No-keep-local).
|
||||
//
|
||||
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
private func makeSessionHome() -> URL {
|
||||
let dir = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("museion-editor-\(UUID().uuidString)", isDirectory: true)
|
||||
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
||||
return dir
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func seedPost(_ home: URL, id: String, body: String) {
|
||||
let dir = home.appendingPathComponent("posts/\(id)", isDirectory: true)
|
||||
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
||||
try? PostStore.stamped(body: body, passState: .firstDraft, origin: .writer)
|
||||
.write(to: dir.appendingPathComponent("post.md"), atomically: true, encoding: .utf8)
|
||||
}
|
||||
|
||||
@Suite(.serialized)
|
||||
@MainActor
|
||||
struct EditorSessionTests {
|
||||
@Test func `debounce flushes after idle and stamps the sidecar`() async throws {
|
||||
let home = makeSessionHome()
|
||||
seedPost(home, id: "alpha", body: "# Alpha\n\nOne.")
|
||||
let session = EditorSession(postID: "alpha", home: home, debounce: .milliseconds(50))
|
||||
|
||||
#expect(session.saveState == .saved)
|
||||
session.edit("# Alpha\n\nOne. Two.")
|
||||
#expect(session.saveState == .saved) // still inside the debounce window
|
||||
|
||||
try await Task.sleep(for: .milliseconds(200))
|
||||
#expect(session.saveState == .saved) // saved → Saving… → Saved lands here
|
||||
#expect(PostStore.readBody(id: "alpha", home: home) == "# Alpha\n\nOne. Two.")
|
||||
|
||||
// Sidecar: written on flush, reads back.
|
||||
let cursor = PostStore.CursorState(selectionLocation: 3, selectionLength: 2, scrollOffset: 128)
|
||||
session.cursorUpdate(cursor)
|
||||
session.edit("# Alpha\n\nOne. Two. Three.")
|
||||
try await Task.sleep(for: .milliseconds(200))
|
||||
let restored = PostStore.readCursor(id: "alpha", home: home)
|
||||
#expect(restored == cursor)
|
||||
}
|
||||
|
||||
@Test func `flush is a no-op when clean and immediate when dirty via command-S path`() {
|
||||
let home = makeSessionHome()
|
||||
seedPost(home, id: "beta", body: "# Beta\n\nBody.")
|
||||
let session = EditorSession(postID: "beta", home: home)
|
||||
|
||||
// Clean: flush does nothing (no throw, no write churn).
|
||||
session.flush()
|
||||
#expect(session.saveState == .saved)
|
||||
|
||||
// Dirty + immediate flush (⌘S) — disk updated synchronously.
|
||||
session.edit("# Beta\n\nChanged.")
|
||||
session.flush()
|
||||
#expect(PostStore.readBody(id: "beta", home: home) == "# Beta\n\nChanged.")
|
||||
}
|
||||
|
||||
@Test func `external change alerts, echo suppressed; Yes reloads, No keeps local`() throws {
|
||||
let home = makeSessionHome()
|
||||
seedPost(home, id: "gamma", body: "# Gamma\n\nOriginal.")
|
||||
let session = EditorSession(postID: "gamma", home: home)
|
||||
|
||||
// Watcher echo of our own write: disk == lastFlushedText → no alert.
|
||||
session.edit("# Gamma\n\nMine now.")
|
||||
session.flush()
|
||||
session.diskDidChange(diskText: "# Gamma\n\nMine now.")
|
||||
#expect(!session.conflictAlert)
|
||||
|
||||
// Genuine external edit → alert.
|
||||
try PostStore.overwrite(id: "gamma", body: "# Gamma\n\nExternal.", home: home)
|
||||
session.diskDidChange(diskText: "# Gamma\n\nExternal.")
|
||||
#expect(session.conflictAlert)
|
||||
|
||||
// Yes-reload: text = disk, load generation moved (surface reloads).
|
||||
session.reloadFromDisk()
|
||||
#expect(!session.conflictAlert)
|
||||
#expect(session.text == "# Gamma\n\nExternal.")
|
||||
#expect(session.loadGeneration == 1)
|
||||
|
||||
// Second external edit → No: keep local; next flush overwrites.
|
||||
try PostStore.overwrite(id: "gamma", body: "# Gamma\n\nNewer external.", home: home)
|
||||
session.diskDidChange(diskText: "# Gamma\n\nNewer external.")
|
||||
#expect(session.conflictAlert)
|
||||
session.keepLocal()
|
||||
#expect(!session.conflictAlert)
|
||||
#expect(session.text == "# Gamma\n\nExternal.") // local kept
|
||||
session.edit("# Gamma\n\nLocal wins.")
|
||||
session.flush()
|
||||
#expect(PostStore.readBody(id: "gamma", home: home) == "# Gamma\n\nLocal wins.")
|
||||
}
|
||||
|
||||
@Test func `write failure flips saveState to failed and retries on next flush`() throws {
|
||||
let home = makeSessionHome()
|
||||
seedPost(home, id: "delta", body: "# Delta\n\nBody.")
|
||||
let session = EditorSession(postID: "delta", home: home)
|
||||
|
||||
// Vanish the post: overwrite throws (no resurrection), state = failed.
|
||||
try FileManager.default.removeItem(
|
||||
at: home.appendingPathComponent("posts/delta", isDirectory: true),
|
||||
)
|
||||
var reported: String?
|
||||
session.onError = { reported = $0 }
|
||||
session.edit("# Delta\n\nOrphan.")
|
||||
session.flush()
|
||||
#expect(session.saveState == .failed)
|
||||
#expect(reported != nil)
|
||||
|
||||
// Next flush retries (still failed until the post returns).
|
||||
session.flush()
|
||||
#expect(session.saveState == .failed)
|
||||
}
|
||||
|
||||
@Test func `debounce does not clobber while the conflict alert is unanswered`() async throws {
|
||||
let home = makeSessionHome()
|
||||
seedPost(home, id: "epsilon", body: "# Epsilon\n\nMine.")
|
||||
let session = EditorSession(postID: "epsilon", home: home, debounce: .milliseconds(50))
|
||||
|
||||
// External change lands mid-typing → alert up; debounce must hold fire.
|
||||
session.edit("# Epsilon\n\nMy newer local.")
|
||||
try PostStore.overwrite(id: "epsilon", body: "# Epsilon\n\nExternal.", home: home)
|
||||
session.diskDidChange(diskText: "# Epsilon\n\nExternal.")
|
||||
#expect(session.conflictAlert)
|
||||
|
||||
try await Task.sleep(for: .milliseconds(200)) // debounce window passes
|
||||
#expect(PostStore.readBody(id: "epsilon", home: home) == "# Epsilon\n\nExternal.") // external edit intact
|
||||
#expect(session.saveState == .saved)
|
||||
|
||||
// Keep Local → next explicit flush overwrites (the writer's choice).
|
||||
session.keepLocal()
|
||||
session.flush()
|
||||
#expect(PostStore.readBody(id: "epsilon", home: home) == "# Epsilon\n\nMy newer local.")
|
||||
}
|
||||
|
||||
@Test func `teardown flushFirst writes pending edits and cancels the debounce`() async throws {
|
||||
let home = makeSessionHome()
|
||||
seedPost(home, id: "zeta", body: "# Zeta\n\nBase.")
|
||||
let session = EditorSession(postID: "zeta", home: home, debounce: .milliseconds(50))
|
||||
|
||||
// flushFirst=true: pending text lands (rename reads disk next).
|
||||
session.edit("# Zeta\n\nReworked.")
|
||||
session.teardown(flushFirst: true)
|
||||
#expect(PostStore.readBody(id: "zeta", home: home) == "# Zeta\n\nReworked.")
|
||||
|
||||
// flushFirst=false (trash path): the armed debounce never fires.
|
||||
session.edit("# Zeta\n\nDoomed.") // session dropped by owner after teardown; debounce armed
|
||||
session.teardown(flushFirst: false)
|
||||
try await Task.sleep(for: .milliseconds(200))
|
||||
#expect(PostStore.readBody(id: "zeta", home: home) == "# Zeta\n\nReworked.") // unwritten
|
||||
#expect(session.saveState != .failed) // no spurious failure fired
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
# Issue 19 — M1 editor core: open, edit, autosave (S1.2)
|
||||
|
||||
> **Date:** 2026-10-03
|
||||
> **Type:** issue
|
||||
> **Reference:** [Wayfinder map #19](https://git.babylondreams.de/AlexKucera/Museion/issues/19) · decisions [#63](https://git.babylondreams.de/AlexKucera/Museion/issues/63)–[#67](https://git.babylondreams.de/AlexKucera/Museion/issues/67)
|
||||
|
||||
## Goal
|
||||
|
||||
Implement the editor core per the #19 wayfinder map's five decisions: TextKit2 editing surface (ADR-0010 mode B, lifted from `spike/textkit2/`), ~1 s debounced autosave with flush on selection change / window close / app quit / ⌘S (#64), Saved→Saving…→Saved indicator with failure state (#65), cursor-state sidecar `posts/<id>/.museion-state.json` (#66), and the explicit external-change alert (#67). Replaces the #18 stub in place.
|
||||
|
||||
## What Was Done
|
||||
|
||||
- `Museion/ProsePresenter.swift` (new) — the spike's presenter lifted, verbatim modulo lint renames: line-kind → attribute map (Iowan Old Style 17 body / 26-20 bold headings / quote spacing / `***`-rule), dimmed syntax (marker prefixes + inline marks, mono 13), `attribute` full-doc + `reattribute` per-paragraph. Anchor search NOT lifted — M2 (#25) per the map's out-of-scope.
|
||||
- `Museion/EditorSession.swift` (new) — @MainActor @Observable session per open post. `edit` re-arms a configurable ~1 s debounce; `flush` = `PostStore.overwrite` + sidecar write, tracks `saveState`; `diskDidChange(diskText:)` equality check (disk ≠ lastFlushed AND ≠ local) raises `conflictAlert`; `reloadFromDisk`/`keepLocal` implement the #67 Yes/No; failure → `.failed` + `onError` → `lastError`.
|
||||
- `Museion/PostStore.swift` — added `CursorState` (Codable: selectionLocation/selectionLength/scrollOffset) + `readCursor`/`writeCursor` on `posts/<id>/.museion-state.json`, atomic write; `bodyURL` helper.
|
||||
- `Museion/PostsModel.swift` — owns the session: `select(_:home:)` flushes the old session + opens a new one; `newPost` flushes first; rename/trash of the open post drops the session; `shutdown()` (app quit) flushes; rescan hands the session the open post's disk text (#67 check); `onError` routes into `lastError`.
|
||||
- `Museion/PostEditorView.swift` (new) — toolbar (crumb + `SaveStateDot` 6px dot, accent on failure; draft shows "⌘S saves"), `ProseTextView` NSViewRepresentable (plain store, presentation-only attributes, native undo/IME/find, 640pt measure, generation-keyed loads, clamped cursor restore, cursor push on selection change), window-close flush observer, the #67 alert (Reload / Keep Local).
|
||||
- `Museion/PostsPaneView.swift` — EditorStub deleted; editor column renders `PostEditorView` (session or draft); `select` call site passes `home`.
|
||||
- `MuseionTests/EditorSessionTests.swift` (new) — 4 tests: debounce→flush+sidecar round-trip, clean no-op + ⌘S immediate, #67 full matrix (echo suppressed / Yes / No→overwrite), write failure → failed + retry.
|
||||
|
||||
## Decisions & Rationale
|
||||
|
||||
| Decision | Rationale |
|
||||
|----------|-----------|
|
||||
| Lift the spike presenter verbatim | #63: already written, perf-proven (≤1.1 ms on PERF-3k); a plain surface first would touch every editor file twice. |
|
||||
| Session owns text; view loads keyed by `loadGeneration` | The NSTextView is the live editor; re-loading per keystroke would fight the first responder. Generation bumps only at open and Yes-reload. |
|
||||
| Watcher-echo suppression by text equality (no timer) | `diskText == lastFlushedText` is exact — our own writes never alert. A suppression timer is state that can drift. |
|
||||
| Sidecar write separate from content write, `try?` | #65/#66: a failed cursor write must never read as a failed content save. |
|
||||
| `keepLocal` = mark disk text as seen | #67 No means "next autosave overwrites" — that requires treating the current disk text as baseline, else the alert re-fires on every watcher tick. |
|
||||
| Drafts keep explicit ⌘S (no autosave, no sidecar) | #64 exempts drafts; #62's lazy-folder rule stands — stray New Post clicks never litter posts/. |
|
||||
| Esc on the conflict alert = Keep Local | Same semantics as No; the alert binding's set-false path calls `keepLocal()`. |
|
||||
|
||||
## Gotchas & Fixes
|
||||
|
||||
| Problem | Root Cause | Fix |
|
||||
|---------|------------|-----|
|
||||
| Build errors: AnyCancellable vs NSObjectProtocol, CGFloat?→Double?, ambiguous `.greatestFiniteMagnitude`, `Self.cursorState` | Straight port slips | Explicit types (`AnyCancellable?`, `Double(...)`, `CGFloat.greatestFiniteMagnitude`, `ProseTextView.cursorState`) |
|
||||
| Draft-mode reload on own keystroke | `updateDraft` round-trips text through the model → updateNSView saw changed `draft` | Echo guard: compare `tv.string != draft` (reload only on genuine divergence) |
|
||||
| SwiftLint identifier_name/line_length on lifted spike code | Spike package had no lint gate; app target does | Renamed `t`→`trimmedLine`, `p`→`style`, `ns`→`nsText`, `ch/c`→`codeUnit/scalar`; extracted `headingFont(size:weight:)` |
|
||||
| SwiftFormat mid-session reformats colliding with patches | Format ran between write and patch | Re-read → full-file rewrite where collided (ProsePresenter); verify with `git status` after every format run |
|
||||
| Visual verification blocked | A fullscreen game owns the display; window-scoped capture returns empty for offscreen windows | Skipped pixels; verified by build + 77 unit tests + 1 UI smoke test + live launch staying alive |
|
||||
| [audit] Rename/trash of the open post dropped the session unflushed; armed debounce then fired at the moved/dead path → edits lost + spurious "file doesn't exist" error | No teardown path — `select`/`newPost` flushed, rename/trash/vanish didn't | `EditorSession.teardown(flushFirst:)`: flush before rename's disk read; cancel-only on trash/vanish; all four owners route through it |
|
||||
| [audit] First ⌘S on a draft left the editor blank | `saveDraft` set `selectedPostID` but no session; the editor column branches on `model.session` | `saveDraft` now opens `EditorSession(postID:)` on success — typing continues in place |
|
||||
| [audit] Debounce overwrote an external edit while its #67 alert was unanswered | `flush()` had no conflict guard | Debounce task checks `conflictAlert` before flushing; only explicit ⌘S overwrites mid-alert |
|
||||
| [audit] Rescan's #67 disk read ran on the main actor | `readBody` sat after the detached scan | Folded into the same `Task.detached` — scan + open-post read return together |
|
||||
| [audit] Dead code: `saveSelected`, `bodyURL`, unused `home` plumbing, write-only `draftText`, no-op `removeObserver(AnyCancellable)`, unused `.receive(on:)`, unreachable quote-spacing branch, `writeCursor`'s `throws` | Reviewer fanout (ponytail-review) | All deleted/folded (~-35 lines, zero behavior change) |
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change Summary |
|
||||
|------|---------------|
|
||||
| `Museion/ProsePresenter.swift` | new — lifted spike presenter (line-kind attributes, dimmed syntax) |
|
||||
| `Museion/EditorSession.swift` | new — debounce/flush/save-state/conflict session model |
|
||||
| `Museion/PostEditorView.swift` | new — TextKit2 surface + toolbar + widget + conflict alert |
|
||||
| `Museion/PostStore.swift` | + `CursorState` sidecar read/write (atomic, best-effort) |
|
||||
| `Museion/PostsModel.swift` | session ownership: select/newPost/rename/trash/shutdown/rescan wiring |
|
||||
| `Museion/PostsPaneView.swift` | EditorStub deleted; PostEditorView rendered; select passes home |
|
||||
| `MuseionTests/EditorSessionTests.swift` | new — 6 session-mechanics tests (debounce+sidecar, ⌘S, #67 matrix, failure retry, conflict-holds-debounce, teardown) |
|
||||
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX pass: editor-core section replaces stub bullets |
|
||||
|
||||
## Open Items & Next Steps
|
||||
|
||||
- [ ] #20 — reading toggle + iterative presentation polish (now narrowed: presenter landed here)
|
||||
- [ ] #21 — focus mode, centered measure (surface already uses a 640pt measure)
|
||||
- [ ] #25 (M2) — Fix-Card anchor highlight + stale-anchor alert in the real editor (spike proved the mechanics; `anchorRange` stays unlifted)
|
||||
- [ ] Visual pass on the editor once the machine's display is free (typography stance per ADR-010's "paper-grade polish" consequence)
|
||||
- [ ] Commit + push pending explicit authorization per repo policy
|
||||
|
||||
---
|
||||
|
||||
*Log written by write-log skill*
|
||||
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
|
||||
<!-- write-log: full-index -->
|
||||
| Date | Type | File | Summary |
|
||||
|------|------|------|---------|
|
||||
| 2026-10-03 | issue | [20261003-issue19-editor-core_log.md](20261003-issue19-editor-core_log.md) | #19 editor core: TextKit2 surface lifted, debounced autosave, save dot, cursor sidecar, conflict alert — 81 tests green |
|
||||
| 2026-10-03 | issue | [20261003-issue18-post-lifecycle_log.md](20261003-issue18-post-lifecycle_log.md) | #18 shipped + audits: Post write side, FSEvents watcher, editor stub — 75 tests green |
|
||||
| 2026-10-01 | issue | [20261001-issue17-home-posts-list_log.md](20261001-issue17-home-posts-list_log.md) | #17 shipped + finish-audit: workspace shell, Posts mirror, Home repoint — 56 tests green |
|
||||
| 2026-10-01 | issue | [20261001-issue55-verdict-substrate-adr-0010_log.md](20261001-issue55-verdict-substrate-adr-0010_log.md) | #55 + map #16 closed: TextKit2 mode B wins, ADR-0010 drafted, typography/rendering stances locked |
|
||||
|
||||
Reference in new issue
Block a user