ReadingPresenter becomes markdown -> bundled apex -> HTML fragment with data-source-line stamps (chunker sentinels + regex restamp, #74-proven); ReadingSurface becomes one WKWebView reloaded in place (no remount), CSS vars from ProseTypography slots + flow knobs. TextKit reading machinery deleted (ADR-0011: no fallbacks; stale-flow defect dies unfixed). Footnotes now render natively (apex upgrade over #69's fallback). Tests re-targeted at HTML string asserts incl. real-bundled-binary pipeline runs. Closes-nothing: wayfinder #76 on map #20; branch wayfinder/76-apex-html-reading.
235 lines
10 KiB
Swift
235 lines
10 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 i = loc
|
|
while i < end {
|
|
if ns.character(at: i) == 0x0A { line += 1 }
|
|
i += 1
|
|
}
|
|
if delim.location == NSNotFound { break }
|
|
var j = delim.location
|
|
while j < ns.length {
|
|
let c = ns.character(at: j)
|
|
if c == 0x0A { line += 1; j += 1 } else if c == 0x0D { j += 1 } else { break }
|
|
}
|
|
loc = j
|
|
}
|
|
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 = { (l: Substring) in l.allSatisfy { $0 == " " || $0 == "\t" || $0 == "\r" } }
|
|
let lines = source.split(separator: "\n", omittingEmptySubsequences: false)
|
|
var out: [String] = []
|
|
var i = 0
|
|
while i < lines.count {
|
|
if isBlank(lines[i]) { i += 1; continue }
|
|
if !out.isEmpty { out.append("") }
|
|
out.append("<!--S:\(i + 1)-->")
|
|
while i < lines.count && !isBlank(lines[i]) { out.append(String(lines[i])); i += 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 {
|
|
let re = try! NSRegularExpression(pattern: #"<!--S:(\d+)-->\s*\n<([a-zA-Z][a-zA-Z0-9]*)"#)
|
|
let ms = NSMutableString(string: html)
|
|
re.replaceMatches(in: ms, range: NSMakeRange(0, ms.length), withTemplate: "<$2 data-source-line=\"$1\"")
|
|
return ms 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 p in ["/opt/homebrew/bin/apex", "/usr/local/bin/apex"] where FileManager.default.isExecutableFile(atPath: p) {
|
|
return p
|
|
}
|
|
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 p = Process()
|
|
p.executableURL = URL(fileURLWithPath: bin)
|
|
var args = ["-t", "html", "--no-mixed-lists", "--embed-images"]
|
|
if let baseDir { args += ["--base-dir", baseDir.path] }
|
|
p.arguments = args
|
|
let stdin = Pipe(), stdout = Pipe(), stderr = Pipe()
|
|
p.standardInput = stdin
|
|
p.standardOutput = stdout
|
|
p.standardError = stderr
|
|
try p.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 {
|
|
p.waitUntilExit()
|
|
throw NSError(
|
|
domain: "apex",
|
|
code: Int(p.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).
|
|
p.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(_ s: String) -> String {
|
|
s.replacingOccurrences(of: "&", with: "&")
|
|
.replacingOccurrences(of: "<", with: "<")
|
|
.replacingOccurrences(of: ">", with: ">")
|
|
}
|
|
|
|
// 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(_ f: NSFont) -> String {
|
|
"\"\(f.familyName ?? (f.displayName ?? ""))\""
|
|
}
|
|
func px(_ v: Double) -> String { "\(String(format: "%.0f", v))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); }
|
|
"""
|
|
}
|
|
}
|