Files
museion/Museion/ReadingPresenter.swift
T
AlexKucera 4cb753d17f feat(reading): polish typography, externalize CSS
Critique-directed polish of the reading surface (#72 ruling: pipeline
calm, surface not-calm) plus the single-user typography rework:

- Flow: leading 1.5, paragraph gap tightened; heading ladder rescaled
  (h1 1.15x / h2 0.85x / h3 body-face semibold) with cling margins,
  hN+hN suppression, no title dead space
- Constructs: confident blockquote (near-ink text, 3px rail, nesting
  degrades), booktabs tables, tinted code panels, relative inline code
- Fonts hardcoded for Alexander's faces: Valkyrie OT B 17 body,
  Concourse OT Semibold headings, UbuntuMono 14 code; 66ch measure
- Stylesheet moved to Museion/Resources/reading.css, read fresh per
  page build — Debug builds load the repo copy (#filePath), so CSS
  edits hot-reload on the next reading toggle
- Settings Typography/Text Flow sections and all flow-key plumbing
  deleted (56 insertions, 417 deletions)

Refs #72, #78. Detector: 192 findings -> 0. Build + 93 tests green.

[Generated by AI]
2026-10-07 17:02:10 +02:00

219 lines
8.5 KiB
Swift

//
// ReadingPresenter.swift
// Museion
//
// #76 (S1.2, map #20; ADR-0011): the reading renderer is the apex HTML
// pipeline — markdown → bundled apex binary → HTML fragment, with the
// blank-line chunker's `<!--S:N-->` sentinels restamped post-conversion
// into `data-source-line` attributes (the paragraph map for click-to-edit
// and scroll-sync, #68; apex emits no source positions — probed in #74).
// The TextKit renderer this replaces is deleted, not kept as fallback
// (ADR-0011: fallbacks rot; the stale-flow defect dies unfixed by design).
// Constructs per #69 ride apex: lists (`1. 1. 1.` renumbers via native
// <ol>), ### headings, HR, fenced code, blockquotes, tables, images
// (base64 inline, CSS hover expand), links + ⌘-click; footnotes render
// natively (apex upgrade over #69's fallback — corpus has none). Typography
// per #70/#71: the ProseTypography slots + flow knobs become CSS custom
// properties, injected at load.
//
// Pure over its input (nonisolated); the WKWebView surface loads the page.
//
import AppKit
import Foundation
/// Reading-mode presentation: markdown → stamped HTML page (#76 / ADR-0011).
nonisolated enum ReadingPresenter {
// MARK: Source map (the #68 click→edit / scroll-sync contract)
/// One paragraph-granularity block: 1-based source line + UTF-16 range in
/// the source text (blank-line chunk, start-of-chunk … chunk end).
struct Block {
let sourceLine: Int
let sourceRange: NSRange
}
/// The chunk list behind the stamp: blank-line split, monotonic — the
/// presenter's public map. Line → UTF-16 conversion for caret landing.
static func blocks(for text: String) -> [Block] {
let ns = text as NSString
var out: [Block] = []
var loc = 0
var line = 1
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 {
out.append(Block(sourceLine: line, sourceRange: NSRange(location: loc, length: end - loc)))
}
// advance line count over the chunk + the blank separator run
var index = loc
while index < end {
if ns.character(at: index) == 0x0A {
line += 1
}
index += 1
}
if delim.location == NSNotFound {
break
}
var scan = delim.location
while scan < ns.length {
let char = ns.character(at: scan)
if char == 0x0A {
line += 1; scan += 1
} else if char == 0x0D {
scan += 1
} else {
break
}
}
loc = scan
}
return out
}
/// Prepend `<!--S:N-->` (N = 1-based source line) before every blank-line
/// chunk — apex passes HTML comments through verbatim (#74).
static func stampSource(_ source: String) -> String {
let isBlank = { (line: Substring) in line.allSatisfy { $0 == " " || $0 == "\t" || $0 == "\r" } }
let lines = source.split(separator: "\n", omittingEmptySubsequences: false)
var out: [String] = []
var index = 0
while index < lines.count {
if isBlank(lines[index]) {
index += 1; continue
}
if !out.isEmpty {
out.append("")
}
out.append("<!--S:\(index + 1)-->")
while index < lines.count, !isBlank(lines[index]) {
out.append(String(lines[index])); index += 1
}
}
return out.joined(separator: "\n")
}
/// Rewrite `<!--S:N-->` into `data-source-line="N"` on the element that
/// follows (spike regex, 0 mis-stamps corpus-wide, #74).
static func stampHTML(_ html: String) -> String {
// Static literal pattern — compiles by construction; a failure would
// crash at first render and every test with it.
// swiftlint:disable:next force_try
let regex = try! NSRegularExpression(pattern: #"<!--S:(\d+)-->\s*\n<([a-zA-Z][a-zA-Z0-9]*)"#)
let mutable = NSMutableString(string: html)
regex.replaceMatches(in: mutable, range: NSMakeRange(0, mutable.length), withTemplate: "<$2 data-source-line=\"$1\"")
return mutable as String
}
// MARK: Apex runner (bundled binary, ADR-0011)
/// Locate apex: bundle resource first, then `APEX_PATH` override, then a
/// Homebrew install (dev machines). A renderer must not grow a gate.
static func apexBinaryPath() -> String? {
if let bundlePath = Bundle.main.path(forResource: "apex", ofType: nil) {
return bundlePath
}
if let env = ProcessInfo.processInfo.environment["APEX_PATH"] {
return env
}
for path in ["/opt/homebrew/bin/apex", "/usr/local/bin/apex"] where FileManager.default.isExecutableFile(atPath: path) {
return path
}
return nil
}
/// markdown → HTML fragment. `--embed-images` + `--base-dir` inline
/// images as base64 (loadHTMLString then needs no file access; nothing
/// is written into the vault). `--no-mixed-lists` is REQUIRED
/// (ADR-0011): apex's default merges an ordered list after bullets into
/// one `<ul>`, killing `1. 1. 1.` renumbering.
static func apexRender(_ markdown: String, baseDir: URL?) throws -> String {
guard let bin = apexBinaryPath() else {
throw CocoaError(.fileNoSuchFile)
}
let process = Process()
process.executableURL = URL(fileURLWithPath: bin)
var args = ["-t", "html", "--no-mixed-lists", "--embed-images"]
if let baseDir {
args += ["--base-dir", baseDir.path]
}
process.arguments = args
let stdin = Pipe(), stdout = Pipe(), stderr = Pipe()
process.standardInput = stdin
process.standardOutput = stdout
process.standardError = stderr
try process.run()
// Sequential post-exit reads; output is bounded by the document.
stdin.fileHandleForWriting.write(Data(markdown.utf8))
stdin.fileHandleForWriting.closeFile()
let data = stdout.fileHandleForReading.readDataToEndOfFile()
guard !data.isEmpty else {
process.waitUntilExit()
throw NSError(
domain: "apex",
code: Int(process.terminationStatus),
userInfo: [NSLocalizedDescriptionKey: String(data: stderr.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "no stderr"],
)
}
// stdout EOF = conversion done (~18 ms). The ~65 ms teardown after is
// apex's own — reap async, hand the HTML over immediately (#74).
process.terminationHandler = { _ in }
return String(decoding: data, as: UTF8.self)
}
// MARK: Page assembly
/// The reading stylesheet, read fresh per page build (#72 rework): the
/// CSS lives in Resources/reading.css so the look is editable while the
/// app runs — save the file, toggle reading (⌘R), see it. ~3 KB read =
/// microseconds against the ~20 ms apex spawn next to it.
/// Debug builds prefer the REPO copy (`#filePath` points into the
/// checkout) so CSS edits apply with no rebuild; release builds ship the
/// bundled copy (`#filePath` is stripped in release, so this resolves to
/// the bundle without any config).
static func styleSheet() -> String {
#if DEBUG
let repoCSS = URL(fileURLWithPath: #filePath) // …/Museion/ReadingPresenter.swift
.deletingLastPathComponent()
.appendingPathComponent("Resources/reading.css")
if let live = try? String(contentsOf: repoCSS, encoding: .utf8), !live.isEmpty {
return live
}
#endif
return Bundle.main.path(forResource: "reading", ofType: "css").flatMap {
try? String(contentsOf: URL(fileURLWithPath: $0), encoding: .utf8)
} ?? ""
}
/// Render `text` to a full page: chunk-sentinels → apex → attribute
/// restamp → style-injected shell. `postFolder` resolves relative images
/// (nil = drafts: relative paths stay raw, missing images fail soft).
static func page(for text: String, postFolder: URL?) -> (html: String, blocks: [Block]) {
let blocks = blocks(for: text)
guard let fragment = try? apexRender(stampSource(text), baseDir: postFolder) else {
return (fallbackPage(text), blocks)
}
return (page(stampHTML(fragment)), blocks)
}
/// Wrap a stamped fragment into the page shell with the live stylesheet.
static func page(_ stampedFragment: String) -> String {
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\(styleSheet())</style></head><body>\(stampedFragment)</body></html>"
}
/// apex failure / missing binary → editing-treated source text (#69's
/// fallback rule: fallback = the source, not a second renderer).
static func fallbackPage(_ text: String) -> String {
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\(styleSheet())</style></head><body><pre data-source-line=\"1\">\(escapeHTML(text))</pre></body></html>"
}
static func escapeHTML(_ text: String) -> String {
text.replacingOccurrences(of: "&", with: "&amp;")
.replacingOccurrences(of: "<", with: "&lt;")
.replacingOccurrences(of: ">", with: "&gt;")
}
}