From 4c91733e78fb104c9420f3f4d12bc378f4f6cee3 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Mon, 5 Oct 2026 15:51:28 +0200 Subject: [PATCH 01/14] =?UTF-8?q?feat(editor):=20land=20reading=20toggle?= =?UTF-8?q?=20=E2=80=94=20render,=20interact,=20typography=20slots=20(S1.2?= =?UTF-8?q?=20#71)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Map #20 execution child, built per decisions #68/#69/#70: - ReadingPresenter: block-aware renderer (ADR-0010 stance) — blank-line split, one block per chunk; lists (bullets + ordered + nesting + auto-renumber via per-level counters — one rendering path), headings by level (h1 = slot size, h2 = 0.77x, ### = body+1, #### floors at bold body), HR via the editing syntaxOnly predicate, fenced code, blockquotes (QuoteTextBlock hairline), tables (NSTextTable 1px border, delimiter-row alignment), images (hover payload), links styled + retained. Footnotes stay fallback. Source ranges ride every block (click→edit map). - ReadingSurface: read-only selectable NSTextView canvas (#68: a presentation of the same TextKit2 document). Tap with no selection after mouseDown returns = edit intent at the clicked block (the tracking-loop fix); ⌘-click opens links; scroll tracking feeds the flip-back caret; image hover NSPopover loads off-main. - ProseTypography (#70): three role slots — Body / Headings / Code — each {face, size}, UserDefaults six values, member-based font resolution (family+weight lookup misresolves Concourse Book→Thin), silent system fallback; both prose surfaces read them; editing presenter's headings + dimmed syntax rewired through the slots. - PostEditorView: Read⇄Edit toolbar button (far left) + View menu "Toggle Reading Mode" + ⌘R; reading state transient per open; drafts included (draft mirror); flip-back caret hint applied once per token. - SettingsPaneView: Typography section — three slot rows (family picker incl. current face not in the installed list + size field). - kitchen-sink.md (+png): corpus piece exercising constructs absent from the eight posts, per #69. Verified: 94 unit tests (renderer classification, renumbering, source ranges, fallbacks) + UI smoke; PERF-3k renders 128 blocks in ~17 ms; live-app probe — Read renders kitchen-sink markers-hidden, renumbered, byte-stable file after full round-trip; click-to-edit flips at the clicked paragraph; typography ladder pixel-verified (20/15 ink px). --- CONTEXT.md | 4 + Museion/EditorSession.swift | 7 + Museion/MuseionApp.swift | 9 + Museion/PostEditorView.swift | 122 +++++- Museion/ProsePresenter.swift | 34 +- Museion/ProseTypography.swift | 148 ++++++++ Museion/ReadingPresenter.swift | 465 +++++++++++++++++++++++ Museion/ReadingSurface.swift | 237 ++++++++++++ Museion/SettingsPaneView.swift | 116 +++++- MuseionTests/ReadingPresenterTests.swift | 218 +++++++++++ spike/prose/assets/kitchen-sink.png | Bin 0 -> 651 bytes spike/prose/kitchen-sink.md | 66 ++++ 12 files changed, 1393 insertions(+), 33 deletions(-) create mode 100644 Museion/ProseTypography.swift create mode 100644 Museion/ReadingPresenter.swift create mode 100644 Museion/ReadingSurface.swift create mode 100644 MuseionTests/ReadingPresenterTests.swift create mode 100644 spike/prose/assets/kitchen-sink.png create mode 100644 spike/prose/kitchen-sink.md diff --git a/CONTEXT.md b/CONTEXT.md index 35efa1e..f8c6140 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -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**: diff --git a/Museion/EditorSession.swift b/Museion/EditorSession.swift index 56f9974..aaabcb7 100644 --- a/Museion/EditorSession.swift +++ b/Museion/EditorSession.swift @@ -28,6 +28,13 @@ final class EditorSession { private let home: URL private let debounce: Duration + /// The post's folder (`/posts/`) — 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). diff --git a/Museion/MuseionApp.swift b/Museion/MuseionApp.swift index cedc306..3382200 100644 --- a/Museion/MuseionApp.swift +++ b/Museion/MuseionApp.swift @@ -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") { diff --git a/Museion/PostEditorView.swift b/Museion/PostEditorView.swift index f7f9eef..34c3159 100644 --- a/Museion/PostEditorView.swift +++ b/Museion/PostEditorView.swift @@ -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 { @@ -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) @@ -228,6 +317,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 +340,7 @@ struct ProseTextView: NSViewRepresentable { weak var textView: NSTextView? var sessionRef: EditorSession? var loadedGeneration = -1 + var appliedCaretToken = -1 init(representable: ProseTextView) { onEdit = representable.onEdit @@ -250,7 +352,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 { diff --git a/Museion/ProsePresenter.swift b/Museion/ProsePresenter.swift index 7a4dae9..46bfcec 100644 --- a/Museion/ProsePresenter.swift +++ b/Museion/ProsePresenter.swift @@ -71,30 +71,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 +108,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))) } diff --git a/Museion/ProseTypography.swift b/Museion/ProseTypography.swift new file mode 100644 index 0000000..569554b --- /dev/null +++ b/Museion/ProseTypography.swift @@ -0,0 +1,148 @@ +// +// 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 + + /// 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, + ]) + } + + 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: 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 + } +} diff --git a/Museion/ReadingPresenter.swift b/Museion/ReadingPresenter.swift new file mode 100644 index 0000000..01031c5 --- /dev/null +++ b/Museion/ReadingPresenter.swift @@ -0,0 +1,465 @@ +// +// 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 { + /// 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? + } + + /// 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? + } + + /// 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) { + if out.length > 0, !out.string.hasSuffix("\n") { + out.append(NSAttributedString(string: "\n", attributes: ProseTypography.bodyAttributes)) + } + let start = out.length + out.append(block.content) + let image = block.imageURL.flatMap { raw -> URL? in + guard raw.scheme == nil, let postFolder else { return raw } + return postFolder.appendingPathComponent(raw.path) + } + bounds.append(Bound( + docRange: NSRange(location: start, length: out.length - start), + sourceRange: block.sourceRange, + imageURL: image, + )) + } + 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). + static func blocks(for text: String) -> [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)) + } + 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) -> Block { + if let url = imageURL(in: chunk) { + return Block(content: inlineParse(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) + } + 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) + } + return Block(content: flowContent(lines, first: first), sourceRange: sourceRange, imageURL: nil) + } + + // MARK: Flow blocks + + private static func flowContent(_ lines: [String], first: String) -> NSAttributedString { + if let level = headingLevel(first) { + let body = first.drop { $0 == "#" }.trimmingCharacters(in: .whitespaces) + return headingContent(body, level: level) + } + if first.hasPrefix("```") { + let inner = lines.dropFirst().dropLast(hasClosingFence(lines) ? 1 : 0) + return codeContent(inner.joined(separator: "\n")) + } + if lines.count >= 2, isTableDelimiterRow(lines[1]), let table = tableContent(lines) { + return table + } + // 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: " ") + return inlineParse(joined) + } + + 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.paragraphSpacing = level <= 2 ? 10 : 8 + 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.paragraphSpacing = 10 + 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 { + let ps = NSMutableParagraphStyle() + ps.textBlocks = [RuleTextBlock()] + 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.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 { + let out = NSMutableAttributedString() + let quoteBlock = QuoteTextBlock() + for (index, line) in lines.enumerated() { + let depth = blockquoteDepth(line) + let indent = CGFloat(6 + (depth - 1) * 18) + let ps = NSMutableParagraphStyle() + ps.textBlocks = [quoteBlock] + 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: simple 1px-bordered NSTextTable; delimiter-row + + // alignment honored — cheap once the delimiter is parsed anyway) + + 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 table = NSTextTable() + table.numberOfColumns = header.count + table.collapsesBorders = true + table.setBorderColor(ProseTypography.tableBorderColor) + table.setWidth(1, type: .absolute, for: .border) + let out = NSMutableAttributedString() + var row = 0 + for (index, line) in lines.enumerated() { + if index == 1 { + continue + } // delimiter row + let cells = tableCells(line) + for column in 0 ..< header.count { + let text = column < cells.count ? cells[column] : "" + let cell = NSTextTableBlock( + table: table, startingRow: row, rowSpan: 1, + startingColumn: column, columnSpan: 1 + ) + cell.setWidth(1, type: .absolute, for: .border) + let ps = NSMutableParagraphStyle() + ps.textBlocks = [cell] + ps.alignment = aligns[column] + let attrs: [NSAttributedString.Key: Any] = [ + .font: row == 0 ? ProseTypography.boldBodyFont : ProseTypography.bodyFont, + .paragraphStyle: ps, + .foregroundColor: ProseTypography.foregroundColor, + ] + out.append(NSAttributedString( + string: text + (column == header.count - 1 ? "\n" : ""), + attributes: attrs + )) + } + row += 1 + } + return out + } + + 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 + } + + // 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])) + } +} + +/// Hairline-left text block for blockquotes (#69). +final nonisolated class QuoteTextBlock: NSTextBlock { + override func drawBackground( + withFrame frameRect: NSRect, in _: NSView?, + characterRange _: NSRange, layoutManager _: NSLayoutManager, + ) { + let path = NSBezierPath() + path.move(to: NSPoint(x: frameRect.minX + 2, y: frameRect.minY)) + path.line(to: NSPoint(x: frameRect.minX + 2, y: frameRect.maxY)) + path.lineWidth = 2 + ProseTypography.quoteRuleColor.setStroke() + path.stroke() + } +} + +/// Full-width hairline text block for horizontal rules (#69). +final nonisolated class RuleTextBlock: NSTextBlock { + override func drawBackground( + withFrame frameRect: NSRect, in _: NSView?, + characterRange _: NSRange, layoutManager _: NSLayoutManager, + ) { + let midY = frameRect.midY + let path = NSBezierPath() + path.move(to: NSPoint(x: frameRect.minX, y: midY)) + path.line(to: NSPoint(x: frameRect.maxX, y: midY)) + path.lineWidth = 1 + ProseTypography.tableBorderColor.setStroke() + path.stroke() + } +} diff --git a/Museion/ReadingSurface.swift b/Museion/ReadingSurface.swift new file mode 100644 index 0000000..f25cca4 --- /dev/null +++ b/Museion/ReadingSurface.swift @@ -0,0 +1,237 @@ +// +// 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] + 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 + tv.onEditIntent = onEditIntent + tv.stateBox = stateBox + context.coordinator.canvas = tv + 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 = "" + } +} + +/// 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 } + } + + 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) + } + } + } +} diff --git a/Museion/SettingsPaneView.swift b/Museion/SettingsPaneView.swift index 3b2743b..ec5c8e5 100644 --- a/Museion/SettingsPaneView.swift +++ b/Museion/SettingsPaneView.swift @@ -3,18 +3,48 @@ // 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 + } + .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 +63,32 @@ struct SettingsPaneView: View { .font(.callout) .foregroundStyle(DesignTokens.muted) } - .padding(24) - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) - .background(DesignTokens.background) + } + + // 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 +102,54 @@ 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 { + Binding( + get: { UserDefaults.standard.string(forKey: faceKey) ?? "" }, + set: { UserDefaults.standard.set($0, forKey: faceKey) }, + ) + } + + private var sizeBinding: Binding { + Binding( + get: { UserDefaults.standard.double(forKey: sizeKey) }, + set: { UserDefaults.standard.set(max(6, min(72, $0)), forKey: sizeKey) }, + ) + } +} + +private extension Array { + /// Order-preserving dedupe (face lists merge current + installed). + func uniqued() -> [Element] where Element: Hashable { + var seen = Set() + return filter { seen.insert($0).inserted } + } +} diff --git a/MuseionTests/ReadingPresenterTests.swift b/MuseionTests/ReadingPresenterTests.swift new file mode 100644 index 0000000..e36049b --- /dev/null +++ b/MuseionTests/ReadingPresenterTests.swift @@ -0,0 +1,218 @@ +// +// 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 NSTextTable blocks with header bold. + @Test + func `table renders`() { + let src = "| A | B |\n| --- | --- |\n| one | two |" + let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil) + #expect(doc.bounds.count == 1) + #expect(doc.content.string.contains("one")) + #expect(doc.content.string.contains("two")) + let hasTableBlock = doc.content.enumerateAttribute( + .paragraphStyle, in: NSRange(location: 0, length: doc.content.length), + ) { value, _, stop in + if let ps = value as? NSParagraphStyle, ps.textBlocks.contains(where: { $0 is NSTextTableBlock }) { + stop.pointee = true + } + } + _ = hasTableBlock // enumerate returns Void; assertion below is the check + // direct check: at least one NSTextTableBlock anywhere + var found = false + doc.content.enumerateAttribute( + .paragraphStyle, in: NSRange(location: 0, length: doc.content.length), + ) { value, _, _ in + if let ps = value as? NSParagraphStyle, ps.textBlocks.contains(where: { $0 is NSTextTableBlock }) { + found = true + } + } + #expect(found) + } + + /// 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, hairline block attached. + @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")) + var foundQuoteBlock = false + doc.content.enumerateAttribute( + .paragraphStyle, in: NSRange(location: 0, length: doc.content.length), + ) { value, _, _ in + if let ps = value as? NSParagraphStyle, ps.textBlocks.contains(where: { $0 is QuoteTextBlock }) { + foundQuoteBlock = true + } + } + #expect(foundQuoteBlock) + } + + /// 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: hairline block, 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) + var foundRule = false + doc.content.enumerateAttribute( + .paragraphStyle, in: NSRange(location: 0, length: doc.content.length), + ) { value, _, _ in + if let ps = value as? NSParagraphStyle, ps.textBlocks.contains(where: { $0 is RuleTextBlock }) { + foundRule = true + } + } + #expect(foundRule) + } + + /// 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) + } +} diff --git a/spike/prose/assets/kitchen-sink.png b/spike/prose/assets/kitchen-sink.png new file mode 100644 index 0000000000000000000000000000000000000000..cc710c28eded6ed354b023ae653563011b34f093 GIT binary patch literal 651 zcmeAS@N?(olHy`uVBq!ia0y~yV0-|?Ivh+uktuV&^D;0n1$nwShE&{od)Sbd!GMQ( zLz48giMortcD5}%ZWmpo8oX*0&^-j~zuVH?PO4cro4-6RGA_96bOtbyF?hQAxvXg^lO{ literal 0 HcmV?d00001 diff --git a/spike/prose/kitchen-sink.md b/spike/prose/kitchen-sink.md new file mode 100644 index 0000000..e33e88f --- /dev/null +++ b/spike/prose/kitchen-sink.md @@ -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. From c4555ed8109747415a57191dbe8c12e909e6d65d Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Mon, 5 Oct 2026 15:52:03 +0200 Subject: [PATCH 02/14] docs(dox): record reading-mode surfaces in app + tests AGENTS.md (#71) --- Museion/AGENTS.md | 7 ++++--- MuseionTests/AGENTS.md | 1 + 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/Museion/AGENTS.md b/Museion/AGENTS.md index 6d85472..b05e056 100644 --- a/Museion/AGENTS.md +++ b/Museion/AGENTS.md @@ -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//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//.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//` 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//.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) diff --git a/MuseionTests/AGENTS.md b/MuseionTests/AGENTS.md index b781932..5752de1 100644 --- a/MuseionTests/AGENTS.md +++ b/MuseionTests/AGENTS.md @@ -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 From 36858bcf1d7712f64b4ee40388faf6130aca3716 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Mon, 5 Oct 2026 15:52:40 +0200 Subject: [PATCH 03/14] docs(devlog): #71 session log --- AGENTS.md | 1 + .../20261005-issue71-reading-toggle_log.md | 42 +++++++++++++++++++ docs/devlog/INDEX.md | 1 + 3 files changed, 44 insertions(+) create mode 100644 docs/devlog/20261005-issue71-reading-toggle_log.md diff --git a/AGENTS.md b/AGENTS.md index 65c5a49..251983c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -178,6 +178,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu | 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) | diff --git a/docs/devlog/20261005-issue71-reading-toggle_log.md b/docs/devlog/20261005-issue71-reading-toggle_log.md new file mode 100644 index 0000000..116d39f --- /dev/null +++ b/docs/devlog/20261005-issue71-reading-toggle_log.md @@ -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. diff --git a/docs/devlog/INDEX.md b/docs/devlog/INDEX.md index 5336884..1c1c95c 100644 --- a/docs/devlog/INDEX.md +++ b/docs/devlog/INDEX.md @@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa | 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 | From c410c99bf83f0617350c880d6ae78e5841c2f8ec Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Mon, 5 Oct 2026 17:41:34 +0200 Subject: [PATCH 04/14] fix(editor): reading-mode layout + stale-reload defects (#71 follow-up) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Five root causes behind Alexander's calibration findings: - Wrap to column: both canvases had a fixed 640pt text container — clipped instead of wrapping when the editor column is narrower (library + mentor open). widthTracksTextView = true now; measure polish can return with calibration. - Tables: TextKit2 stacks NSTextTable rows vertically (each row its own content-width fragment — no grid). The reading canvas forces the TextKit1 bridge (replaceLayoutManager); probe-verified grid + column borders. Read-only canvas — nothing editing-grade lost. - Heading-tail: a chunk like "# Title" followed by body lines (single newline, legal markdown) dropped everything after line one. The heading now renders, then the remaining lines as a soft-joined paragraph. - Stale reload (data-loss vector): ProseTextView seeded from session.loadText (open-time snapshot) — after a reading⇄editing swap the recreated editor showed the pre-paste text, and a keystroke there flushed stale content over the user's real edits. Seeds from session.text (live) now. - Quote one-char-per-line: did not reproduce after the layout fixes; root cause was the broken layout state above. EditorSessionTests debounce flake (50ms margin under parallel load) passed on both re-runs — timing margin, not a regression. Full suite green (94 unit + UI smoke); lint clean. --- Museion/PostEditorView.swift | 13 ++++++++++--- Museion/ReadingPresenter.swift | 20 ++++++++++++++++---- Museion/ReadingSurface.swift | 10 ++++++++-- default.profraw | 0 4 files changed, 34 insertions(+), 9 deletions(-) create mode 100644 default.profraw diff --git a/Museion/PostEditorView.swift b/Museion/PostEditorView.swift index 34c3159..b6fcf21 100644 --- a/Museion/PostEditorView.swift +++ b/Museion/PostEditorView.swift @@ -278,8 +278,10 @@ 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 + // 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 = 12 tv.textContainerInset = NSSize(width: 0, height: 20) let scroll = NSScrollView() @@ -301,7 +303,12 @@ struct ProseTextView: NSViewRepresentable { // 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)) + // 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() diff --git a/Museion/ReadingPresenter.swift b/Museion/ReadingPresenter.swift index 01031c5..a9a2638 100644 --- a/Museion/ReadingPresenter.swift +++ b/Museion/ReadingPresenter.swift @@ -117,7 +117,19 @@ enum ReadingPresenter { private static func flowContent(_ lines: [String], first: String) -> NSAttributedString { if let level = headingLevel(first) { let body = first.drop { $0 == "#" }.trimmingCharacters(in: .whitespaces) - return headingContent(body, level: level) + 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) @@ -209,7 +221,7 @@ enum ReadingPresenter { item.append(inlineParse(marker.payload.trimmingCharacters(in: .whitespaces))) item.addAttribute( .paragraphStyle, value: ps, - range: NSRange(location: 0, length: item.length) + range: NSRange(location: 0, length: item.length), ) out.append(item) if index < lines.count - 1 { @@ -277,7 +289,7 @@ enum ReadingPresenter { let text = column < cells.count ? cells[column] : "" let cell = NSTextTableBlock( table: table, startingRow: row, rowSpan: 1, - startingColumn: column, columnSpan: 1 + startingColumn: column, columnSpan: 1, ) cell.setWidth(1, type: .absolute, for: .border) let ps = NSMutableParagraphStyle() @@ -290,7 +302,7 @@ enum ReadingPresenter { ] out.append(NSAttributedString( string: text + (column == header.count - 1 ? "\n" : ""), - attributes: attrs + attributes: attrs, )) } row += 1 diff --git a/Museion/ReadingSurface.swift b/Museion/ReadingSurface.swift index f25cca4..ecdffc4 100644 --- a/Museion/ReadingSurface.swift +++ b/Museion/ReadingSurface.swift @@ -64,8 +64,14 @@ struct ReadingSurface: NSViewRepresentable { tv.isVerticallyResizable = true tv.isHorizontallyResizable = false tv.autoresizingMask = [.width] - tv.textContainer?.containerSize = NSSize(width: 640, height: CGFloat.greatestFiniteMagnitude) - tv.textContainer?.widthTracksTextView = false + // Tables (#69) lay out correctly under TextKit1 only — TK2 stacks + // NSTextTable rows vertically (probed). The canvas is read-only, so + // nothing editing-grade is lost by forcing the TK1 bridge. + tv.textContainer?.replaceLayoutManager(NSLayoutManager()) + // 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 = 12 tv.textContainerInset = NSSize(width: 0, height: 20) let scroll = NSScrollView() diff --git a/default.profraw b/default.profraw new file mode 100644 index 0000000..e69de29 From 8992e2ade55eb2a2bd6562082fcd35cbb0c97c3c Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Mon, 5 Oct 2026 17:41:44 +0200 Subject: [PATCH 05/14] chore: drop accidentally-committed profraw, ignore it --- .gitignore | 1 + default.profraw | 0 2 files changed, 1 insertion(+) delete mode 100644 default.profraw diff --git a/.gitignore b/.gitignore index 36776af..c561bb9 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ DerivedData/ .DS_Store CLAUDE.md .claude/ +profraw diff --git a/default.profraw b/default.profraw deleted file mode 100644 index e69de29..0000000 From 4138bf22dd8d336d6b303ae61040085ee114ee32 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Mon, 5 Oct 2026 18:05:16 +0200 Subject: [PATCH 06/14] fix(editor): draw quote/HR/table decorations on the canvas (#71 follow-up 2) NSTextBlock/NSTextTable layout is broken on this TextKit build regardless of engine: textBlocks zero-width the line rect (quotes wrapped one character per line), NSTextTable rows stack vertically with no grid (tables rendered as concatenated text with a stray outline). The TextKit1 bridge attempt failed live too. Stop fighting the API: - Presenter emits plain content: quotes indent-only, HR a thin invisible line, tables mono-space-padded grid text with alignment honored. - Each Block/Bound carries a Decoration payload (quote indent, rule, table column offsets); ReadingCanvasView.draw renders hairlines, rules, and table grids from measured layoutManager geometry. - Tests assert decorations + column alignment instead of textBlocks. Full suite green; lint clean. --- Museion/ReadingPresenter.swift | 170 +++++++++++++---------- Museion/ReadingSurface.swift | 70 +++++++++- MuseionTests/ReadingPresenterTests.swift | 62 +++------ 3 files changed, 186 insertions(+), 116 deletions(-) diff --git a/Museion/ReadingPresenter.swift b/Museion/ReadingPresenter.swift index a9a2638..bee19bb 100644 --- a/Museion/ReadingPresenter.swift +++ b/Museion/ReadingPresenter.swift @@ -26,6 +26,8 @@ enum ReadingPresenter { 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 @@ -34,6 +36,19 @@ enum ReadingPresenter { 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 @@ -62,6 +77,7 @@ enum ReadingPresenter { docRange: NSRange(location: start, length: out.length - start), sourceRange: block.sourceRange, imageURL: image, + decoration: block.decoration, )) } return Document(content: out, bounds: bounds) @@ -101,13 +117,16 @@ enum ReadingPresenter { // 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) + 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) + 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) } @@ -135,9 +154,6 @@ enum ReadingPresenter { let inner = lines.dropFirst().dropLast(hasClosingFence(lines) ? 1 : 0) return codeContent(inner.joined(separator: "\n")) } - if lines.count >= 2, isTableDelimiterRow(lines[1]), let table = tableContent(lines) { - return table - } // HR — the editing presenter's syntaxOnly matcher reused verbatim // (#69: same predicate both modes = one mental model). if ProsePresenter.lineKind(first) == .syntaxOnly { @@ -185,8 +201,8 @@ enum ReadingPresenter { } private static func hrContent() -> NSAttributedString { + // Hairline drawn by the canvas (Decoration.rule). let ps = NSMutableParagraphStyle() - ps.textBlocks = [RuleTextBlock()] ps.paragraphSpacingBefore = 8 ps.paragraphSpacing = 8 return NSAttributedString(string: " ", attributes: [ @@ -234,13 +250,14 @@ enum ReadingPresenter { // 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() - let quoteBlock = QuoteTextBlock() for (index, line) in lines.enumerated() { let depth = blockquoteDepth(line) let indent = CGFloat(6 + (depth - 1) * 18) let ps = NSMutableParagraphStyle() - ps.textBlocks = [quoteBlock] ps.firstLineHeadIndent = indent ps.headIndent = indent ps.paragraphSpacing = 4 @@ -265,51 +282,89 @@ enum ReadingPresenter { return String(line.dropFirst(prefix.count)).trimmingCharacters(in: .whitespaces) } - // MARK: Tables (#69: simple 1px-bordered NSTextTable; delimiter-row + // MARK: Tables (#69: mono grid — plain padded text; the canvas draws the - // alignment honored — cheap once the delimiter is parsed anyway) + // 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 table = NSTextTable() - table.numberOfColumns = header.count - table.collapsesBorders = true - table.setBorderColor(ProseTypography.tableBorderColor) - table.setWidth(1, type: .absolute, for: .border) - let out = NSMutableAttributedString() - var row = 0 - for (index, line) in lines.enumerated() { - if index == 1 { - continue - } // delimiter row - let cells = tableCells(line) - for column in 0 ..< header.count { - let text = column < cells.count ? cells[column] : "" - let cell = NSTextTableBlock( - table: table, startingRow: row, rowSpan: 1, - startingColumn: column, columnSpan: 1, - ) - cell.setWidth(1, type: .absolute, for: .border) - let ps = NSMutableParagraphStyle() - ps.textBlocks = [cell] - ps.alignment = aligns[column] - let attrs: [NSAttributedString.Key: Any] = [ - .font: row == 0 ? ProseTypography.boldBodyFont : ProseTypography.bodyFont, - .paragraphStyle: ps, - .foregroundColor: ProseTypography.foregroundColor, - ] - out.append(NSAttributedString( - string: text + (column == header.count - 1 ? "\n" : ""), - attributes: attrs, - )) + 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) } - row += 1 + } + let pad = 2 + 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 + 4) * advance + } + return .table(columns: offsets + [running]) + } + private static func tableCells(_ line: String) -> [String] { var trimmed = line.trimmingCharacters(in: .whitespaces) if trimmed.hasPrefix("|") { @@ -444,34 +499,3 @@ enum ReadingPresenter { return URL(string: String(trimmed[start ..< closeParen])) } } - -/// Hairline-left text block for blockquotes (#69). -final nonisolated class QuoteTextBlock: NSTextBlock { - override func drawBackground( - withFrame frameRect: NSRect, in _: NSView?, - characterRange _: NSRange, layoutManager _: NSLayoutManager, - ) { - let path = NSBezierPath() - path.move(to: NSPoint(x: frameRect.minX + 2, y: frameRect.minY)) - path.line(to: NSPoint(x: frameRect.minX + 2, y: frameRect.maxY)) - path.lineWidth = 2 - ProseTypography.quoteRuleColor.setStroke() - path.stroke() - } -} - -/// Full-width hairline text block for horizontal rules (#69). -final nonisolated class RuleTextBlock: NSTextBlock { - override func drawBackground( - withFrame frameRect: NSRect, in _: NSView?, - characterRange _: NSRange, layoutManager _: NSLayoutManager, - ) { - let midY = frameRect.midY - let path = NSBezierPath() - path.move(to: NSPoint(x: frameRect.minX, y: midY)) - path.line(to: NSPoint(x: frameRect.maxX, y: midY)) - path.lineWidth = 1 - ProseTypography.tableBorderColor.setStroke() - path.stroke() - } -} diff --git a/Museion/ReadingSurface.swift b/Museion/ReadingSurface.swift index ecdffc4..1b94d62 100644 --- a/Museion/ReadingSurface.swift +++ b/Museion/ReadingSurface.swift @@ -64,10 +64,6 @@ struct ReadingSurface: NSViewRepresentable { tv.isVerticallyResizable = true tv.isHorizontallyResizable = false tv.autoresizingMask = [.width] - // Tables (#69) lay out correctly under TextKit1 only — TK2 stacks - // NSTextTable rows vertically (probed). The canvas is read-only, so - // nothing editing-grade is lost by forcing the TK1 bridge. - tv.textContainer?.replaceLayoutManager(NSLayoutManager()) // 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) @@ -136,6 +132,72 @@ final class ReadingCanvasView: NSTextView { blockBounds.last { $0.docRange.location <= index } } + // MARK: Decorations (#69 fix: quote hairlines, HR rules, table grids — + + // drawn from measured geometry; NSTextBlock/NSTextTable layout is + // broken on modern TextKit) + + override func draw(_ dirtyRect: NSRect) { + super.draw(dirtyRect) + guard let layoutManager, let container = textContainer else { return } + for bound in blockBounds { + guard let decoration = bound.decoration else { continue } + let glyphRange = layoutManager.glyphRange( + forCharacterRange: bound.docRange, actualCharacterRange: nil, + ) + switch decoration { + case let .quote(indent): + let rect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: container) + let x = textContainerOrigin.x + container.lineFragmentPadding + indent - 6 + let path = NSBezierPath() + path.move(to: NSPoint(x: x, y: rect.minY)) + path.line(to: NSPoint(x: x, y: rect.maxY)) + path.lineWidth = 2 + ProseTypography.quoteRuleColor.setStroke() + path.stroke() + case .rule: + let rect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: container) + let y = rect.midY + let path = NSBezierPath() + path.move(to: NSPoint(x: textContainerOrigin.x, y: y)) + path.line(to: NSPoint(x: textContainerOrigin.x + container.size.width, y: y)) + path.lineWidth = 1 + ProseTypography.tableBorderColor.setStroke() + path.stroke() + case let .table(columns): + let rect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: container) + let originX = textContainerOrigin.x + container.lineFragmentPadding + let path = NSBezierPath() + for offset in columns { + let x = originX + offset + path.move(to: NSPoint(x: x, y: rect.minY)) + path.line(to: NSPoint(x: x, y: rect.maxY)) + } + var lineStart = glyphRange.location + var rowLines: [CGFloat] = [] + while lineStart < NSMaxRange(glyphRange) { + var effective = NSRange(location: 0, length: 0) + let lineRect = layoutManager.lineFragmentRect( + forGlyphAt: lineStart, effectiveRange: &effective, + withoutAdditionalLayout: true, + ) + if effective.length == 0 { + break + } + rowLines.append(lineRect.maxY) + lineStart = NSMaxRange(effective) + } + for y in rowLines { + 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() + } + } + } + override func updateTrackingAreas() { super.updateTrackingAreas() if hoverTrackingArea == nil { diff --git a/MuseionTests/ReadingPresenterTests.swift b/MuseionTests/ReadingPresenterTests.swift index e36049b..d9defac 100644 --- a/MuseionTests/ReadingPresenterTests.swift +++ b/MuseionTests/ReadingPresenterTests.swift @@ -63,32 +63,26 @@ struct ReadingPresenterTests { #expect(doc.bounds[3].sourceRange.location == expected) } - /// Tables render as NSTextTable blocks with header bold. + /// Tables render as a mono grid: decoration carries column offsets, + /// header/body rows are padded columns of text. @Test - func `table renders`() { + 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) - #expect(doc.content.string.contains("one")) - #expect(doc.content.string.contains("two")) - let hasTableBlock = doc.content.enumerateAttribute( - .paragraphStyle, in: NSRange(location: 0, length: doc.content.length), - ) { value, _, stop in - if let ps = value as? NSParagraphStyle, ps.textBlocks.contains(where: { $0 is NSTextTableBlock }) { - stop.pointee = true - } + 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 } - _ = hasTableBlock // enumerate returns Void; assertion below is the check - // direct check: at least one NSTextTableBlock anywhere - var found = false - doc.content.enumerateAttribute( - .paragraphStyle, in: NSRange(location: 0, length: doc.content.length), - ) { value, _, _ in - if let ps = value as? NSParagraphStyle, ps.textBlocks.contains(where: { $0 is NSTextTableBlock }) { - found = true - } - } - #expect(found) + #expect(columns.count == 3) // two columns + closing edge } /// Fenced code: mono face, markers hidden, content intact. @@ -102,22 +96,17 @@ struct ReadingPresenterTests { #expect((attrs[.font] as? NSFont)?.fontName == ProseTypography.codeFont.fontName) } - /// Blockquote: markers hidden, hairline block attached. + /// 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")) - var foundQuoteBlock = false - doc.content.enumerateAttribute( - .paragraphStyle, in: NSRange(location: 0, length: doc.content.length), - ) { value, _, _ in - if let ps = value as? NSParagraphStyle, ps.textBlocks.contains(where: { $0 is QuoteTextBlock }) { - foundQuoteBlock = true - } + guard case .quote? = doc.bounds[0].decoration else { + Issue.record("expected quote decoration") + return } - #expect(foundQuoteBlock) } /// Links styled + attribute retained (⌘-click opens). @@ -158,21 +147,16 @@ struct ReadingPresenterTests { #expect(doc.content.string.contains("[^1]")) } - /// HR: hairline block, matcher shared with editing. + /// 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) - var foundRule = false - doc.content.enumerateAttribute( - .paragraphStyle, in: NSRange(location: 0, length: doc.content.length), - ) { value, _, _ in - if let ps = value as? NSParagraphStyle, ps.textBlocks.contains(where: { $0 is RuleTextBlock }) { - foundRule = true - } + guard case .rule? = doc.bounds[1].decoration else { + Issue.record("expected rule decoration") + return } - #expect(foundRule) } /// Soft-joined lines: one paragraph, single spaces. From 2fbc8af24ddc55a8f0f1b38b804bf54f2952bb18 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Tue, 6 Oct 2026 11:36:29 +0200 Subject: [PATCH 07/14] fix(editor): measure decorations via TK2 fragment geometry (#71 follow-up 3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The TK1-compat layoutManager reports wrong rects under TextKit2 — the table grid drew compressed above its text, the quote hairline landed mid-heading. fragmentFrames(for:) walks NSTextLayoutManager fragments (the engine's own frames, document order): quote hairlines span the block, HRs center on their line, table verticals span all rows and horizontals underline every grid line. --- Museion/ReadingSurface.swift | 71 ++++++++++++++++++++---------------- 1 file changed, 39 insertions(+), 32 deletions(-) diff --git a/Museion/ReadingSurface.swift b/Museion/ReadingSurface.swift index 1b94d62..9564ced 100644 --- a/Museion/ReadingSurface.swift +++ b/Museion/ReadingSurface.swift @@ -134,60 +134,67 @@ final class ReadingCanvasView: NSTextView { // MARK: Decorations (#69 fix: quote hairlines, HR rules, table grids — - // drawn from measured geometry; NSTextBlock/NSTextTable layout is - // broken on modern TextKit) + // drawn from measured TK2 fragment geometry; NSTextBlock/NSTextTable + // layout is broken on modern TextKit, and the TK1-compat layoutManager + // reports wrong rects, so measure via NSTextLayoutManager directly.) + + /// Union of layout-fragment frames for a document character range + /// (engine-native measurement; fragments arrive in document order). + private func fragmentFrames(for docRange: NSRange) -> [CGRect] { + guard let tlm = textLayoutManager, let tcm = tlm.textContentManager else { return [] } + let docStart = tcm.documentRange.location + guard + let startLoc = tcm.location(docStart, offsetBy: docRange.location), + let endLoc = tcm.location(docStart, offsetBy: NSMaxRange(docRange)) + else { return [] } + let endOffset = docRange.location + docRange.length + var frames: [CGRect] = [] + tlm.enumerateTextLayoutFragments(from: startLoc) { fragment in + let fragStart = tcm.offset(from: docStart, to: fragment.rangeInElement.location) + if fragStart >= endOffset { + return false + } + frames.append(fragment.layoutFragmentFrame) + return true + } + return frames + } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) - guard let layoutManager, let container = textContainer else { return } for bound in blockBounds { guard let decoration = bound.decoration else { continue } - let glyphRange = layoutManager.glyphRange( - forCharacterRange: bound.docRange, actualCharacterRange: nil, - ) + let frames = fragmentFrames(for: bound.docRange) + guard let firstFrame = frames.first, let lastFrame = frames.last else { continue } switch decoration { case let .quote(indent): - let rect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: container) - let x = textContainerOrigin.x + container.lineFragmentPadding + indent - 6 + let x = textContainerOrigin.x + (textContainer?.lineFragmentPadding ?? 0) + indent - 6 let path = NSBezierPath() - path.move(to: NSPoint(x: x, y: rect.minY)) - path.line(to: NSPoint(x: x, y: rect.maxY)) + 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 rect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: container) - let y = rect.midY + let y = (firstFrame.minY + firstFrame.maxY) / 2 let path = NSBezierPath() path.move(to: NSPoint(x: textContainerOrigin.x, y: y)) - path.line(to: NSPoint(x: textContainerOrigin.x + container.size.width, y: y)) + path.line(to: NSPoint(x: textContainerOrigin.x + (textContainer?.size.width ?? 0), y: y)) path.lineWidth = 1 ProseTypography.tableBorderColor.setStroke() path.stroke() case let .table(columns): - let rect = layoutManager.boundingRect(forGlyphRange: glyphRange, in: container) - let originX = textContainerOrigin.x + container.lineFragmentPadding + let originX = textContainerOrigin.x + (textContainer?.lineFragmentPadding ?? 0) let path = NSBezierPath() + // verticals: column separators + closing edge, spanning all rows for offset in columns { let x = originX + offset - path.move(to: NSPoint(x: x, y: rect.minY)) - path.line(to: NSPoint(x: x, y: rect.maxY)) + path.move(to: NSPoint(x: x, y: firstFrame.minY)) + path.line(to: NSPoint(x: x, y: lastFrame.maxY)) } - var lineStart = glyphRange.location - var rowLines: [CGFloat] = [] - while lineStart < NSMaxRange(glyphRange) { - var effective = NSRange(location: 0, length: 0) - let lineRect = layoutManager.lineFragmentRect( - forGlyphAt: lineStart, effectiveRange: &effective, - withoutAdditionalLayout: true, - ) - if effective.length == 0 { - break - } - rowLines.append(lineRect.maxY) - lineStart = NSMaxRange(effective) - } - for y in rowLines { + // horizontals: top border + a line under every text line + 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)) } From d9cb615bc26552de3ee7b8eb140fd7668423068a Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Tue, 6 Oct 2026 11:56:58 +0200 Subject: [PATCH 08/14] fix(editor): engine-agnostic decoration measurement (#71 follow-up 4) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The reading canvas runs TextKit1 (textLayoutManager nil — the scroll-view config path engages the TK1 bridge), so the TK2 fragment walk found nothing and draw() bailed: no hairline, no grid. framesForRange() now measures through whichever engine is live — TK2 fragments, else TK1 boundingRect per character line (lineFragmentRect returns degenerate rects mid-layout; boundingRect is truthful, pixel-verified). Headless pixel probe (temporary, deleted): quote hairline + table grid lines render at the right coordinates. --- Museion/ReadingSurface.swift | 64 +++++++++++++++++++++--------------- 1 file changed, 37 insertions(+), 27 deletions(-) diff --git a/Museion/ReadingSurface.swift b/Museion/ReadingSurface.swift index 9564ced..38de8db 100644 --- a/Museion/ReadingSurface.swift +++ b/Museion/ReadingSurface.swift @@ -135,36 +135,15 @@ final class ReadingCanvasView: NSTextView { // 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 layoutManager - // reports wrong rects, so measure via NSTextLayoutManager directly.) - - /// Union of layout-fragment frames for a document character range - /// (engine-native measurement; fragments arrive in document order). - private func fragmentFrames(for docRange: NSRange) -> [CGRect] { - guard let tlm = textLayoutManager, let tcm = tlm.textContentManager else { return [] } - let docStart = tcm.documentRange.location - guard - let startLoc = tcm.location(docStart, offsetBy: docRange.location), - let endLoc = tcm.location(docStart, offsetBy: NSMaxRange(docRange)) - else { return [] } - let endOffset = docRange.location + docRange.length - var frames: [CGRect] = [] - tlm.enumerateTextLayoutFragments(from: startLoc) { fragment in - let fragStart = tcm.offset(from: docStart, to: fragment.rangeInElement.location) - if fragStart >= endOffset { - return false - } - frames.append(fragment.layoutFragmentFrame) - return true - } - return frames - } + // 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) for bound in blockBounds { guard let decoration = bound.decoration else { continue } - let frames = fragmentFrames(for: bound.docRange) + let frames = framesForRange(bound.docRange) guard let firstFrame = frames.first, let lastFrame = frames.last else { continue } switch decoration { case let .quote(indent): @@ -186,13 +165,11 @@ final class ReadingCanvasView: NSTextView { case let .table(columns): let originX = textContainerOrigin.x + (textContainer?.lineFragmentPadding ?? 0) let path = NSBezierPath() - // verticals: column separators + closing edge, spanning all rows 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)) } - // horizontals: top border + a line under every text line let ys = [firstFrame.minY] + frames.map(\.maxY) for y in ys { path.move(to: NSPoint(x: originX, y: y)) @@ -205,6 +182,39 @@ final class ReadingCanvasView: NSTextView { } } + /// 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 { From 7ed7a56642dde05a5bb5b7d89fcfebe57bad4965 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Tue, 6 Oct 2026 12:04:37 +0200 Subject: [PATCH 09/14] fix(editor): translate decoration frames by textContainerOrigin (#71 follow-up 5) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Frames arrive in CONTAINER space; the view draws text at textContainerOrigin + frame. The missing +origin.y (inset height 20) drew every decoration 20pt too high — hairline ending above the quote, grid compressed over the table's top rows. Translate once, per-frame. --- Museion/ReadingSurface.swift | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/Museion/ReadingSurface.swift b/Museion/ReadingSurface.swift index 38de8db..7148c32 100644 --- a/Museion/ReadingSurface.swift +++ b/Museion/ReadingSurface.swift @@ -141,13 +141,18 @@ final class ReadingCanvasView: NSTextView { 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 = textContainerOrigin.x + (textContainer?.lineFragmentPadding ?? 0) + indent - 6 + 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)) @@ -157,13 +162,13 @@ final class ReadingCanvasView: NSTextView { case .rule: let y = (firstFrame.minY + firstFrame.maxY) / 2 let path = NSBezierPath() - path.move(to: NSPoint(x: textContainerOrigin.x, y: y)) - path.line(to: NSPoint(x: textContainerOrigin.x + (textContainer?.size.width ?? 0), y: y)) + 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 = textContainerOrigin.x + (textContainer?.lineFragmentPadding ?? 0) + let originX = (textContainer?.lineFragmentPadding ?? 0) let path = NSBezierPath() for offset in columns { let x = originX + offset From 2d4e2563f7a02c9219c8a84001c4e03452dd3b91 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Tue, 6 Oct 2026 12:49:04 +0200 Subject: [PATCH 10/14] =?UTF-8?q?feat(editor):=20reading=20polish=20?= =?UTF-8?q?=E2=80=94=20inline=20images,=20rhythm,=20table=20padding,=20mar?= =?UTF-8?q?gins=20(#71=20follow-up=206)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Images render inline via NSTextAttachment (scaled to 480pt, alt as caption); the hover popover and its ImagePopoverView are gone. - Vertical rhythm per the author's measurements: lineHeightMultiple 1.25, 1 line after paragraphs, 2 after headings (all block styles). - Table cells breathe: mono pad 2→3 per side; decoration offsets measure with the same pad so the grid still lands on the text. - Margins: lineFragmentPadding 12→24 (reading + editing), inset height 24. - Image URL resolution hoisted into blocks(for:) — the attachment loads the resolved path, document() no longer re-resolves. --- Museion/PostEditorView.swift | 2 +- Museion/ReadingPresenter.swift | 79 +++++++++++++++++++++++++++------- Museion/ReadingSurface.swift | 4 +- 3 files changed, 67 insertions(+), 18 deletions(-) diff --git a/Museion/PostEditorView.swift b/Museion/PostEditorView.swift index b6fcf21..a87cb00 100644 --- a/Museion/PostEditorView.swift +++ b/Museion/PostEditorView.swift @@ -282,7 +282,7 @@ struct ProseTextView: NSViewRepresentable { // 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 = 12 + tv.textContainer?.lineFragmentPadding = 24 tv.textContainerInset = NSSize(width: 0, height: 20) let scroll = NSScrollView() scroll.documentView = tv diff --git a/Museion/ReadingPresenter.swift b/Museion/ReadingPresenter.swift index bee19bb..a1744cf 100644 --- a/Museion/ReadingPresenter.swift +++ b/Museion/ReadingPresenter.swift @@ -19,6 +19,11 @@ 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 { @@ -63,20 +68,16 @@ enum ReadingPresenter { static func document(for text: String, resolvingImagesIn postFolder: URL?) -> Document { let out = NSMutableAttributedString() var bounds: [Bound] = [] - for block in blocks(for: text) { + 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) - let image = block.imageURL.flatMap { raw -> URL? in - guard raw.scheme == nil, let postFolder else { return raw } - return postFolder.appendingPathComponent(raw.path) - } bounds.append(Bound( docRange: NSRange(location: start, length: out.length - start), sourceRange: block.sourceRange, - imageURL: image, + imageURL: block.imageURL, decoration: block.decoration, )) } @@ -87,7 +88,8 @@ enum ReadingPresenter { /// Render `text` into reading blocks: blank-line split, one block per /// chunk (a run of list items or quote lines renders as one block). - static func blocks(for text: String) -> [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 @@ -98,7 +100,7 @@ enum ReadingPresenter { if end > loc { let chunkRange = NSRange(location: loc, length: end - loc) let chunk = ns.substring(with: chunkRange) - out.append(block(chunk: chunk, sourceRange: chunkRange)) + out.append(block(chunk: chunk, sourceRange: chunkRange, postFolder: postFolder)) } loc = delim.location == NSNotFound ? ns.length : delim.location + 2 } @@ -106,9 +108,15 @@ enum ReadingPresenter { } /// Classify one chunk and render it. - private static func block(chunk: String, sourceRange: NSRange) -> Block { - if let url = imageURL(in: chunk) { - return Block(content: inlineParse(chunk), sourceRange: sourceRange, imageURL: url) + 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 { @@ -133,6 +141,35 @@ enum ReadingPresenter { // 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.paragraphSpacing = 10 + 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) @@ -178,7 +215,8 @@ enum ReadingPresenter { default: ProseTypography.bodyFont.pointSize } let ps = NSMutableParagraphStyle() - ps.paragraphSpacing = level <= 2 ? 10 : 8 + 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), @@ -189,7 +227,8 @@ enum ReadingPresenter { private static func codeContent(_ code: String) -> NSAttributedString { let ps = NSMutableParagraphStyle() - ps.paragraphSpacing = 10 + ps.lineHeightMultiple = lineHeightMultiple + ps.paragraphSpacing = paragraphSpacingAfter ps.paragraphSpacingBefore = 6 ps.firstLineHeadIndent = 12 ps.headIndent = 12 @@ -203,6 +242,7 @@ enum ReadingPresenter { 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: [ @@ -223,6 +263,7 @@ enum ReadingPresenter { 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 @@ -258,6 +299,7 @@ enum ReadingPresenter { 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 @@ -300,7 +342,7 @@ enum ReadingPresenter { widths[column] = max(widths[column], cell.count) } } - let pad = 2 + let pad = 3 let codeAttrs: [NSAttributedString.Key: Any] = [ .font: ProseTypography.codeFont, .foregroundColor: ProseTypography.foregroundColor, @@ -360,7 +402,7 @@ enum ReadingPresenter { var running = 0.0 for width in widths { offsets.append(running) - running += CGFloat(width + 4) * advance + running += CGFloat(width + 6) * advance // cell pad 3 + 3, matches gridLine } return .table(columns: offsets + [running]) } @@ -428,6 +470,13 @@ enum ReadingPresenter { 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 { diff --git a/Museion/ReadingSurface.swift b/Museion/ReadingSurface.swift index 7148c32..6cc9e47 100644 --- a/Museion/ReadingSurface.swift +++ b/Museion/ReadingSurface.swift @@ -68,8 +68,8 @@ struct ReadingSurface: NSViewRepresentable { // 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 = 12 - tv.textContainerInset = NSSize(width: 0, height: 20) + tv.textContainer?.lineFragmentPadding = 24 + tv.textContainerInset = NSSize(width: 0, height: 24) let scroll = NSScrollView() scroll.documentView = tv scroll.hasVerticalScroller = true From 6d7d1411a26f3a440dec1321bee2d4ac19b8af32 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Tue, 6 Oct 2026 13:43:43 +0200 Subject: [PATCH 11/14] =?UTF-8?q?feat(editor):=20configurable=20text=20flo?= =?UTF-8?q?w=20=E2=80=94=20line=20height=20+=20spacing=20knobs=20(#71=20fo?= =?UTF-8?q?llow-up=207)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three UserDefaults-backed knobs in ProseTypography (line-height multiple, space-after-¶ and space-after-heading in body lines, clamped), surfaced in Settings → Text Flow. Also fixes two real bugs from the last commit: paragraphSpacing was set to 1.25 POINTS (now lines × linePoints), and reading-mode body paragraphs never received the rhythm at all (they rode the editing surface's fixed 10pt) — both surfaces now share one rhythm. --- Museion/ProsePresenter.swift | 8 +++--- Museion/ProseTypography.swift | 37 ++++++++++++++++++++++++++ Museion/ReadingPresenter.swift | 11 ++++++-- Museion/SettingsPaneView.swift | 47 ++++++++++++++++++++++++++++++++++ 4 files changed, 98 insertions(+), 5 deletions(-) diff --git a/Museion/ProsePresenter.swift b/Museion/ProsePresenter.swift index 46bfcec..6ad9838 100644 --- a/Museion/ProsePresenter.swift +++ b/Museion/ProsePresenter.swift @@ -42,10 +42,12 @@ nonisolated enum ProsePresenter { /// as body anyway; dedicated quote spacing waits for #20's polish pass. static func paragraph(_ kind: LineKind) -> NSParagraphStyle { let style = NSMutableParagraphStyle() + style.lineHeightMultiple = ProseTypography.lineHeightMultiple + let line = ProseTypography.linePoints 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 + case .heading1: style.paragraphSpacing = 2 * line; style.paragraphSpacingBefore = 26 + case .heading2: style.paragraphSpacing = 2 * line; style.paragraphSpacingBefore = 1 * line + case .quote, .syntaxOnly, .body: style.paragraphSpacing = 1 * line } return style } diff --git a/Museion/ProseTypography.swift b/Museion/ProseTypography.swift index 569554b..5538b2e 100644 --- a/Museion/ProseTypography.swift +++ b/Museion/ProseTypography.swift @@ -28,6 +28,11 @@ nonisolated enum ProseTypography { 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() { @@ -38,6 +43,9 @@ nonisolated enum ProseTypography { "proseHeadingsSize": defaultHeadingsSize, "proseCodeFace": defaultCodeFace, "proseCodeSize": defaultCodeSize, + "proseLineHeight": defaultLineHeight, + "proseParagraphSpacingLines": defaultParagraphSpacingLines, + "proseHeadingSpacingLines": defaultHeadingSpacingLines, ]) } @@ -83,6 +91,35 @@ nonisolated enum ProseTypography { 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) + } + + /// 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) -> 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 { diff --git a/Museion/ReadingPresenter.swift b/Museion/ReadingPresenter.swift index a1744cf..020d12f 100644 --- a/Museion/ReadingPresenter.swift +++ b/Museion/ReadingPresenter.swift @@ -146,7 +146,8 @@ enum ReadingPresenter { /// paragraph when the file can't load. private static func imageBlockContent(url: URL, alt: String) -> NSAttributedString { let ps = NSMutableParagraphStyle() - ps.paragraphSpacing = 10 + 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) @@ -201,7 +202,13 @@ enum ReadingPresenter { .map { $0.trimmingCharacters(in: .whitespaces) } .filter { !$0.isEmpty } .joined(separator: " ") - return inlineParse(joined) + 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 { diff --git a/Museion/SettingsPaneView.swift b/Museion/SettingsPaneView.swift index ec5c8e5..cc8b41c 100644 --- a/Museion/SettingsPaneView.swift +++ b/Museion/SettingsPaneView.swift @@ -35,6 +35,7 @@ struct SettingsPaneView: View { VStack(alignment: .leading, spacing: 24) { contentSection typographySection + flowSection } .padding(24) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) @@ -65,6 +66,23 @@ struct SettingsPaneView: View { } } + // 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; the spacings are measured in body lines — tune them when a face change tightens or loosens the page.", + ) + .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 { @@ -146,6 +164,35 @@ private struct SlotRow: View { } } +/// One flow knob: label + numeric field (UserDefaults-backed). +private struct FlowRow: View { + let label: String + let key: String + let range: ClosedRange + 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 { + 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 { From 677dc8c07397304547a51890760e4d6006ba5fdf Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Tue, 6 Oct 2026 14:14:17 +0200 Subject: [PATCH 12/14] =?UTF-8?q?fix(editor):=20source-editor=20spacing=20?= =?UTF-8?q?=E2=80=94=20blank=20lines=20are=20the=20separator=20(#71=20foll?= =?UTF-8?q?ow-up=208)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two defects from the flow-knob commit: (1) edit mode got reading-mode's paragraph spacing stacked on top of the visible blank source lines — gaps tripled. Source editors render the blank line AS the separator; paragraph spacing is now 0, only lineHeightMultiple rides the knobs. (2) Knob changes never reached an open editor — updateNSView now re-attributes the whole storage (selection preserved) when ProseTypography.flowKey moves. --- Museion/PostEditorView.swift | 10 ++++++++++ Museion/ProsePresenter.swift | 13 ++++++------- Museion/ProseTypography.swift | 6 ++++++ 3 files changed, 22 insertions(+), 7 deletions(-) diff --git a/Museion/PostEditorView.swift b/Museion/PostEditorView.swift index a87cb00..952d89e 100644 --- a/Museion/PostEditorView.swift +++ b/Museion/PostEditorView.swift @@ -297,6 +297,15 @@ struct ProseTextView: NSViewRepresentable { func updateNSView(_ scroll: NSScrollView, context: Context) { guard let tv = scroll.documentView as? NSTextView else { return } + // Typography/flow knob change: re-attribute everything, keep text + // and selection (settings live in another pane; the editor is idle). + if context.coordinator.appliedFlowKey != ProseTypography.flowKey { + context.coordinator.appliedFlowKey = ProseTypography.flowKey + let sel = tv.selectedRange() + let storage = tv.textStorage as! NSMutableAttributedString + storage.setAttributedString(ProsePresenter.attribute(tv.string)) + tv.setSelectedRange(sel) + } if let session { context.coordinator.sessionRef = session // Load only when the generation moved (open, Yes-reload) — never @@ -348,6 +357,7 @@ struct ProseTextView: NSViewRepresentable { var sessionRef: EditorSession? var loadedGeneration = -1 var appliedCaretToken = -1 + var appliedFlowKey = "" init(representable: ProseTextView) { onEdit = representable.onEdit diff --git a/Museion/ProsePresenter.swift b/Museion/ProsePresenter.swift index 6ad9838..4738ed2 100644 --- a/Museion/ProsePresenter.swift +++ b/Museion/ProsePresenter.swift @@ -40,15 +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() + // 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 - let line = ProseTypography.linePoints - switch kind { - case .heading1: style.paragraphSpacing = 2 * line; style.paragraphSpacingBefore = 26 - case .heading2: style.paragraphSpacing = 2 * line; style.paragraphSpacingBefore = 1 * line - case .quote, .syntaxOnly, .body: style.paragraphSpacing = 1 * line - } + style.paragraphSpacing = 0 + style.paragraphSpacingBefore = 0 return style } diff --git a/Museion/ProseTypography.swift b/Museion/ProseTypography.swift index 5538b2e..99a62c8 100644 --- a/Museion/ProseTypography.swift +++ b/Museion/ProseTypography.swift @@ -108,6 +108,12 @@ nonisolated enum ProseTypography { 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 From 0d3d5af78ace9adfdbf9ffe5f5d37c253b547c91 Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Tue, 6 Oct 2026 14:17:53 +0200 Subject: [PATCH 13/14] fix(editor): typography knob changes reach open surfaces (#71 follow-up 9) updateNSView never fires on UserDefaults writes from the Settings pane, so the flowKey check there was dead code. Both surfaces now observe UserDefaults.didChangeNotification directly: the editor re-attributes (selection preserved), the reading canvas rebuilds its document. Also closes the parked stale-reading-view defect from the handoff notes. --- Museion/PostEditorView.swift | 38 +++++++++++++++++++++++++++--------- Museion/ReadingSurface.swift | 24 +++++++++++++++++++++++ 2 files changed, 53 insertions(+), 9 deletions(-) diff --git a/Museion/PostEditorView.swift b/Museion/PostEditorView.swift index 952d89e..89133d0 100644 --- a/Museion/PostEditorView.swift +++ b/Museion/PostEditorView.swift @@ -297,21 +297,18 @@ struct ProseTextView: NSViewRepresentable { func updateNSView(_ scroll: NSScrollView, context: Context) { guard let tv = scroll.documentView as? NSTextView else { return } - // Typography/flow knob change: re-attribute everything, keep text - // and selection (settings live in another pane; the editor is idle). - if context.coordinator.appliedFlowKey != ProseTypography.flowKey { - context.coordinator.appliedFlowKey = ProseTypography.flowKey - let sel = tv.selectedRange() - let storage = tv.textStorage as! NSMutableAttributedString - storage.setAttributedString(ProsePresenter.attribute(tv.string)) - tv.setSelectedRange(sel) - } + // 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 + 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 @@ -358,6 +355,29 @@ struct ProseTextView: NSViewRepresentable { 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 diff --git a/Museion/ReadingSurface.swift b/Museion/ReadingSurface.swift index 6cc9e47..0a9b73f 100644 --- a/Museion/ReadingSurface.swift +++ b/Museion/ReadingSurface.swift @@ -79,6 +79,7 @@ struct ReadingSurface: NSViewRepresentable { tv.onEditIntent = onEditIntent tv.stateBox = stateBox context.coordinator.canvas = tv + context.coordinator.watchDefaults(tv, representable: self) return scroll } @@ -110,6 +111,29 @@ struct ReadingSurface: NSViewRepresentable { 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 + } + } } } From b30c0e3dd688e86626180fa20af0106b34087acc Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Tue, 6 Oct 2026 14:23:04 +0200 Subject: [PATCH 14/14] =?UTF-8?q?fix(settings):=20say=20where=20the=20flow?= =?UTF-8?q?=20knobs=20apply=20=E2=80=94=20line=20height=20everywhere,=20sp?= =?UTF-8?q?acings=20reading-only?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Museion/SettingsPaneView.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Museion/SettingsPaneView.swift b/Museion/SettingsPaneView.swift index cc8b41c..08c7335 100644 --- a/Museion/SettingsPaneView.swift +++ b/Museion/SettingsPaneView.swift @@ -73,7 +73,7 @@ struct SettingsPaneView: View { Text("Text Flow") .font(.system(size: 13, weight: .semibold)) Text( - "Reading rhythm. Line height scales the leading; the spacings are measured in body lines — tune them when a face change tightens or loosens the page.", + "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)