// // 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 `` 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 //
    ), ### 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 `` (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("") while index < lines.count, !isBlank(lines[index]) { out.append(String(lines[index])); index += 1 } } return out.joined(separator: "\n") } /// Rewrite `` 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*\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 `