Files
museion/Museion/ReadingPresenter.swift
T
AlexKucera f1c915fed1 chore(reading): lint-clean lift — local renames, tab escape, DOX pass (#76)
Spike-locals renamed at lift time (identifier_name), literal tab in a
string escape fixed (unprintable-ASCII build error), swiftlint
force_try disable for the static regex. AGENTS.md reading-mode section
rewritten for the apex HTML pipeline; native-only Work Guidance line
rescoped to the editing side per ADR-0011.
2026-10-06 18:30:21 +02:00

260 lines
11 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
/// 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;")
}
// MARK: Stylesheet — ProseTypography slots + flow knobs as CSS variables
/// Variables from the live slot values (UserDefaults-driven, #70/#71) +
/// the spike's fixed rules (proven live, #74). `familyName` (not the
/// member PS name) is what CSS font matching wants; weight rides CSS.
static func styleSheet() -> String {
func family(_ font: NSFont) -> String {
"\"\(font.familyName ?? (font.displayName ?? ""))\""
}
func px(_ value: Double) -> String {
"\(String(format: "%.0f", value))px"
}
let body = ProseTypography.bodyFont
let head = ProseTypography.headingFont
let code = ProseTypography.codeFont
let line = ProseTypography.linePoints
return """
:root {
--body-face: \(family(body)), Georgia, serif;
--body-size: \(px(body.pointSize));
--headings-face: \(family(head)), Georgia, serif;
--headings-size: \(px(head.pointSize));
--code-face: \(family(code)), UbuntuMonoNFM, monospace;
--code-size: \(px(code.pointSize));
--lh: \(String(format: "%.2f", ProseTypography.lineHeightMultiple));
--para-space: \(px(Double(line * ProseTypography.paragraphSpacingLines)));
--head-space: \(px(Double(line * ProseTypography.headingSpacingLines)));
--measure: 640px;
--ink: #1d1d1f; --muted: #6e6e73; --hairline: #d2d2d7;
}
html { background: #fbfbfd; }
body {
margin: 24px auto; padding: 0 24px; width: var(--measure); max-width: calc(100vw - 48px);
color: var(--ink); font-family: var(--body-face); font-size: var(--body-size);
line-height: var(--lh); -webkit-font-smoothing: antialiased;
}
p { margin: var(--para-space) 0 0; }
h1, h2, h3, h4, h5, h6 { font-family: var(--headings-face); font-weight: 700; line-height: 1.15; margin: var(--head-space) 0 0; }
h1 { font-size: var(--headings-size); }
h2 { font-size: calc(var(--headings-size) * 0.77); }
h3 { font-size: calc(var(--body-size) + 1px); }
h4, h5, h6 { font-family: var(--body-face); font-size: var(--body-size); font-weight: 700; }
ul, ol { margin: var(--para-space) 0 0; padding-left: 1.6em; }
li { margin: 0; }
li > ul, li > ol { margin: 0; }
pre { font-family: var(--code-face); font-size: var(--code-size); margin: var(--para-space) 0 0;
padding: 8px 12px; border: 1px solid var(--hairline); border-radius: 6px; white-space: pre-wrap; }
code { font-family: var(--code-face); font-size: var(--code-size); }
blockquote { margin: var(--para-space) 0 0; padding-left: 14px; border-left: 1.5px solid var(--hairline); color: var(--muted); }
blockquote p { margin: 0; }
hr { border: none; border-top: 1px solid var(--hairline); margin: var(--head-space) 0 0; }
a { color: var(--ink); text-decoration: underline; text-decoration-color: var(--hairline); text-underline-offset: 3px; }
table { border-collapse: collapse; margin: var(--para-space) 0 0; }
th, td { border: 1px solid var(--hairline); padding: 4px 10px; text-align: left; }
figure { margin: var(--para-space) 0 0; }
figure img { max-height: 1.6em; transition: max-height .25s ease; vertical-align: middle; }
figure:hover img { max-height: 420px; }
figcaption { display: none; }
section.footnotes { color: var(--muted); }
[data-source-line]:hover { background: rgba(0,122,255,.05); }
"""
}
}