Files
museion/Museion/ProsePresenter.swift
T
AlexKucera 4c91733e78 feat(editor): land reading toggle — render, interact, typography slots (S1.2 #71)
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).
2026-10-05 15:51:28 +02:00

128 lines
4.6 KiB
Swift

//
// ProsePresenter.swift
// Museion
//
// #19 (S1.2): line-based markdown presentation for the editor — lifted from
// the proven spike (spike/textkit2, ADR-0010: ≤1.1 ms full-doc attribute load
// on PERF-3k). Presentation-only: the plain `isRichText = false` store stays
// the source of truth; attributes ride on top and re-apply per edited
// paragraph. The Fix-Card anchor search stays with M2 (#25) — not lifted.
//
import AppKit
/// Styled-source presentation (ADR-0010 mode B): variable heading sizes,
/// paragraph spacing, dimmed syntax. Pure functions over text; no AppKit view
/// state. Colors are the spike's proven values (foreground ≈ DesignTokens
/// foreground; the 0.55 syntax dim is deliberately lighter than muted).
nonisolated enum ProsePresenter {
enum LineKind { case heading1, heading2, quote, syntaxOnly, body }
static func lineKind(_ line: String) -> LineKind {
let trimmedLine = line.drop(while: { $0 == " " })
if trimmedLine.hasPrefix("## ") {
return .heading2
}
if trimmedLine.hasPrefix("# ") {
return .heading1
}
if trimmedLine.hasPrefix("> ") {
return .quote
}
if !trimmedLine.isEmpty, trimmedLine.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) {
return .syntaxOnly
}
return .body
}
static let inlineSyntax: Set<Character> = ["*", "_", "`", "[", "]", "(", ")", "!", "<", ">"]
/// Paragraph spacing per line kind, applied via NSParagraphStyle.
/// ponytail: quote rides body spacing — attributes(for:) styles quotes
/// as body anyway; dedicated quote spacing waits for #20's polish pass.
static func paragraph(_ kind: LineKind) -> NSParagraphStyle {
let style = NSMutableParagraphStyle()
switch kind {
case .heading1: style.paragraphSpacing = 18; style.paragraphSpacingBefore = 26
case .heading2: style.paragraphSpacing = 12; style.paragraphSpacingBefore = 20
case .quote, .syntaxOnly, .body: style.paragraphSpacing = 10
}
return style
}
/// Attribute a whole text (initial load). Headings/body/quote styling + dimmed syntax.
static func attribute(_ text: String) -> NSAttributedString {
let out = NSMutableAttributedString(string: text, attributes: bodyAttributes)
let nsText = text as NSString
nsText.enumerateSubstrings(in: NSRange(location: 0, length: nsText.length), options: [.byLines]) { line, range, _, _ in
guard let line else { return }
let kind = lineKind(line)
out.setAttributes(Self.attributes(for: kind), range: range)
dimSyntax(in: out, range: range)
}
return out
}
/// Attribute one paragraph (editing-time re-apply). Cheap: one line, one pass.
static func reattribute(_ out: NSMutableAttributedString, paragraphRange: NSRange) {
let line = (out.string as NSString).substring(with: paragraphRange)
let kind = lineKind(line)
out.setAttributes(Self.attributes(for: kind), range: paragraphRange)
dimSyntax(in: out, range: paragraphRange)
}
// Typography: the #70 role slots (ProseTypography) — Body / Headings /
// Code — shared with reading mode; editing chrome (dimmed syntax) rides
// the Code slot.
static var bodyFont: NSFont {
ProseTypography.bodyFont
}
static var bodyAttributes: [NSAttributedString.Key: Any] {
ProseTypography.bodyAttributes
}
static func attributes(for kind: LineKind) -> [NSAttributedString.Key: Any] {
switch kind {
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
}
}
/// Dim markdown syntax characters within a line range (marker prefixes + inline marks).
static func dimSyntax(in out: NSMutableAttributedString, range: NSRange) {
let nsText = out.string as NSString
guard range.length > 0 else { return }
let line = nsText.substring(with: range)
let kind = lineKind(line)
// prefix markers
let markerLen = switch kind {
case .heading1: 2
case .heading2: 3
case .quote: 2
default: 0
}
let dim: [NSAttributedString.Key: Any] = [
.foregroundColor: ProseTypography.syntaxColor,
.font: ProseTypography.codeFont,
]
if markerLen > 0 {
out.addAttributes(dim, range: NSRange(location: range.location, length: min(markerLen, range.length)))
}
// inline marks in body/quote
if kind == .body || kind == .quote {
for (offset, codeUnit) in line.utf16.enumerated() {
if let scalar = Unicode.Scalar(codeUnit).map({ Character($0) }), inlineSyntax.contains(scalar) {
out.addAttributes(dim, range: NSRange(location: range.location + offset, length: 1))
}
}
}
}
}