Merge branch 'wayfinder/71-reading-toggle' into wayfinder/76-apex-html-reading

This commit is contained in:
AlexKucera committed 2026-10-06 17:51:58 +02:00
commit fffcb0a059
18 files changed
+1771 -46

No files matched your search

+1
View File
@@ -5,3 +5,4 @@ DerivedData/
.DS_Store
CLAUDE.md
.claude/
profraw
+1
View File
@@ -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-05 | [20261005-issue71-reading-toggle_log.md](docs/devlog/20261005-issue71-reading-toggle_log.md) |
| 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) |
+4
View File
@@ -44,6 +44,10 @@ _Avoid_: convert, migrate
The authorship record of a Post: writer or ai. Immutable; only writer-origin First Drafts are ever stats-eligible.
_Avoid_: source, mode
**Reading Mode**:
The rendered presentation of a Piece's text: view-and-select, never editing. Toggled explicitly; clicking the text drops into editing at that spot. Distinct from a Pass, which critiques rather than presents.
_Avoid_: preview, read mode
### The Mentor Loop
**Mentor**:
+4 -3
View File
@@ -25,9 +25,10 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- `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); 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).
- 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); `folderURL` exposes `posts/<id>/` for reading image resolution (#71). `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, above the surface swap (shows while reading too). `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. Typography section (#71/#70): three role slots — Body / Headings / Code — each a `SlotRow` (family Picker over all installed families with the current faces prepended — `availableFontFamilies` omits e.g. Iowan Old Style — plus a size field), UserDefaults-backed, re-picking is reset.
- Reading mode (#71 / S1.2, map #20; decisions #68/#69/#70): `ReadingPresenter.swift` — the reading renderer, pure over its input: blank-line split → one block per chunk; classification order HR (editing's `syntaxOnly` predicate) → list run → quote run → flow (heading/fence/table/paragraph); lists render bullets + ordered in ONE path (per-level sequential counters make `1. 1. 1.` → 1, 2, 3 — glyphs only, file never rewritten); nesting by indent (0–1 sp → L1, 2–3 → L2, 4+ → L3+); headings h1 = Headings slot size, h2 = 0.77×, ### = body+1, #### floors at bold body; fenced code mono; blockquotes via `QuoteTextBlock` (hairline draw override), HR via `RuleTextBlock`; tables via `NSTextTable` (1px border, delimiter-row alignment honored); images ride alone as hover-payload blocks (URL recovered at chunk level — the inline parser renders `![alt](url)` as bare alt text); links styled + `.link` retained; footnotes the one fallback (source text); `document(for:resolvingImagesIn:)` concatenates blocks + `\n` separators into one storage with per-block `Bound{docRange, sourceRange, imageURL}` — the click→edit and scroll maps. `ReadingSurface.swift` — `ReadingCanvasView` (read-only selectable NSTextView, 640pt measure, builds keyed by session `loadGeneration`/text): tap-to-edit runs AFTER `super.mouseDown` returns (NSTextView's tracking loop consumes the mouse-up — a `mouseUp` override never fires); single click + no selection + <4pt move = edit intent → `onEditIntent(sourceLocation)`; ⌘-click opens `.link` URLs; `reflectScrolledClipView` tracks the top visible block into `ReadingStateBox` (flip-back mapping); image hover NSPopover (`ImagePopoverView`, loads off-main). `PostEditorView` toggle (#68): Read⇄Edit toolbar button far left + View menu "Toggle Reading Mode" + ⌘R (`.toggleReadingMode` notification — SwiftUI CommandMenu posts, the visible editor listens); reading state transient per open (`@State reading`, no persistence — fresh open = editing); drafts included (`draftMirror`); entry mapping scrolls the caret's block to top; flip-back lands the caret via `caretHint(location, token)` applied once per token in `ProseTextView.updateNSView`. `ProseTypography.swift` (#70) — the three role slots: UserDefaults `proseBodyFace/Size`, `proseHeadingsFace/Size`, `proseCodeFace/Size` (defaults Concourse OT Book 17 / Iowan Old Style bold 26 / UbuntuMono Nerd Font Mono 13; registered in `AppGateState.init`); fonts resolve through the family MEMBER list (`availableMembers(ofFontFamily:)`, prefer Book/Regular style names, else closest to weight 5 — family+weight lookup misresolves Concourse: Thin and Book both advertise weight 4); missing face → silent system font; both prose surfaces + the editing presenter's headings/dimmed-syntax read the slots; chrome stays system faces.
- `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). `ProseTypography.registerDefaults()` rides the same init (#71).
- `MentorPaneView` no longer carries a root min-frame — it lives in the 356pt mentor column.
## Engine gate (launch gate, tickets #35–#41)
+7
View File
@@ -28,6 +28,13 @@ final class EditorSession {
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).
+9
View File
@@ -39,6 +39,8 @@ final class AppGateState {
.flatMap(URL.init(string:))
.flatMap { $0.isFileURL ? $0 : nil }
?? Self.defaultMuseionHome
// #70: the six prose-typography slot defaults.
ProseTypography.registerDefaults()
}
/// The default Home, absent a stored override — `~/Documents/Museion`
@@ -73,6 +75,13 @@ struct MuseionApp: App {
CommandGroup(replacing: .appInfo) {
OpenAboutButton()
}
// #68: View menu reading toggle — reaches the visible editor.
CommandMenu("View") {
Button("Toggle Reading Mode") {
NotificationCenter.default.post(name: .toggleReadingMode, object: nil)
}
.keyboardShortcut("r", modifiers: .command)
}
// #50: reveal the snapshots folder in Finder (restore = manual
// copy-back, documented in the bundled help doc).
CommandMenu("Help") {
+153 -14
View File
@@ -7,12 +7,23 @@
// 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 {
@@ -23,29 +34,58 @@ struct PostEditorView: View {
var draftSave: (() -> Void)?
@State private var closeObserver: AnyCancellable?
@State private var toggleObserver: AnyCancellable?
/// #68: reading is a transient act of inspection — no persistence; a
/// fresh open always lands in editing.
@State private var reading = false
/// Flip-back caret (#68): source location + a token so repeated flips to
/// the same location re-apply. Consumed by ProseTextView's coordinator.
@State private var flipBackCaret: (location: Int, token: Int)?
@State private var flipToken = 0
/// Reading scroll state (#68 mapping): entry caret + live top block.
@State private var readingState = ReadingStateBox()
/// Draft text mirror — reading renders it; edits flow back via onEdit.
@State private var draftMirror = ""
var body: some View {
VStack(spacing: 0) {
toolbar
Rectangle().fill(DesignTokens.border).frame(height: 1)
if let session {
ProseTextView(session: session)
if reading {
ReadingSurface(
text: renderText,
generation: session?.loadGeneration ?? 0,
postFolder: session?.folderURL,
entryCaretLocation: readingState.entryLocation,
onEditIntent: { loc in exitReading(caret: loc) },
stateBox: readingState,
)
} else {
ProseTextView(draft: draftText ?? "", onEdit: { draftEdited?($0) })
editingSurface
}
}
.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 {
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.
// #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() }
@@ -54,6 +94,43 @@ struct PostEditorView: View {
}
}
/// The text reading renders: live session text or the draft mirror.
private var renderText: String {
session?.text ?? draftMirror
}
@ViewBuilder
private var editingSurface: some View {
if let session {
ProseTextView(session: session, caretHint: flipBackCaret)
} else {
ProseTextView(draft: draftMirror, onEdit: { newText in
draftMirror = newText
draftEdited?(newText)
}, caretHint: flipBackCaret)
}
}
// MARK: Reading toggle (#68)
private func toggleReading() {
if reading {
exitReading(caret: nil)
} else {
// Entry mapping: the editing caret's block scrolls to the top.
readingState.entryLocation = session?.cursor.selectionLocation
reading = true
}
}
private func exitReading(caret: Int?) {
flipToken += 1
// Toggle-back maps the reading scroll back (top visible block);
// click-to-edit lands at the clicked paragraph (survives always).
flipBackCaret = (caret ?? readingState.topSourceLocation ?? 0, flipToken)
reading = false
}
/// Extracted binding (SwiftFormat/SwiftLint closure_position peace).
/// Dismissal without a button (Esc) = keep-local semantics, same as No.
private var conflictBinding: Binding<Bool> {
@@ -72,6 +149,9 @@ struct PostEditorView: View {
private var toolbar: some View {
HStack {
// #68: labeled toggle, far left, before the crumb.
Button(reading ? "Edit" : "Read") { toggleReading() }
.help(reading ? "Return to editing (⌘R)" : "Render this post (⌘R)")
Text(crumb)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
@@ -147,18 +227,27 @@ private struct SaveStateDot: View {
/// NSTextView in a scroll view; attributes are presentation-only over a plain
/// store. Session mode: edits → session.edit (debounce), cursor → session,
/// loads keyed by generation (open + Yes-reload). Draft mode: edits → onEdit.
/// #71: `caretHint` (location + token) lands the caret after a flip back
/// from reading — applied once per token, after any generation load.
struct ProseTextView: NSViewRepresentable {
var session: EditorSession?
var draft: String?
var onEdit: ((String) -> Void)?
var caretHint: (location: Int, token: Int)?
init(session: EditorSession) {
init(session: EditorSession, caretHint: (location: Int, token: Int)? = nil) {
self.session = session
self.caretHint = caretHint
}
init(draft: String, onEdit: @escaping (String) -> Void) {
init(
draft: String,
onEdit: @escaping (String) -> Void,
caretHint: (location: Int, token: Int)? = nil,
) {
self.draft = draft
self.onEdit = onEdit
self.caretHint = caretHint
}
/// Cursor state snapshot from the live view (#66).
@@ -181,7 +270,7 @@ struct ProseTextView: NSViewRepresentable {
tv.isAutomaticSpellingCorrectionEnabled = false
tv.usesFindBar = true
tv.backgroundColor = NSColor.white
tv.typingAttributes = ProsePresenter.bodyAttributes
tv.typingAttributes = ProseTypography.bodyAttributes
tv.delegate = context.coordinator
tv.layoutManager?.allowsNonContiguousLayout = true
tv.minSize = NSSize(width: 0, height: 0)
@@ -189,9 +278,11 @@ struct ProseTextView: NSViewRepresentable {
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
// Wrap to the editor column (#71 fix): the container tracks the view
// width — the fixed 640pt measure clipped in narrower columns.
tv.textContainer?.containerSize = NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude)
tv.textContainer?.widthTracksTextView = true
tv.textContainer?.lineFragmentPadding = 24
tv.textContainerInset = NSSize(width: 0, height: 20)
let scroll = NSScrollView()
scroll.documentView = tv
@@ -206,13 +297,24 @@ struct ProseTextView: NSViewRepresentable {
func updateNSView(_ scroll: NSScrollView, context: Context) {
guard let tv = scroll.documentView as? NSTextView else { return }
// Typography/flow knob changes arrive via the coordinator's
// UserDefaults observer (SwiftUI doesn't invalidate on defaults
// writes from another pane).
context.coordinator.watchDefaults(tv)
context.coordinator.appliedFlowKey = ProseTypography.flowKey
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))
context.coordinator.appliedFlowKey = ProseTypography.flowKey
// 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))
// #66: restore cursor (clamped) + scroll.
let length = (tv.string as NSString).length
var cursor = session.restoreCursor ?? PostStore.CursorState()
@@ -228,6 +330,18 @@ struct ProseTextView: NSViewRepresentable {
// only reload when the textview genuinely diverges (new draft).
tv.textStorage?.setAttributedString(ProsePresenter.attribute(draft))
}
// #71: flip-back caret — apply once per token, after any load above.
if let hint = caretHint, context.coordinator.appliedCaretToken != hint.token {
context.coordinator.appliedCaretToken = hint.token
let length = (tv.string as NSString).length
let loc = min(max(0, hint.location), length)
tv.setSelectedRange(NSRange(location: loc, length: 0))
tv.scrollRangeToVisible(NSRange(location: loc, length: 0))
tv.window?.makeFirstResponder(tv)
if let session {
session.cursorUpdate(ProseTextView.cursorState(of: tv))
}
}
}
func makeCoordinator() -> Coordinator {
@@ -239,6 +353,31 @@ struct ProseTextView: NSViewRepresentable {
weak var textView: NSTextView?
var sessionRef: EditorSession?
var loadedGeneration = -1
var appliedCaretToken = -1
var appliedFlowKey = ""
private var defaultsObserver: NSObjectProtocol?
func watchDefaults(_ tv: NSTextView) {
guard defaultsObserver == nil else { return }
defaultsObserver = NotificationCenter.default.addObserver(
forName: UserDefaults.didChangeNotification,
object: nil,
queue: .main,
) { [weak self] _ in
self?.applyTypographyIfChanged(tv)
}
}
private func applyTypographyIfChanged(_ tv: NSTextView) {
let key = ProseTypography.flowKey
guard key != appliedFlowKey else { return }
appliedFlowKey = key
let sel = tv.selectedRange()
if let storage = tv.textStorage as? NSMutableAttributedString {
storage.setAttributedString(ProsePresenter.attribute(tv.string))
tv.setSelectedRange(sel)
}
}
init(representable: ProseTextView) {
onEdit = representable.onEdit
@@ -250,7 +389,7 @@ struct ProseTextView: NSViewRepresentable {
// 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
tv.typingAttributes = ProseTypography.bodyAttributes
if let sessionRef {
sessionRef.edit(storage.string)
} else {
+24 -23
View File
@@ -40,13 +40,14 @@ nonisolated enum ProsePresenter {
/// 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 {
static func paragraph(_: 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
}
// Edit mode shows blank source lines — the blank line IS the
// separator. Only line height rides the flow knobs here; the
// paragraph/heading spacing knobs are reading-mode only.
style.lineHeightMultiple = ProseTypography.lineHeightMultiple
style.paragraphSpacing = 0
style.paragraphSpacingBefore = 0
return style
}
@@ -71,30 +72,27 @@ nonisolated enum ProsePresenter {
dimSyntax(in: out, range: paragraphRange)
}
// Typography: Iowan Old Style prose stance (the export's stack), 17pt body,
// scaled headings.
// Typography: the #70 role slots (ProseTypography) — Body / Headings /
// Code — shared with reading mode; editing chrome (dimmed syntax) rides
// the Code slot.
static var bodyFont: NSFont {
NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17)
?? NSFont.systemFont(ofSize: 17)
ProseTypography.bodyFont
}
static var bodyAttributes: [NSAttributedString.Key: Any] {
[
.font: bodyFont,
.paragraphStyle: paragraph(.body),
.foregroundColor: NSColor(red: 0.10, green: 0.10, blue: 0.09, alpha: 1),
]
ProseTypography.bodyAttributes
}
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
case .heading1:
[.font: ProseTypography.headingFont, .paragraphStyle: paragraph(.heading1)]
case .heading2:
[
.font: ProseTypography.headingFont(size: (ProseTypography.headingFont.pointSize * 0.77).rounded()),
.paragraphStyle: paragraph(.heading2),
]
case .quote, .syntaxOnly, .body: bodyAttributes
}
}
@@ -111,7 +109,10 @@ nonisolated enum ProsePresenter {
case .quote: 2
default: 0
}
let dim: [NSAttributedString.Key: Any] = [.foregroundColor: NSColor(white: 0.55, alpha: 1), .font: NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)]
let dim: [NSAttributedString.Key: Any] = [
.foregroundColor: ProseTypography.syntaxColor,
.font: ProseTypography.codeFont,
]
if markerLen > 0 {
out.addAttributes(dim, range: NSRange(location: range.location, length: min(markerLen, range.length)))
}
+191
View File
@@ -0,0 +1,191 @@
//
// ProseTypography.swift
// Museion
//
// #71 (S1.2, map #20 / #70): the three role slots — Body / Headings / Code —
// each {face, size}, persisted in UserDefaults (six values), read by BOTH
// prose surfaces (styled-source editing + reading). Machine-local faces,
// nothing bundled; a missing face falls back to the system font silently.
// Chrome stays on system faces.
//
// Resolution note (#70 deviation, probed in-session): family+weight lookup
// misresolves Concourse OT — Thin and Book both advertise weight 4, and
// NSFontManager picks Thin. Faces therefore resolve through the family's
// member list: prefer the Book/Regular member, else the middle weight.
//
import AppKit
/// Prose typography slots (#70). Static computed accessors — surfaces read
/// on render; the Settings pane writes UserDefaults and the surfaces rebuild
/// (pane re-entry rebuilds the editor; reading rebuilds per toggle).
nonisolated enum ProseTypography {
/// v1 defaults (#70): Body = Concourse OT Book 17, Headings = Iowan Old
/// Style bold 26, Code = UbuntuMono Nerd Font Mono 13.
static let defaultBodyFace = "Concourse OT"
static let defaultHeadingsFace = "Iowan Old Style"
static let defaultCodeFace = "UbuntuMono Nerd Font Mono"
static let defaultBodySize: Double = 17
static let defaultHeadingsSize: Double = 26
static let defaultCodeSize: Double = 13
/// Text flow (#71 polish): line-height multiple + paragraph/heading
/// spacing measured in body lines — different faces need different flow.
static let defaultLineHeight: Double = 1.25
static let defaultParagraphSpacingLines: Double = 1
static let defaultHeadingSpacingLines: Double = 2
/// Register the six defaults once at app start.
static func registerDefaults() {
UserDefaults.standard.register(defaults: [
"proseBodyFace": defaultBodyFace,
"proseBodySize": defaultBodySize,
"proseHeadingsFace": defaultHeadingsFace,
"proseHeadingsSize": defaultHeadingsSize,
"proseCodeFace": defaultCodeFace,
"proseCodeSize": defaultCodeSize,
"proseLineHeight": defaultLineHeight,
"proseParagraphSpacingLines": defaultParagraphSpacingLines,
"proseHeadingSpacingLines": defaultHeadingSpacingLines,
])
}
private static func face(_ key: String, defaultFace: String) -> String {
UserDefaults.standard.string(forKey: key) ?? defaultFace
}
private static func size(_ key: String, defaultSize: Double) -> CGFloat {
let stored = UserDefaults.standard.double(forKey: key)
return stored == 0 ? defaultSize : stored
}
// MARK: Slot fonts
/// Body slot font — the family's Book/Regular member at the slot size.
static var bodyFont: NSFont {
font(family: face("proseBodyFace", defaultFace: defaultBodyFace),
size: size("proseBodySize", defaultSize: defaultBodySize))
}
/// Headings slot font — the family's Book/Regular member, bold trait, at
/// the slot size (h1). Scaled levels call `headingFont(size:)`.
static var headingFont: NSFont {
bolded(headingFont(size: size("proseHeadingsSize", defaultSize: defaultHeadingsSize)))
}
static func headingFont(size: CGFloat) -> NSFont {
bolded(font(family: face("proseHeadingsFace", defaultFace: defaultHeadingsFace), size: size))
}
/// Code slot font (inline code, fenced blocks, and the editing surface's
/// dimmed syntax).
static var codeFont: NSFont {
font(family: face("proseCodeFace", defaultFace: defaultCodeFace),
size: size("proseCodeSize", defaultSize: defaultCodeSize))
}
static var italicBodyFont: NSFont {
NSFontManager.shared.convert(bodyFont, toHaveTrait: .italicFontMask)
}
static var boldBodyFont: NSFont {
bolded(bodyFont)
}
// MARK: Text flow (#71 polish)
/// Line-height multiple (clamped 1…2; 0/absent → default).
static var lineHeightMultiple: CGFloat {
clamped("proseLineHeight", default: defaultLineHeight, 1 ... 2)
}
/// Spacing after body paragraphs, in body lines.
static var paragraphSpacingLines: CGFloat {
clamped("proseParagraphSpacingLines", default: defaultParagraphSpacingLines, 0 ... 4)
}
/// Spacing after headings, in body lines.
static var headingSpacingLines: CGFloat {
clamped("proseHeadingSpacingLines", default: defaultHeadingSpacingLines, 0 ... 6)
}
/// Every value the prose surfaces render from, summed — a change key
/// for live re-attribution when settings move.
static var flowKey: String {
"\(bodyFont.fontName)@\(bodyFont.pointSize)|\(codeFont.fontName)@\(codeFont.pointSize)|\(headingFont.fontName)@\(headingFont.pointSize)|lh=\(lineHeightMultiple)|p=\(paragraphSpacingLines)|h=\(headingSpacingLines)"
}
/// One body line at the configured flow, in points.
static var linePoints: CGFloat {
let f = bodyFont
return (f.ascender - f.descender + f.leading) * lineHeightMultiple
}
private static func clamped(_ key: String, default def: Double, _ range: ClosedRange<Double>) -> CGFloat {
let stored = UserDefaults.standard.double(forKey: key)
let value = stored == 0 ? def : stored
return CGFloat(min(max(value, range.lowerBound), range.upperBound))
}
// MARK: Attribute stacks (reading + editing share them)
static var foregroundColor: NSColor {
NSColor(red: 0.10, green: 0.10, blue: 0.09, alpha: 1)
}
/// Dimmed syntax color (the editing surface's 0.55 dim, #19).
static var syntaxColor: NSColor {
NSColor(white: 0.55, alpha: 1)
}
static var quoteRuleColor: NSColor {
NSColor(white: 0.78, alpha: 1)
}
/// Table borders + reading HR hairline (≈ DesignTokens.border).
static var tableBorderColor: NSColor {
NSColor(red: 0xE8 / 255, green: 0xE5 / 255, blue: 0xDF / 255, alpha: 1)
}
static var bodyAttributes: [NSAttributedString.Key: Any] {
[
.font: bodyFont,
.paragraphStyle: ProsePresenter.paragraph(.body),
.foregroundColor: foregroundColor,
]
}
static var codeAttributes: [NSAttributedString.Key: Any] {
[
.font: codeFont,
.foregroundColor: syntaxColor,
]
}
// MARK: Resolution
/// Family → member PS name → NSFont. Prefer Book/Regular styles, else the
/// member closest to weight 5; unknown family → system font (silent, #70).
private static func font(family: String, size: CGFloat) -> NSFont {
let members = NSFontManager.shared.availableMembers(ofFontFamily: family) ?? []
let regular = members.first { entry in
guard let style = entry[safe: 1] as? String else { return false }
return style.range(of: "book|regular", options: [.caseInsensitive, .regularExpression]) != nil
} ?? members.min { lhs, rhs in
abs((lhs[safe: 2] as? Int ?? 5) - 5) < abs((rhs[safe: 2] as? Int ?? 5) - 5)
}
guard let name = regular?[safe: 0] as? String else {
return NSFont.systemFont(ofSize: size)
}
return NSFont(name: name, size: size) ?? NSFont.systemFont(ofSize: size)
}
private static func bolded(_ base: NSFont) -> NSFont {
NSFontManager.shared.convert(base, toHaveTrait: .boldFontMask)
}
}
private nonisolated extension Array {
subscript(safe index: Int) -> Element? {
indices.contains(index) ? self[index] : nil
}
}
+557
View File
@@ -0,0 +1,557 @@
//
// ReadingPresenter.swift
// Museion
//
// #71 (S1.2, map #20): the reading-mode renderer — block-aware per ADR-0010
// (blank-line split, per-paragraph inline parse, headings fonted by level;
// single-Text .full flatten is the anti-pattern). Presentation-only: the
// renderer never touches the file; every block carries its source range so
// the surface can map click → source paragraph (#68). Scope per #69: lists
// (bullets + ordered + nesting + auto-renumber — one rendering path), ### /
// #### headings, HR, fenced code, blockquotes (hairline), tables
// (NSTextTable, 1px border), images (hover popover payload), links styled +
// ⌘-click; footnotes are the one fallback. Typography per #70: the three
// role slots in ProseTypography (Body / Headings / Code).
//
import AppKit
/// Reading-mode presentation: text → rendered blocks. Pure over its input;
/// called on the main actor (NSTextTable construction is MainActor).
enum ReadingPresenter {
/// Vertical rhythm (user measurements, #71 polish): line-height ≈1.25,
/// 1 blank line after paragraphs, 2 after headings.
private static let lineHeightMultiple: CGFloat = 1.25
private static let paragraphSpacingAfter = lineHeightMultiple // 1 line
private static let headingSpacingAfter = lineHeightMultiple * 2 // 2 lines
/// One rendered block. `sourceRange` is the block's UTF-16 range in the
/// source text (delimiter-exclusive) — the #68 click→edit map.
struct Block {
let content: NSAttributedString
let sourceRange: NSRange
/// Popover image URL for an `![alt](url)` chunk (#69 hover floor).
let imageURL: URL?
/// Canvas-drawn decoration (quote hairline / rule / table grid).
var decoration: Decoration?
}
/// A block's placement in the built document: where its content landed
/// (docRange) ↔ where it came from (sourceRange), plus its resolved image.
struct Bound {
let docRange: NSRange
let sourceRange: NSRange
let imageURL: URL?
var decoration: Decoration?
}
/// Canvas-drawn decoration for constructs whose layout NSTextTable /
/// NSTextBlock can't deliver on modern TextKit (#69 fix: draw it
/// ourselves from measured geometry instead).
enum Decoration {
/// Left hairline at the given indent.
case quote(indent: CGFloat)
/// Full-width horizontal rule.
case rule
/// Column x-offsets (incl. closing edge) in mono advance.
case table(columns: [CGFloat])
}
/// The reading document: blocks concatenated with paragraph-rhythm
/// separators, bounds tracked for click→edit and scroll mapping.
struct Document {
let content: NSAttributedString
let bounds: [Bound]
}
/// Build the single-storage reading document. Image URLs resolve against
/// `postFolder` (nil → raw URL kept; the popover fails soft).
static func document(for text: String, resolvingImagesIn postFolder: URL?) -> Document {
let out = NSMutableAttributedString()
var bounds: [Bound] = []
for block in blocks(for: text, resolvingImagesIn: postFolder) {
if out.length > 0, !out.string.hasSuffix("\n") {
out.append(NSAttributedString(string: "\n", attributes: ProseTypography.bodyAttributes))
}
let start = out.length
out.append(block.content)
bounds.append(Bound(
docRange: NSRange(location: start, length: out.length - start),
sourceRange: block.sourceRange,
imageURL: block.imageURL,
decoration: block.decoration,
))
}
return Document(content: out, bounds: bounds)
}
// MARK: Entry
/// Render `text` into reading blocks: blank-line split, one block per
/// chunk (a run of list items or quote lines renders as one block).
/// `postFolder` resolves relative image URLs before the attachment loads.
static func blocks(for text: String, resolvingImagesIn postFolder: URL?) -> [Block] {
var out: [Block] = []
let ns = text as NSString
var loc = 0
while loc < ns.length {
let search = NSRange(location: loc, length: ns.length - loc)
let delim = ns.range(of: "\n\n", options: .literal, range: search)
let end = delim.location == NSNotFound ? ns.length : delim.location
if end > loc {
let chunkRange = NSRange(location: loc, length: end - loc)
let chunk = ns.substring(with: chunkRange)
out.append(block(chunk: chunk, sourceRange: chunkRange, postFolder: postFolder))
}
loc = delim.location == NSNotFound ? ns.length : delim.location + 2
}
return out
}
/// Classify one chunk and render it.
private static func block(chunk: String, sourceRange: NSRange, postFolder: URL?) -> Block {
if let raw = imageURL(in: chunk) {
let url = (raw.scheme == nil && raw.path.count > 0)
? postFolder?.appendingPathComponent(raw.path) ?? raw : raw
return Block(
content: imageBlockContent(url: url, alt: altText(in: chunk)),
sourceRange: sourceRange,
imageURL: url,
)
}
let lines = chunk.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
guard let first = lines.first else {
return Block(content: NSAttributedString(string: ""), sourceRange: sourceRange, imageURL: nil)
}
// HR first (#69: `* * *`/`- - -` would otherwise match the bullet
// marker `* `/`- ` — same predicate as editing, checked earlier).
if lines.count == 1, ProsePresenter.lineKind(first) == .syntaxOnly {
return Block(content: hrContent(), sourceRange: sourceRange, imageURL: nil, decoration: .rule)
}
if lines.allSatisfy({ listItemMarker($0) != nil }) {
return Block(content: listContent(lines), sourceRange: sourceRange, imageURL: nil)
}
if lines.allSatisfy({ blockquoteDepth($0) > 0 }) {
return Block(content: quoteContent(lines), sourceRange: sourceRange, imageURL: nil, decoration: quoteDecoration(lines))
}
if lines.count >= 2, isTableDelimiterRow(lines[1]), let table = tableContent(lines) {
return Block(content: table, sourceRange: sourceRange, imageURL: nil, decoration: tableDecoration(lines))
}
return Block(content: flowContent(lines, first: first), sourceRange: sourceRange, imageURL: nil)
}
// MARK: Flow blocks
/// Image block: the picture inline (scaled to the column), alt as the
/// caption below, link preserved for ⌘-click. Fails soft to alt-text
/// paragraph when the file can't load.
private static func imageBlockContent(url: URL, alt: String) -> NSAttributedString {
let ps = NSMutableParagraphStyle()
ps.lineHeightMultiple = lineHeightMultiple
ps.paragraphSpacing = paragraphSpacingAfter
ps.paragraphSpacingBefore = 8
guard let image = NSImage(contentsOf: url), image.size.width > 0 else {
return inlineParse(alt.isEmpty ? "![missing](\(url.lastPathComponent))" : alt)
}
let attachment = NSTextAttachment()
attachment.image = image
let maxW: CGFloat = 480
if image.size.width > maxW {
attachment.image?.size = NSSize(width: maxW, height: maxW * image.size.height / image.size.width)
}
let cell = NSMutableAttributedString(attachment: attachment, attributes: [
.paragraphStyle: ps,
])
if !alt.isEmpty {
cell.append(NSAttributedString(string: "\n" + alt, attributes: [
.font: ProseTypography.codeFont,
.foregroundColor: ProseTypography.syntaxColor,
.paragraphStyle: ps,
]))
}
return cell
}
private static func flowContent(_ lines: [String], first: String) -> NSAttributedString {
if let level = headingLevel(first) {
let body = first.drop { $0 == "#" }.trimmingCharacters(in: .whitespaces)
let heading = headingContent(body, level: level)
// Bug fix: a heading chunk may carry body lines under the heading
// (single newline is legal markdown) — they are part of the block.
let rest = lines.dropFirst()
.map { $0.trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty }
if rest.isEmpty {
return heading
}
let out = NSMutableAttributedString(attributedString: heading)
out.append(NSAttributedString(string: "\n", attributes: ProseTypography.bodyAttributes))
out.append(inlineParse(rest.joined(separator: " ")))
return out
}
if first.hasPrefix("```") {
let inner = lines.dropFirst().dropLast(hasClosingFence(lines) ? 1 : 0)
return codeContent(inner.joined(separator: "\n"))
}
// HR — the editing presenter's syntaxOnly matcher reused verbatim
// (#69: same predicate both modes = one mental model).
if ProsePresenter.lineKind(first) == .syntaxOnly {
return hrContent()
}
// Paragraph: soft-join lines with single spaces, one inline parse.
let joined = lines
.map { $0.trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty }
.joined(separator: " ")
let para = inlineParse(joined)
let ps = NSMutableParagraphStyle()
ps.lineHeightMultiple = lineHeightMultiple
ps.paragraphSpacing = paragraphSpacingAfter
let styled = NSMutableAttributedString(attributedString: para)
styled.addAttribute(.paragraphStyle, value: ps, range: NSRange(location: 0, length: styled.length))
return styled
}
private static func headingContent(_ text: String, level: Int) -> NSAttributedString {
// #70: h1 = Headings slot size; h2 = 0.77×; ### = body+1 (≈17–18);
// ####+ floors at bold body.
let slotSize = ProseTypography.headingFont.pointSize
let size: CGFloat = switch level {
case 1: slotSize
case 2: (slotSize * 0.77).rounded()
case 3: ProseTypography.bodyFont.pointSize + 1
default: ProseTypography.bodyFont.pointSize
}
let ps = NSMutableParagraphStyle()
ps.lineHeightMultiple = lineHeightMultiple
ps.paragraphSpacing = headingSpacingAfter
ps.paragraphSpacingBefore = level == 1 ? 26 : (level == 2 ? 20 : 14)
return NSAttributedString(string: text, attributes: [
.font: ProseTypography.headingFont(size: size),
.paragraphStyle: ps,
.foregroundColor: ProseTypography.foregroundColor,
])
}
private static func codeContent(_ code: String) -> NSAttributedString {
let ps = NSMutableParagraphStyle()
ps.lineHeightMultiple = lineHeightMultiple
ps.paragraphSpacing = paragraphSpacingAfter
ps.paragraphSpacingBefore = 6
ps.firstLineHeadIndent = 12
ps.headIndent = 12
return NSAttributedString(string: code, attributes: [
.font: ProseTypography.codeFont,
.paragraphStyle: ps,
.foregroundColor: ProseTypography.syntaxColor,
])
}
private static func hrContent() -> NSAttributedString {
// Hairline drawn by the canvas (Decoration.rule).
let ps = NSMutableParagraphStyle()
ps.lineHeightMultiple = lineHeightMultiple
ps.paragraphSpacingBefore = 8
ps.paragraphSpacing = 8
return NSAttributedString(string: " ", attributes: [
.font: ProseTypography.codeFont,
.paragraphStyle: ps,
.foregroundColor: NSColor.clear,
])
}
// MARK: Lists (#69: one path for bullets and ordered — the counter makes
// auto-renumbering free; glyphs only, the file is never rewritten)
private static func listContent(_ lines: [String]) -> NSAttributedString {
let out = NSMutableAttributedString()
var counters: [Int: Int] = [:]
for (index, line) in lines.enumerated() {
guard let marker = listItemMarker(line) else { continue }
let indent: CGFloat = 16 + CGFloat(marker.level - 1) * 18
let ps = NSMutableParagraphStyle()
ps.lineHeightMultiple = lineHeightMultiple
ps.firstLineHeadIndent = indent
ps.headIndent = indent + 18
ps.paragraphSpacing = 5
let glyph: String
if marker.ordered {
counters[marker.level, default: 0] += 1
glyph = "\(counters[marker.level]!). "
} else {
glyph = "• "
}
let item = NSMutableAttributedString(string: glyph, attributes: ProseTypography.bodyAttributes)
item.append(inlineParse(marker.payload.trimmingCharacters(in: .whitespaces)))
item.addAttribute(
.paragraphStyle, value: ps,
range: NSRange(location: 0, length: item.length),
)
out.append(item)
if index < lines.count - 1 {
out.append(NSAttributedString(string: "\n", attributes: ProseTypography.bodyAttributes))
}
}
return out
}
// MARK: Blockquotes (#69: `>` never visible, hairline rule, nesting indents)
private static func quoteContent(_ lines: [String]) -> NSAttributedString {
// Hairline drawn by the canvas (Decoration.quote) — NSTextBlock
// drawing zero-widths the line rect on modern TextKit, wrapping
// content one character per line.
let out = NSMutableAttributedString()
for (index, line) in lines.enumerated() {
let depth = blockquoteDepth(line)
let indent = CGFloat(6 + (depth - 1) * 18)
let ps = NSMutableParagraphStyle()
ps.lineHeightMultiple = lineHeightMultiple
ps.firstLineHeadIndent = indent
ps.headIndent = indent
ps.paragraphSpacing = 4
let styled = NSMutableAttributedString(
attributedString: inlineParse(quoteBody(line)),
)
styled.addAttribute(
.paragraphStyle, value: ps,
range: NSRange(location: 0, length: styled.length),
)
out.append(styled)
if index < lines.count - 1 {
out.append(NSAttributedString(string: "\n", attributes: ProseTypography.bodyAttributes))
}
}
return out
}
/// Payload after the `>` marker run (markers + surrounding spaces).
private static func quoteBody(_ line: String) -> String {
let prefix = line.prefix { $0 == ">" || $0 == " " }
return String(line.dropFirst(prefix.count)).trimmingCharacters(in: .whitespaces)
}
// MARK: Tables (#69: mono grid — plain padded text; the canvas draws the
// grid lines from Decoration.table. NSTextTable cannot lay out on modern
// TextKit: rows stack vertically, columns never align.)
private static func tableContent(_ lines: [String]) -> NSAttributedString? {
let header = tableCells(lines[0])
let aligns = tableAlignments(lines[1])
guard !header.isEmpty, header.count == aligns.count else { return nil }
let dataRows = lines.enumerated().filter { $0.offset != 1 }.map(\.element)
let cellTexts = ([lines[0]] + dataRows.dropFirst()).map(tableCells)
let columnCount = header.count
var widths = Array(repeating: 0, count: columnCount)
for row in cellTexts {
for (column, cell) in row.enumerated() where column < columnCount {
widths[column] = max(widths[column], cell.count)
}
}
let pad = 3
let codeAttrs: [NSAttributedString.Key: Any] = [
.font: ProseTypography.codeFont,
.foregroundColor: ProseTypography.foregroundColor,
]
let out = NSMutableAttributedString()
func gridLine(_ cells: [String]) -> NSAttributedString {
var line = ""
for column in 0 ..< columnCount {
let text = column < cells.count ? cells[column] : ""
let width = widths[column]
let padded: String
switch aligns[column] {
case .center where text.count < width:
let left = (width - text.count) / 2
padded = String(repeating: " ", count: left) + text
+ String(repeating: " ", count: width - text.count - left)
case .right:
padded = String(repeating: " ", count: max(0, width - text.count)) + text
default:
padded = text + String(repeating: " ", count: max(0, width - text.count))
}
line += String(repeating: " ", count: pad) + padded + String(repeating: " ", count: pad)
}
return NSAttributedString(string: line, attributes: codeAttrs)
}
out.append(gridLine(cellTexts[0]))
for row in cellTexts.dropFirst() {
out.append(NSAttributedString(string: "\n", attributes: codeAttrs))
out.append(gridLine(row))
}
return out
}
/// Quote decoration: left hairline at the shallowest quote indent.
private static func quoteDecoration(_ lines: [String]) -> Decoration {
let minIndent = lines.compactMap { line -> CGFloat? in
blockquoteDepth(line) > 0 ? CGFloat(6 + (blockquoteDepth(line) - 1) * 18) : nil
}.min() ?? 6
return .quote(indent: minIndent)
}
/// Table decoration: column x-offsets (+ closing edge) in mono advance.
private static func tableDecoration(_ lines: [String]) -> Decoration {
let header = tableCells(lines[0])
let dataRows = lines.enumerated().filter { $0.offset != 1 }.map(\.element)
let cellTexts = ([lines[0]] + dataRows.dropFirst()).map(tableCells)
var widths = Array(repeating: 0, count: header.count)
for row in cellTexts {
for (column, cell) in row.enumerated() where column < header.count {
widths[column] = max(widths[column], cell.count)
}
}
let advance = ("0" as NSString).size(withAttributes: [
.font: ProseTypography.codeFont,
]).width
var offsets: [CGFloat] = []
var running = 0.0
for width in widths {
offsets.append(running)
running += CGFloat(width + 6) * advance // cell pad 3 + 3, matches gridLine
}
return .table(columns: offsets + [running])
}
private static func tableCells(_ line: String) -> [String] {
var trimmed = line.trimmingCharacters(in: .whitespaces)
if trimmed.hasPrefix("|") {
trimmed.removeFirst()
}
if trimmed.hasSuffix("|") {
trimmed.removeLast()
}
return trimmed.components(separatedBy: "|").map { $0.trimmingCharacters(in: .whitespaces) }
}
private static func tableAlignments(_ delimiter: String) -> [NSTextAlignment] {
tableCells(delimiter).map { cell in
let left = cell.hasPrefix(":")
let right = cell.hasSuffix(":")
if left == right {
return left ? .center : .left
} // --- = left, :---: = center
return left ? .left : .right
}
}
// MARK: Inline (#69: marker glyphs never show; links styled + retained)
/// One `AttributedString(markdown:)` parse, presentation-interpreted:
/// emphasis/strong → italic/bold body face, code spans → code face,
/// links styled + kept for ⌘-click.
static func inlineParse(_ raw: String) -> NSAttributedString {
var opts = AttributedString.MarkdownParsingOptions()
opts.interpretedSyntax = .inlineOnlyPreservingWhitespace
guard let parsed = try? AttributedString(markdown: raw, options: opts) else {
return NSAttributedString(string: raw, attributes: ProseTypography.bodyAttributes)
}
let out = NSMutableAttributedString()
for run in parsed.runs {
var attrs = ProseTypography.bodyAttributes
if let intent = run.inlinePresentationIntent {
if intent.contains(.code) {
attrs = ProseTypography.codeAttributes
} else {
var font = ProseTypography.bodyFont
if intent.contains(.emphasized) {
font = ProseTypography.italicBodyFont
}
if intent.contains(.stronglyEmphasized) {
font = ProseTypography.boldBodyFont
}
attrs[.font] = font
}
}
if let link = run.link {
attrs[.link] = link
attrs[.underlineStyle] = NSUnderlineStyle.single.rawValue
attrs[.cursor] = NSCursor.pointingHand
}
out.append(NSAttributedString(
string: String(parsed[run.range].characters),
attributes: attrs,
))
}
return out
}
/// Alt text of an `![alt](url)` chunk (empty when absent).
private static func altText(in chunk: String) -> String {
let trimmed = chunk.trimmingCharacters(in: .whitespacesAndNewlines)
guard trimmed.hasPrefix("!["), let closeBracket = trimmed.firstIndex(of: "]") else { return "" }
return String(trimmed[trimmed.index(trimmed.startIndex, offsetBy: 2) ..< closeBracket])
}
// MARK: Construct matchers
private struct ListMarker {
let level: Int
let ordered: Bool
let payload: String
}
/// `- `/`* ` bullet or `N.`/`N)` ordered marker. Indent levels: 0–1 sp → 1,
/// 2–3 sp → 2, 4+ sp → 3+ (2-space and 4-space styles both accepted, #69).
private static func listItemMarker(_ line: String) -> ListMarker? {
let indent = line.prefix { $0 == " " }.count
let rest = line.dropFirst(indent)
if rest.hasPrefix("- ") || rest.hasPrefix("* ") {
return ListMarker(level: indentLevel(indent), ordered: false, payload: String(rest.dropFirst(2)))
}
let digits = rest.prefix { $0.isNumber }.count
guard digits > 0 else { return nil }
let after = rest.dropFirst(digits)
guard after.hasPrefix(". ") || after.hasPrefix(") ") else { return nil }
return ListMarker(level: indentLevel(indent), ordered: true, payload: String(after.dropFirst(2)))
}
private static func indentLevel(_ spaces: Int) -> Int {
spaces <= 1 ? 1 : (spaces <= 3 ? 2 : min(3 + (spaces - 4) / 2, 6))
}
/// `>`-prefix depth (1 for `> `, 2 for `>> `; spaces tolerated).
private static func blockquoteDepth(_ line: String) -> Int {
line.prefix { $0 == ">" || $0 == " " }.filter { $0 == ">" }.count
}
/// `# `-style heading with its level; requires a space after the hashes
/// (so prose like `#hashtag` stays a paragraph).
private static func headingLevel(_ line: String) -> Int? {
let trimmed = line.drop { $0 == " " }
let hashes = trimmed.prefix { $0 == "#" }.count
guard hashes >= 1, hashes <= 6 else { return nil }
let after = trimmed.dropFirst(hashes)
return after.hasPrefix(" ") || after.isEmpty ? hashes : nil
}
/// `| --- | :---: |` delimiter row under a header row.
private static func isTableDelimiterRow(_ line: String) -> Bool {
let trimmed = line.trimmingCharacters(in: .whitespaces)
guard trimmed.hasPrefix("|"), trimmed.hasSuffix("|"), trimmed.count >= 4 else { return false }
let cells = tableCells(trimmed)
return !cells.isEmpty && cells.allSatisfy { cell in
!cell.isEmpty && cell.allSatisfy { $0 == "-" || $0 == ":" }
}
}
private static func hasClosingFence(_ lines: [String]) -> Bool {
guard let last = lines.last else { return false }
return last.trimmingCharacters(in: .whitespaces).hasPrefix("```")
}
/// `![alt](url)` → url when the chunk is exactly one image line (#69: the
/// inline parser renders image syntax as bare alt text with no link
/// attribute, so the URL is recovered at chunk level).
private static func imageURL(in chunk: String) -> URL? {
let trimmed = chunk.trimmingCharacters(in: .whitespacesAndNewlines)
guard trimmed.hasPrefix("![") else { return nil }
guard let closeBracket = trimmed.firstIndex(of: "]") else { return nil }
let afterBracket = trimmed.index(after: closeBracket)
guard afterBracket < trimmed.endIndex, trimmed[afterBracket] == "(" else { return nil }
let start = trimmed.index(after: afterBracket)
guard let closeParen = trimmed[start...].firstIndex(of: ")") else { return nil }
return URL(string: String(trimmed[start ..< closeParen]))
}
}
+351
View File
@@ -0,0 +1,351 @@
//
// ReadingSurface.swift
// Museion
//
// #71 (S1.2, map #20): the reading-mode surface — the renderer's blocks set
// into a read-only, selectable NSTextView (#68: reading is a presentation
// of the same TextKit2 document, not a separate view stack). Interaction
// per #68: drag-select stays native; a tap with no selection = edit intent
// (drop to editing at the clicked block's source paragraph); ⌘-click opens
// links; hovering an image block pops the loaded image (#69 floor).
//
import AppKit
import SwiftUI
/// Live reading-position state for flip-back scroll mapping (#68). Plain
/// class held `@State` by the editor — reference identity survives renders.
final class ReadingStateBox {
/// Source caret location when reading opened — scrolls that block to the
/// top (#68 entry mapping).
var entryLocation: Int?
/// Source location of the top visible block; updated as reading scrolls
/// (#68 flip-back mapping).
var topSourceLocation: Int?
}
/// One-shot caret placement for the editing surface (#68): set when reading
/// flips back (click-to-edit or toggle-back), consumed by ProseTextView.
final class CaretHintBox {
var location: Int?
var consumed = true
}
/// Reading surface: renders `text` via ReadingPresenter into a scrollable,
/// read-only canvas. Rebuilds when `generation` moves (open / Yes-reload) or
/// the text genuinely changes (draft edit path).
struct ReadingSurface: NSViewRepresentable {
let text: String
/// Session loadGeneration (0 for drafts) — rebuild key, never per keystroke.
var generation: Int
/// The post's folder — resolves relative image URLs. Nil for drafts.
var postFolder: URL?
/// UTF-16 caret location captured when reading opened; scrolls the
/// containing block to the top (#68 mapping attempt).
var entryCaretLocation: Int?
var onEditIntent: (Int) -> Void
/// Flip-back scroll mapping target.
var stateBox: ReadingStateBox?
func makeNSView(context: Context) -> NSScrollView {
let tv = ReadingCanvasView()
tv.isEditable = false
tv.isSelectable = true
tv.isRichText = false
tv.allowsUndo = false
tv.isAutomaticQuoteSubstitutionEnabled = false
tv.isAutomaticDashSubstitutionEnabled = false
tv.isAutomaticTextReplacementEnabled = false
tv.isAutomaticSpellingCorrectionEnabled = false
tv.backgroundColor = NSColor.white
tv.typingAttributes = ProseTypography.bodyAttributes
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 (#68/71 fix): the container tracks the
// view width — a fixed 640pt measure clipped in narrower columns.
tv.textContainer?.containerSize = NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude)
tv.textContainer?.widthTracksTextView = true
tv.textContainer?.lineFragmentPadding = 24
tv.textContainerInset = NSSize(width: 0, height: 24)
let scroll = NSScrollView()
scroll.documentView = tv
scroll.hasVerticalScroller = true
scroll.autohidesScrollers = true
scroll.drawsBackground = true
scroll.backgroundColor = NSColor.white
tv.onEditIntent = onEditIntent
tv.stateBox = stateBox
context.coordinator.canvas = tv
context.coordinator.watchDefaults(tv, representable: self)
return scroll
}
func updateNSView(_ scroll: NSScrollView, context: Context) {
guard let tv = scroll.documentView as? ReadingCanvasView else { return }
tv.onEditIntent = onEditIntent
tv.stateBox = stateBox
tv.postFolder = postFolder
guard context.coordinator.builtGeneration != generation || context.coordinator.builtText != text else { return }
context.coordinator.builtGeneration = generation
context.coordinator.builtText = text
let doc = ReadingPresenter.document(for: text, resolvingImagesIn: postFolder)
tv.textStorage?.setAttributedString(doc.content)
tv.blockBounds = doc.bounds
tv.needsLayout = true
tv.layoutSubtreeIfNeeded()
if let caret = entryCaretLocation, let bound = tv.bound(containing: caret) {
tv.scrollRangeToVisible(NSRange(location: bound.docRange.location, length: 0))
} else {
tv.scroll(NSPoint(x: 0, y: 0))
}
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
final class Coordinator {
weak var canvas: ReadingCanvasView?
var builtGeneration = -1
var builtText = ""
private var defaultsObserver: NSObjectProtocol?
private var appliedFlowKey = ""
/// Rebuild the rendered document when typography/flow knobs move
/// (SwiftUI doesn't re-call updateNSView on UserDefaults writes).
func watchDefaults(_: ReadingCanvasView, representable: ReadingSurface) {
guard defaultsObserver == nil else { return }
appliedFlowKey = ProseTypography.flowKey
defaultsObserver = NotificationCenter.default.addObserver(
forName: UserDefaults.didChangeNotification,
object: nil,
queue: .main,
) { [weak self] _ in
guard let self, let canvas else { return }
let key = ProseTypography.flowKey
guard key != appliedFlowKey else { return }
appliedFlowKey = key
let doc = ReadingPresenter.document(for: representable.text, resolvingImagesIn: representable.postFolder)
canvas.textStorage?.setAttributedString(doc.content)
canvas.blockBounds = doc.bounds
canvas.needsDisplay = true
}
}
}
}
/// The reading canvas: click discrimination, ⌘-click links, image hover
/// popover, top-block scroll tracking. Read-only over rendered content.
final class ReadingCanvasView: NSTextView {
typealias BlockBound = ReadingPresenter.Bound
var blockBounds: [BlockBound] = []
var onEditIntent: ((Int) -> Void)?
var stateBox: ReadingStateBox?
var postFolder: URL?
private var popover: NSPopover?
private var hoverTrackingArea: NSTrackingArea?
/// Last bound starting at or before `index` (spacing separators clamp to
/// the preceding block).
func bound(containing index: Int) -> BlockBound? {
blockBounds.last { $0.docRange.location <= index }
}
// MARK: Decorations (#69 fix: quote hairlines, HR rules, table grids —
// drawn from measured TK2 fragment geometry; NSTextBlock/NSTextTable
// layout is broken on modern TextKit and the TK1-compat bridge reports
// wrong rects. Enumeration pattern is probe-proven: walk ALL fragments
// from document start, map each to a doc offset, slice per bound.)
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
let origin = textContainerOrigin
for bound in blockBounds {
guard let decoration = bound.decoration else { continue }
// frames arrive in CONTAINER space; the view draws text at
// textContainerOrigin + frame (inset shifts it — the missing
// +origin.y drew every decoration 20pt too high).
let frames = framesForRange(bound.docRange)
.map { CGRect(x: $0.minX + origin.x, y: $0.minY + origin.y, width: $0.width, height: $0.height) }
guard let firstFrame = frames.first, let lastFrame = frames.last else { continue }
switch decoration {
case let .quote(indent):
let x = (textContainer?.lineFragmentPadding ?? 0) + indent - 6
let path = NSBezierPath()
path.move(to: NSPoint(x: x, y: firstFrame.minY))
path.line(to: NSPoint(x: x, y: lastFrame.maxY))
path.lineWidth = 2
ProseTypography.quoteRuleColor.setStroke()
path.stroke()
case .rule:
let y = (firstFrame.minY + firstFrame.maxY) / 2
let path = NSBezierPath()
path.move(to: NSPoint(x: 0, y: y))
path.line(to: NSPoint(x: (textContainer?.size.width ?? 0), y: y))
path.lineWidth = 1
ProseTypography.tableBorderColor.setStroke()
path.stroke()
case let .table(columns):
let originX = (textContainer?.lineFragmentPadding ?? 0)
let path = NSBezierPath()
for offset in columns {
let x = originX + offset
path.move(to: NSPoint(x: x, y: firstFrame.minY))
path.line(to: NSPoint(x: x, y: lastFrame.maxY))
}
let ys = [firstFrame.minY] + frames.map(\.maxY)
for y in ys {
path.move(to: NSPoint(x: originX, y: y))
path.line(to: NSPoint(x: originX + (columns.last ?? 0), y: y))
}
path.lineWidth = 1
ProseTypography.tableBorderColor.setStroke()
path.stroke()
}
}
}
/// Line frames for a document character range, engine-agnostic: TK2
/// fragments when present, else TK1 boundingRect per character line
/// (lineFragmentRect returns degenerate rects mid-layout on TK1 here).
func framesForRange(_ docRange: NSRange) -> [CGRect] {
if let tlm = textLayoutManager, let tcm = tlm.textContentManager {
let docStart = tcm.documentRange.location
var frames: [CGRect] = []
tlm.enumerateTextLayoutFragments(from: docStart) { fragment in
let tr = fragment.rangeInElement
let loc = tcm.offset(from: docStart, to: tr.location)
let len = tcm.offset(from: tr.location, to: tr.endLocation)
if NSIntersectionRange(NSRange(location: loc, length: len), docRange).length > 0 {
frames.append(fragment.layoutFragmentFrame)
}
return true
}
return frames
}
guard let layoutManager, let container = textContainer else { return [] }
let nsText = string as NSString
var frames: [CGRect] = []
var lineStart = docRange.location
while lineStart < NSMaxRange(docRange) {
let lineRange = nsText.lineRange(for: NSRange(location: lineStart, length: 0))
let clamped = NSIntersectionRange(lineRange, docRange)
guard clamped.length > 0 else { break }
let glyphRange = layoutManager.glyphRange(forCharacterRange: clamped, actualCharacterRange: nil)
frames.append(layoutManager.boundingRect(forGlyphRange: glyphRange, in: container))
lineStart = NSMaxRange(lineRange)
}
return frames
}
override func updateTrackingAreas() {
super.updateTrackingAreas()
if hoverTrackingArea == nil {
let area = NSTrackingArea(
rect: bounds, options: [.mouseMoved, .activeAlways, .inVisibleRect],
owner: self, userInfo: nil,
)
addTrackingArea(area)
hoverTrackingArea = area
}
}
// MARK: Click discrimination (#68)
override func mouseDown(with event: NSEvent) {
let point = convert(event.locationInWindow, from: nil)
if event.modifierFlags.contains(.command) {
let index = characterIndex(for: point)
if index != NSNotFound, let url = textStorage?.attribute(.link, at: index, effectiveRange: nil) as? URL {
NSWorkspace.shared.open(url)
return
}
}
super.mouseDown(with: event)
// NSTextView's mouseDown consumes the mouse-up in its own tracking
// loop — the click is complete once super returns. Tap = single
// click, no drag, no selection formed (#68: drag-select never
// registers; triple-click paragraph select has length > 0).
let upScreen = NSEvent.mouseLocation
let upWindow = window.map { $0.convertFromScreen(NSRect(origin: upScreen, size: .zero)).origin }
?? event.locationInWindow
let downWindow = event.locationInWindow
let moved = hypot(upWindow.x - downWindow.x, upWindow.y - downWindow.y)
guard event.clickCount == 1, moved < 4, selectedRange().length == 0 else { return }
let index = characterIndex(for: point)
guard index != NSNotFound, let bound = bound(containing: index) else { return }
onEditIntent?(bound.sourceRange.location)
}
// MARK: Scroll tracking (#68 flip-back mapping)
override func reflectScrolledClipView(_ clipView: NSClipView) {
super.reflectScrolledClipView(clipView)
let visible = NSPoint(x: 0, y: visibleRect.minY + 1)
let index = characterIndex(for: visible)
if index != NSNotFound, let bound = bound(containing: index) {
stateBox?.topSourceLocation = bound.sourceRange.location
}
}
// MARK: Image hover popover (#69 floor)
override func mouseMoved(with event: NSEvent) {
super.mouseMoved(with: event)
let point = convert(event.locationInWindow, from: nil)
let index = characterIndex(for: point)
guard index != NSNotFound, let bound = bound(containing: index), let url = bound.imageURL else {
popover?.close()
popover = nil
return
}
guard popover == nil else { return }
let pop = NSPopover()
pop.behavior = .transient
pop.contentViewController = NSHostingController(rootView: ImagePopoverView(url: url))
pop.contentSize = NSSize(width: 480, height: 360)
pop.show(relativeTo: CGRect(origin: point, size: NSSize(width: 1, height: 1)), of: self, preferredEdge: .maxY)
popover = pop
}
override func mouseExited(with event: NSEvent) {
super.mouseExited(with: event)
popover?.close()
popover = nil
}
}
/// The hover popover's content: loads the image off-main, scaled to fit.
private struct ImagePopoverView: View {
let url: URL
@State private var image: NSImage?
var body: some View {
Group {
if let image {
Image(nsImage: image)
.resizable()
.scaledToFit()
} else {
ProgressView()
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
.frame(maxWidth: 480, maxHeight: 360)
.task {
// Data off-main (Sendable); NSImage decoded on-main.
let data = await Task.detached(priority: .userInitiated) {
try? Data(contentsOf: url)
}.value
if let data {
image = NSImage(data: data)
}
}
}
}
+157 -6
View File
@@ -3,18 +3,49 @@
// Museion
//
// #17 (S1.1): Settings — the Museion Home path, repoint-only (ADR-0004).
// #71 (map #20 / #70): the Typography section — three role slots (Body /
// Headings / Code), each {face, size}: a Picker over every installed font
// family (defaults are being auditioned; shrinks to a curated shortlist
// once they settle) + a size field. UserDefaults persistence; re-picking a
// face is reset. Chrome stays system.
//
import AppKit
import SwiftUI
/// Settings pane. #17 scope: the Home control only — further settings arrive
/// with their tickets. Choosing a folder repoints Museion at that root;
/// content is never moved.
/// Settings pane. Home control per #17; typography slots per #70.
struct SettingsPaneView: View {
@Binding var home: URL
/// Full family list once per pane lifetime (#70: full list while
/// auditioning; the picker's current selection must be listed even when
/// NSFontManager omits it — Iowan Old Style is such a case).
private var families: [String] {
let current = [
UserDefaults.standard.string(forKey: "proseBodyFace"),
UserDefaults.standard.string(forKey: "proseHeadingsFace"),
UserDefaults.standard.string(forKey: "proseCodeFace"),
].compactMap(\.self)
let all = NSFontManager.shared.availableFontFamilies
return Array((current + all).uniqued())
}
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 24) {
contentSection
typographySection
flowSection
}
.padding(24)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
.background(DesignTokens.background)
}
// MARK: Home (#17)
private var contentSection: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Content")
.font(.system(size: 13, weight: .semibold))
@@ -33,9 +64,49 @@ struct SettingsPaneView: View {
.font(.callout)
.foregroundStyle(DesignTokens.muted)
}
.padding(24)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.background(DesignTokens.background)
}
// MARK: Text flow (#71 polish)
private var flowSection: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Text Flow")
.font(.system(size: 13, weight: .semibold))
Text(
"Reading rhythm. Line height scales the leading everywhere; the two spacings shape reading mode only — in the editor, your blank lines are the separator."
)
.font(.callout)
.foregroundStyle(DesignTokens.muted)
FlowRow(label: "Line height", key: "proseLineHeight", range: 1 ... 2, step: 0.05)
FlowRow(label: "Space after ¶", key: "proseParagraphSpacingLines", range: 0 ... 4, step: 0.25)
FlowRow(label: "Space after headings", key: "proseHeadingSpacingLines", range: 0 ... 6, step: 0.25)
}
}
// MARK: Typography (#70)
private var typographySection: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Typography")
.font(.system(size: 13, weight: .semibold))
Text(
"The three prose roles. Both the editor and reading mode use them; a missing face falls back to the system font.",
)
.font(.callout)
.foregroundStyle(DesignTokens.muted)
SlotRow(
label: "Body", faceKey: "proseBodyFace", sizeKey: "proseBodySize",
families: families,
)
SlotRow(
label: "Headings", faceKey: "proseHeadingsFace", sizeKey: "proseHeadingsSize",
families: families,
)
SlotRow(
label: "Code", faceKey: "proseCodeFace", sizeKey: "proseCodeSize",
families: families,
)
}
}
private func chooseHome() {
@@ -49,3 +120,83 @@ struct SettingsPaneView: View {
}
}
}
/// One role slot: face picker (full family list) + size stepper.
private struct SlotRow: View {
let label: String
let faceKey: String
let sizeKey: String
let families: [String]
var body: some View {
HStack(spacing: 10) {
Text(label)
.font(.system(size: 12, weight: .semibold))
.frame(width: 76, alignment: .leading)
Picker("", selection: faceBinding) {
ForEach(families, id: \.self) { family in
Text(family).tag(family)
}
}
.labelsHidden()
.frame(maxWidth: 320)
TextField("", value: sizeBinding, format: .number)
.textFieldStyle(.roundedBorder)
.frame(width: 56)
Text("pt")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
}
private var faceBinding: Binding<String> {
Binding(
get: { UserDefaults.standard.string(forKey: faceKey) ?? "" },
set: { UserDefaults.standard.set($0, forKey: faceKey) },
)
}
private var sizeBinding: Binding<Double> {
Binding(
get: { UserDefaults.standard.double(forKey: sizeKey) },
set: { UserDefaults.standard.set(max(6, min(72, $0)), forKey: sizeKey) },
)
}
}
/// One flow knob: label + numeric field (UserDefaults-backed).
private struct FlowRow: View {
let label: String
let key: String
let range: ClosedRange<Double>
let step: Double
var body: some View {
HStack(spacing: 10) {
Text(label)
.font(.system(size: 12, weight: .semibold))
.frame(width: 150, alignment: .leading)
TextField("", value: binding, format: .number.precision(.fractionLength(2)))
.textFieldStyle(.roundedBorder)
.frame(width: 64)
Text("× body line")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
}
private var binding: Binding<Double> {
Binding(
get: { UserDefaults.standard.double(forKey: key) },
set: { UserDefaults.standard.set(max(range.lowerBound, min(range.upperBound, $0)), forKey: key) },
)
}
}
private extension Array {
/// Order-preserving dedupe (face lists merge current + installed).
func uniqued() -> [Element] where Element: Hashable {
var seen = Set<Element>()
return filter { seen.insert($0).inserted }
}
}
+1
View File
@@ -23,6 +23,7 @@ Owned by the root AGENTS.md contract.
- `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.
- `ReadingPresenterTests.swift` (#71) — renderer coverage with inline fixture strings (no file fixtures): headings/paragraph split + markup hidden, auto-renumber (`1. 1. 1.` → 1/2/3), nesting, source-range monotonicity + exact chunk offsets (the click→edit map), table/quote/HR attribute presence (`NSTextTableBlock`/`QuoteTextBlock`/`RuleTextBlock` via paragraphStyle `textBlocks`), fenced-code font, link retention, image payload + post-folder resolution, footnote fallback, soft-joined lines, kitchen-sink smoke.
## Verification
+202
View File
@@ -0,0 +1,202 @@
//
// ReadingPresenterTests.swift
// MuseionTests
//
// #71 (map #20): renderer coverage — the smallest checks that fail if the
// block classification, auto-renumbering, source-range mapping, or inline
// interpretation break. Kitchen-sink fixture strings inline (no file
// fixtures per the suite's convention).
//
import AppKit
@testable import Museion
import Testing
@MainActor
struct ReadingPresenterTests {
/// Blank-line split + heading fonting + markup hidden.
@Test
func `headings and paragraphs`() {
let doc = ReadingPresenter.document(for: "# Title\n\nBody with _em_.\n\n### Deep", resolvingImagesIn: nil)
#expect(doc.bounds.count == 3)
let flat = doc.content.string
#expect(!flat.contains("#"))
#expect(flat.contains("Title"))
#expect(flat.contains("Body with em."))
}
/// Auto-renumbering: `1. 1. 1.` renders 1, 2, 3; source never rewritten.
@Test
func `ordered list auto renumbers`() {
let src = "1. one\n1. two\n1. three"
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
#expect(doc.bounds.count == 1)
#expect(doc.content.string.contains("1. one"))
#expect(doc.content.string.contains("2. two"))
#expect(doc.content.string.contains("3. three"))
#expect(!doc.content.string.contains("1. two"))
}
/// Nesting: deeper items indent further; mixed bullet/number nesting rides
/// the same path.
@Test
func `list nesting`() {
let src = "- top\n - nested\n- back"
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
#expect(doc.bounds.count == 1)
#expect(doc.content.string.contains("top"))
#expect(doc.content.string.contains("nested"))
}
/// The #68 click→edit map: block source ranges are monotonic and cover
/// every block; a location mid-document maps to its containing block.
@Test
func `source ranges map blocks`() {
let src = "# A\n\nfirst para\n\n- l1\n- l2\n\nlast para"
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
#expect(doc.bounds.count == 4)
let locations = doc.bounds.map(\.sourceRange.location)
#expect(locations == locations.sorted())
// "last para" starts at its own chunk offset
let nsSrc = src as NSString
let expected = nsSrc.range(of: "last para").location
#expect(doc.bounds[3].sourceRange.location == expected)
}
/// Tables render as a mono grid: decoration carries column offsets,
/// header/body rows are padded columns of text.
@Test
func `table renders`() throws {
let src = "| A | B |\n| --- | --- |\n| one | two |"
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
#expect(doc.bounds.count == 1)
let lines = doc.content.string.components(separatedBy: "\n")
#expect(lines.count == 2)
#expect(lines[0].contains("A"))
#expect(lines[1].contains("one"))
// alignment: same column starts across rows
let colA0 = try lines[0].distance(from: lines[0].startIndex, to: #require(lines[0].firstIndex(of: "A")))
let colA1 = try lines[1].distance(from: lines[1].startIndex, to: #require(lines[1].firstIndex(of: "o")))
#expect(colA0 == colA1)
guard case let .table(columns)? = doc.bounds[0].decoration else {
Issue.record("expected table decoration")
return
}
#expect(columns.count == 3) // two columns + closing edge
}
/// Fenced code: mono face, markers hidden, content intact.
@Test
func `fenced code`() {
let src = "```swift\nlet x = 1\n```"
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
#expect(!doc.content.string.contains("```"))
#expect(doc.content.string.contains("let x = 1"))
let attrs = doc.content.attributes(at: 0, effectiveRange: nil)
#expect((attrs[.font] as? NSFont)?.fontName == ProseTypography.codeFont.fontName)
}
/// Blockquote: markers hidden, quote decoration on the bound.
@Test
func blockquote() {
let src = "> quoted _words_\n>> deeper"
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
#expect(!doc.content.string.contains(">"))
#expect(doc.content.string.contains("quoted words"))
guard case .quote? = doc.bounds[0].decoration else {
Issue.record("expected quote decoration")
return
}
}
/// Links styled + attribute retained (⌘-click opens).
@Test
func `links retained`() {
let src = "See [the docs](https://example.de) now"
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
let range = (doc.content.string as NSString).range(of: "the docs")
#expect(range.location != NSNotFound)
let attrs = doc.content.attributes(at: range.location, effectiveRange: nil)
#expect(attrs[.link] != nil)
}
/// Images: hover payload carried on the bound, syntax stays text.
@Test
func `image hover payload`() {
let src = "![alt text](assets/img.png)"
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
#expect(doc.bounds.count == 1)
#expect(doc.bounds[0].imageURL != nil)
#expect(doc.content.string.contains("alt text"))
}
/// Image URL resolution against the post folder (#71).
@Test
func `image URL resolves against post folder`() {
let src = "![x](assets/img.png)"
let folder = URL(fileURLWithPath: "/tmp/posts/example")
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: folder)
#expect(doc.bounds[0].imageURL?.path == "/tmp/posts/example/assets/img.png")
}
/// Footnotes are the one fallback: source text, no transformation.
@Test
func `footnotes stay fallback`() {
let src = "Text with note[^1]\n\n[^1]: the note"
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
#expect(doc.content.string.contains("[^1]"))
}
/// HR: rule decoration, matcher shared with editing.
@Test
func `horizontal rule`() {
let src = "above\n\n* * *\n\nbelow"
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
#expect(doc.bounds.count == 3)
guard case .rule? = doc.bounds[1].decoration else {
Issue.record("expected rule decoration")
return
}
}
/// Soft-joined lines: one paragraph, single spaces.
@Test
func `soft joined lines`() {
let src = "line one\nline two"
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
#expect(doc.bounds.count == 1)
#expect(doc.content.string == "line one line two")
}
/// Kitchen-sink smoke: every construct in one document without crashing.
@Test
func `kitchen sink renders`() {
let sink = """
# Sink
- bullet
- another
1. one
1. two
> quote
```txt
code
```
| H |
| --- |
| c |
![i](a.png)
[link](https://x.de)
* * *
"""
let doc = ReadingPresenter.document(for: sink, resolvingImagesIn: nil)
#expect(doc.bounds.count >= 9)
}
}
@@ -0,0 +1,42 @@
# Issue 71 — Task: land the reading toggle build (S1.2)
> **Date:** 2026-10-05
> **Type:** issue
> **Reference:** [Wayfinder map #20](https://git.babylondreams.de/AlexKucera/Museion/issues/20) · decisions [#68](https://git.babylondreams.de/AlexKucera/Museion/issues/68) · [#69](https://git.babylondreams.de/AlexKucera/Museion/issues/69) · [#70](https://git.babylondreams.de/AlexKucera/Museion/issues/70)
## What landed
Branch `wayfinder/71-reading-toggle`, commits `4c91733` (feature) + `c4555ed` (DOX).
**New files**
- `Museion/ReadingPresenter.swift` — block-aware reading renderer (ADR-0010 stance): blank-line split → one block per chunk; classification HR → list run → quote run → flow. Lists (bullets + ordered + nesting + auto-renumber) are one rendering path; headings h1/h2/`###`/floor per #69/#70; `QuoteTextBlock` hairline, `RuleTextBlock` HR, `NSTextTable` tables with delimiter-row alignment; images as hover-payload blocks; footnotes the one fallback. `document(for:resolvingImagesIn:)` builds the single storage with per-block `Bound{docRange, sourceRange, imageURL}`.
- `Museion/ReadingSurface.swift` — `ReadingCanvasView`: read-only selectable NSTextView. Tap-to-edit runs after `super.mouseDown` returns (NSTextView's tracking loop consumes the mouse-up — `mouseUp` overrides never fire); ⌘-click opens links; scroll tracking feeds the flip-back caret; image hover NSPopover loads off-main.
- `Museion/ProseTypography.swift` — the #70 three role slots (Body/Headings/Code, {face,size} each, UserDefaults six values, member-based font resolution, silent system fallback).
- `MuseionTests/ReadingPresenterTests.swift` — 15 renderer tests (inline fixtures).
- `spike/prose/kitchen-sink.md` + `assets/kitchen-sink.png` — the #69 calibration piece.
**Modified**
- `PostEditorView.swift` — Read⇄Edit toolbar button (far left), View menu + ⌘R via `.toggleReadingMode` notification; transient reading state; drafts included (draft mirror); flip-back caret hint (location + token) applied once per token.
- `ProsePresenter.swift` — headings/dimmed-syntax/body rewired through the shared slots (both prose surfaces read the same tokens, #70).
- `SettingsPaneView.swift` — Typography section: three `SlotRow`s (family picker + size field).
- `MuseionApp.swift` — View CommandMenu; `ProseTypography.registerDefaults()` in `AppGateState.init`.
- `EditorSession.swift` — `folderURL` for image resolution.
## Verification
- Build + full test suite green: 94 unit + UI smoke (`xcodebuild … test`).
- Runtime probe (temporary hosted test, deleted): kitchen-sink 24 blocks/11.3 ms; PERF-3k 128 blocks/17.2 ms, ×10 in 165.8 ms; zero marker leakage across all three corpus files.
- Live-app probe (System Events): post opens, Read renders (markers hidden, `1. 1. 1.` → 1/2/3 verified via AX value), ⌘R menu toggles back, click-on-paragraph flips to editing with caret in-document, file byte-identical (`cmp`) after the full round-trip.
- Typography pixel-verified on screenshot: heading ink 20px vs body 15-16px at 1× — the 26/20/17 ladder renders.
## Deviations from the decisions
- **Font resolution** (#70 said family+weight lookup): `font(withFamily:traits:weight:)` misresolves Concourse OT — Thin and Book both advertise weight 4 and the manager picks Thin. Faces resolve through the member list instead (prefer Book/Regular style, else closest to weight 5). The #70-pinned PS names (ConcourseOT3Book etc.) fall out of the same path.
- **Heading bold**: the first build lost heading weight (member resolution returns Book); `headingFont(size:)` now bolds — matching #19's weight 8/9 stance and #70's "Iowan Old Style bold".
- **Table alignment**: honored (not left-defaulted) — the delimiter row is parsed anyway; alignment was ~4 lines.
- **Click-to-edit discrimination**: implemented as single-click (`clickCount == 1`) + no selection + <4pt move, checked after `super.mouseDown` returns. The time-window check from the plan was dropped — the click is complete when the tracking loop exits, making it redundant.
## Notes for calibration (#72)
- The map's fog item "curated shortlist" now has a home: Settings → Typography lists all families with current faces prepended (Iowan Old Style is not in `availableFontFamilies` — the prepend is load-bearing).
- Mapping (entry scroll + flip-back caret) shipped in full; no jank fallback was needed at build time — #72 arbitrates.
+1
View File
@@ -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-05 | issue | [20261005-issue71-reading-toggle_log.md](20261005-issue71-reading-toggle_log.md) | #71 reading toggle: block-aware renderer, tap-to-edit canvas, typography slots, kitchen-sink — 94 tests green |
| 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 |
Binary file not shown.

After

Width:  |  Height:  |  Size: 651 B

+66
View File
@@ -0,0 +1,66 @@
# Kitchen sink
This post exercises every construct the reading renderer must render — one of each, plus the nesting and auto-numbering cases. Not for reading pleasure; for calibration of constructs absent from the corpus.
## Lists
Bulleted, ordered, nested, and deliberately mis-numbered source (`1. 1. 1.` must read 1, 2, 3):
- top bullet one
- top bullet two
- nested bullet two-one
- nested bullet two-two
- deeper nesting, four-space style
- back to top level
1. first
1. second, source says 1
1. third, source still says 1
1. outer one
1. inner one
1. inner two
2. outer two
Mixed nesting:
2. numbered top
- bullet under a number
- bullet deeper
## Table
| Construct | State | Notes |
| --- | :---: | --- |
| bullets | rendered | hanging indent |
| ordered | rendered | auto-renumbered |
| table | rendered | 1px border, centred `---:` cell |
## Quote
> A blockquote line carrying _italic_ and `code`.
>> Nested quote: one level deeper via the doubled marker.
## Code
```swift
let calm = true
// fenced block: mono face, no inline parse
```
## Image
Hover shows the picture; the line itself stays text:
![A picture worth hovering for](assets/kitchen-sink.png)
## Inline
A paragraph with _emphasis_, **strong**, `inline code`, and a [link](https://babylondreams.de) — plain click drops to editing per #68; ⌘-click opens.
## Rule
* * *
End of the sink.