feat(reading): swap reading surface to apex HTML pipeline (#76)
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.
This commit is contained in:
1 parent
fffcb0a059
commit
cc04ec236e
4 files changed
+505
-965
No files matched your search
+199
-522
@@ -2,556 +2,233 @@
|
||||
// ReadingPresenter.swift
|
||||
// Museion
|
||||
//
|
||||
// #71 (S1.2, map #20): the reading-mode renderer — block-aware per ADR-0010
|
||||
// (blank-line split, per-paragraph inline parse, headings fonted by level;
|
||||
// single-Text .full flatten is the anti-pattern). Presentation-only: the
|
||||
// renderer never touches the file; every block carries its source range so
|
||||
// the surface can map click → source paragraph (#68). Scope per #69: lists
|
||||
// (bullets + ordered + nesting + auto-renumber — one rendering path), ### /
|
||||
// #### headings, HR, fenced code, blockquotes (hairline), tables
|
||||
// (NSTextTable, 1px border), images (hover popover payload), links styled +
|
||||
// ⌘-click; footnotes are the one fallback. Typography per #70: the three
|
||||
// role slots in ProseTypography (Body / Headings / Code).
|
||||
// #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: text → rendered blocks. Pure over its input;
|
||||
/// called on the main actor (NSTextTable construction is MainActor).
|
||||
enum ReadingPresenter {
|
||||
/// Vertical rhythm (user measurements, #71 polish): line-height ≈1.25,
|
||||
/// 1 blank line after paragraphs, 2 after headings.
|
||||
private static let lineHeightMultiple: CGFloat = 1.25
|
||||
private static let paragraphSpacingAfter = lineHeightMultiple // 1 line
|
||||
private static let headingSpacingAfter = lineHeightMultiple * 2 // 2 lines
|
||||
/// One rendered block. `sourceRange` is the block's UTF-16 range in the
|
||||
/// source text (delimiter-exclusive) — the #68 click→edit map.
|
||||
/// 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 content: NSAttributedString
|
||||
let sourceLine: Int
|
||||
let sourceRange: NSRange
|
||||
/// Popover image URL for an `` chunk (#69 hover floor).
|
||||
let imageURL: URL?
|
||||
/// Canvas-drawn decoration (quote hairline / rule / table grid).
|
||||
var decoration: Decoration?
|
||||
}
|
||||
|
||||
/// A block's placement in the built document: where its content landed
|
||||
/// (docRange) ↔ where it came from (sourceRange), plus its resolved image.
|
||||
struct Bound {
|
||||
let docRange: NSRange
|
||||
let sourceRange: NSRange
|
||||
let imageURL: URL?
|
||||
var decoration: Decoration?
|
||||
}
|
||||
|
||||
/// Canvas-drawn decoration for constructs whose layout NSTextTable /
|
||||
/// NSTextBlock can't deliver on modern TextKit (#69 fix: draw it
|
||||
/// ourselves from measured geometry instead).
|
||||
enum Decoration {
|
||||
/// Left hairline at the given indent.
|
||||
case quote(indent: CGFloat)
|
||||
/// Full-width horizontal rule.
|
||||
case rule
|
||||
/// Column x-offsets (incl. closing edge) in mono advance.
|
||||
case table(columns: [CGFloat])
|
||||
}
|
||||
|
||||
/// The reading document: blocks concatenated with paragraph-rhythm
|
||||
/// separators, bounds tracked for click→edit and scroll mapping.
|
||||
struct Document {
|
||||
let content: NSAttributedString
|
||||
let bounds: [Bound]
|
||||
}
|
||||
|
||||
/// Build the single-storage reading document. Image URLs resolve against
|
||||
/// `postFolder` (nil → raw URL kept; the popover fails soft).
|
||||
static func document(for text: String, resolvingImagesIn postFolder: URL?) -> Document {
|
||||
let out = NSMutableAttributedString()
|
||||
var bounds: [Bound] = []
|
||||
for block in blocks(for: text, resolvingImagesIn: postFolder) {
|
||||
if out.length > 0, !out.string.hasSuffix("\n") {
|
||||
out.append(NSAttributedString(string: "\n", attributes: ProseTypography.bodyAttributes))
|
||||
}
|
||||
let start = out.length
|
||||
out.append(block.content)
|
||||
bounds.append(Bound(
|
||||
docRange: NSRange(location: start, length: out.length - start),
|
||||
sourceRange: block.sourceRange,
|
||||
imageURL: block.imageURL,
|
||||
decoration: block.decoration,
|
||||
))
|
||||
}
|
||||
return Document(content: out, bounds: bounds)
|
||||
}
|
||||
|
||||
// MARK: Entry
|
||||
|
||||
/// Render `text` into reading blocks: blank-line split, one block per
|
||||
/// chunk (a run of list items or quote lines renders as one block).
|
||||
/// `postFolder` resolves relative image URLs before the attachment loads.
|
||||
static func blocks(for text: String, resolvingImagesIn postFolder: URL?) -> [Block] {
|
||||
var out: [Block] = []
|
||||
/// 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 {
|
||||
let chunkRange = NSRange(location: loc, length: end - loc)
|
||||
let chunk = ns.substring(with: chunkRange)
|
||||
out.append(block(chunk: chunk, sourceRange: chunkRange, postFolder: postFolder))
|
||||
out.append(Block(sourceLine: line, sourceRange: NSRange(location: loc, length: end - loc)))
|
||||
}
|
||||
loc = delim.location == NSNotFound ? ns.length : delim.location + 2
|
||||
// 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
|
||||
}
|
||||
|
||||
/// Classify one chunk and render it.
|
||||
private static func block(chunk: String, sourceRange: NSRange, postFolder: URL?) -> Block {
|
||||
if let raw = imageURL(in: chunk) {
|
||||
let url = (raw.scheme == nil && raw.path.count > 0)
|
||||
? postFolder?.appendingPathComponent(raw.path) ?? raw : raw
|
||||
return Block(
|
||||
content: imageBlockContent(url: url, alt: altText(in: chunk)),
|
||||
sourceRange: sourceRange,
|
||||
imageURL: url,
|
||||
/// 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"]
|
||||
)
|
||||
}
|
||||
let lines = chunk.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
|
||||
guard let first = lines.first else {
|
||||
return Block(content: NSAttributedString(string: ""), sourceRange: sourceRange, imageURL: nil)
|
||||
}
|
||||
// HR first (#69: `* * *`/`- - -` would otherwise match the bullet
|
||||
// marker `* `/`- ` — same predicate as editing, checked earlier).
|
||||
if lines.count == 1, ProsePresenter.lineKind(first) == .syntaxOnly {
|
||||
return Block(content: hrContent(), sourceRange: sourceRange, imageURL: nil, decoration: .rule)
|
||||
}
|
||||
if lines.allSatisfy({ listItemMarker($0) != nil }) {
|
||||
return Block(content: listContent(lines), sourceRange: sourceRange, imageURL: nil)
|
||||
}
|
||||
if lines.allSatisfy({ blockquoteDepth($0) > 0 }) {
|
||||
return Block(content: quoteContent(lines), sourceRange: sourceRange, imageURL: nil, decoration: quoteDecoration(lines))
|
||||
}
|
||||
if lines.count >= 2, isTableDelimiterRow(lines[1]), let table = tableContent(lines) {
|
||||
return Block(content: table, sourceRange: sourceRange, imageURL: nil, decoration: tableDecoration(lines))
|
||||
}
|
||||
return Block(content: flowContent(lines, first: first), sourceRange: sourceRange, imageURL: nil)
|
||||
// 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: Flow blocks
|
||||
// MARK: Page assembly
|
||||
|
||||
/// Image block: the picture inline (scaled to the column), alt as the
|
||||
/// caption below, link preserved for ⌘-click. Fails soft to alt-text
|
||||
/// paragraph when the file can't load.
|
||||
private static func imageBlockContent(url: URL, alt: String) -> NSAttributedString {
|
||||
let ps = NSMutableParagraphStyle()
|
||||
ps.lineHeightMultiple = lineHeightMultiple
|
||||
ps.paragraphSpacing = paragraphSpacingAfter
|
||||
ps.paragraphSpacingBefore = 8
|
||||
guard let image = NSImage(contentsOf: url), image.size.width > 0 else {
|
||||
return inlineParse(alt.isEmpty ? ")" : alt)
|
||||
/// 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)
|
||||
}
|
||||
let attachment = NSTextAttachment()
|
||||
attachment.image = image
|
||||
let maxW: CGFloat = 480
|
||||
if image.size.width > maxW {
|
||||
attachment.image?.size = NSSize(width: maxW, height: maxW * image.size.height / image.size.width)
|
||||
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 ?? ""))\""
|
||||
}
|
||||
let cell = NSMutableAttributedString(attachment: attachment, attributes: [
|
||||
.paragraphStyle: ps,
|
||||
])
|
||||
if !alt.isEmpty {
|
||||
cell.append(NSAttributedString(string: "\n" + alt, attributes: [
|
||||
.font: ProseTypography.codeFont,
|
||||
.foregroundColor: ProseTypography.syntaxColor,
|
||||
.paragraphStyle: ps,
|
||||
]))
|
||||
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;
|
||||
}
|
||||
return cell
|
||||
}
|
||||
|
||||
private static func flowContent(_ lines: [String], first: String) -> NSAttributedString {
|
||||
if let level = headingLevel(first) {
|
||||
let body = first.drop { $0 == "#" }.trimmingCharacters(in: .whitespaces)
|
||||
let heading = headingContent(body, level: level)
|
||||
// Bug fix: a heading chunk may carry body lines under the heading
|
||||
// (single newline is legal markdown) — they are part of the block.
|
||||
let rest = lines.dropFirst()
|
||||
.map { $0.trimmingCharacters(in: .whitespaces) }
|
||||
.filter { !$0.isEmpty }
|
||||
if rest.isEmpty {
|
||||
return heading
|
||||
}
|
||||
let out = NSMutableAttributedString(attributedString: heading)
|
||||
out.append(NSAttributedString(string: "\n", attributes: ProseTypography.bodyAttributes))
|
||||
out.append(inlineParse(rest.joined(separator: " ")))
|
||||
return out
|
||||
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;
|
||||
}
|
||||
if first.hasPrefix("```") {
|
||||
let inner = lines.dropFirst().dropLast(hasClosingFence(lines) ? 1 : 0)
|
||||
return codeContent(inner.joined(separator: "\n"))
|
||||
}
|
||||
// HR — the editing presenter's syntaxOnly matcher reused verbatim
|
||||
// (#69: same predicate both modes = one mental model).
|
||||
if ProsePresenter.lineKind(first) == .syntaxOnly {
|
||||
return hrContent()
|
||||
}
|
||||
// Paragraph: soft-join lines with single spaces, one inline parse.
|
||||
let joined = lines
|
||||
.map { $0.trimmingCharacters(in: .whitespaces) }
|
||||
.filter { !$0.isEmpty }
|
||||
.joined(separator: " ")
|
||||
let para = inlineParse(joined)
|
||||
let ps = NSMutableParagraphStyle()
|
||||
ps.lineHeightMultiple = lineHeightMultiple
|
||||
ps.paragraphSpacing = paragraphSpacingAfter
|
||||
let styled = NSMutableAttributedString(attributedString: para)
|
||||
styled.addAttribute(.paragraphStyle, value: ps, range: NSRange(location: 0, length: styled.length))
|
||||
return styled
|
||||
}
|
||||
|
||||
private static func headingContent(_ text: String, level: Int) -> NSAttributedString {
|
||||
// #70: h1 = Headings slot size; h2 = 0.77×; ### = body+1 (≈17–18);
|
||||
// ####+ floors at bold body.
|
||||
let slotSize = ProseTypography.headingFont.pointSize
|
||||
let size: CGFloat = switch level {
|
||||
case 1: slotSize
|
||||
case 2: (slotSize * 0.77).rounded()
|
||||
case 3: ProseTypography.bodyFont.pointSize + 1
|
||||
default: ProseTypography.bodyFont.pointSize
|
||||
}
|
||||
let ps = NSMutableParagraphStyle()
|
||||
ps.lineHeightMultiple = lineHeightMultiple
|
||||
ps.paragraphSpacing = headingSpacingAfter
|
||||
ps.paragraphSpacingBefore = level == 1 ? 26 : (level == 2 ? 20 : 14)
|
||||
return NSAttributedString(string: text, attributes: [
|
||||
.font: ProseTypography.headingFont(size: size),
|
||||
.paragraphStyle: ps,
|
||||
.foregroundColor: ProseTypography.foregroundColor,
|
||||
])
|
||||
}
|
||||
|
||||
private static func codeContent(_ code: String) -> NSAttributedString {
|
||||
let ps = NSMutableParagraphStyle()
|
||||
ps.lineHeightMultiple = lineHeightMultiple
|
||||
ps.paragraphSpacing = paragraphSpacingAfter
|
||||
ps.paragraphSpacingBefore = 6
|
||||
ps.firstLineHeadIndent = 12
|
||||
ps.headIndent = 12
|
||||
return NSAttributedString(string: code, attributes: [
|
||||
.font: ProseTypography.codeFont,
|
||||
.paragraphStyle: ps,
|
||||
.foregroundColor: ProseTypography.syntaxColor,
|
||||
])
|
||||
}
|
||||
|
||||
private static func hrContent() -> NSAttributedString {
|
||||
// Hairline drawn by the canvas (Decoration.rule).
|
||||
let ps = NSMutableParagraphStyle()
|
||||
ps.lineHeightMultiple = lineHeightMultiple
|
||||
ps.paragraphSpacingBefore = 8
|
||||
ps.paragraphSpacing = 8
|
||||
return NSAttributedString(string: " ", attributes: [
|
||||
.font: ProseTypography.codeFont,
|
||||
.paragraphStyle: ps,
|
||||
.foregroundColor: NSColor.clear,
|
||||
])
|
||||
}
|
||||
|
||||
// MARK: Lists (#69: one path for bullets and ordered — the counter makes
|
||||
|
||||
// auto-renumbering free; glyphs only, the file is never rewritten)
|
||||
|
||||
private static func listContent(_ lines: [String]) -> NSAttributedString {
|
||||
let out = NSMutableAttributedString()
|
||||
var counters: [Int: Int] = [:]
|
||||
for (index, line) in lines.enumerated() {
|
||||
guard let marker = listItemMarker(line) else { continue }
|
||||
let indent: CGFloat = 16 + CGFloat(marker.level - 1) * 18
|
||||
let ps = NSMutableParagraphStyle()
|
||||
ps.lineHeightMultiple = lineHeightMultiple
|
||||
ps.firstLineHeadIndent = indent
|
||||
ps.headIndent = indent + 18
|
||||
ps.paragraphSpacing = 5
|
||||
let glyph: String
|
||||
if marker.ordered {
|
||||
counters[marker.level, default: 0] += 1
|
||||
glyph = "\(counters[marker.level]!). "
|
||||
} else {
|
||||
glyph = "• "
|
||||
}
|
||||
let item = NSMutableAttributedString(string: glyph, attributes: ProseTypography.bodyAttributes)
|
||||
item.append(inlineParse(marker.payload.trimmingCharacters(in: .whitespaces)))
|
||||
item.addAttribute(
|
||||
.paragraphStyle, value: ps,
|
||||
range: NSRange(location: 0, length: item.length),
|
||||
)
|
||||
out.append(item)
|
||||
if index < lines.count - 1 {
|
||||
out.append(NSAttributedString(string: "\n", attributes: ProseTypography.bodyAttributes))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// MARK: Blockquotes (#69: `>` never visible, hairline rule, nesting indents)
|
||||
|
||||
private static func quoteContent(_ lines: [String]) -> NSAttributedString {
|
||||
// Hairline drawn by the canvas (Decoration.quote) — NSTextBlock
|
||||
// drawing zero-widths the line rect on modern TextKit, wrapping
|
||||
// content one character per line.
|
||||
let out = NSMutableAttributedString()
|
||||
for (index, line) in lines.enumerated() {
|
||||
let depth = blockquoteDepth(line)
|
||||
let indent = CGFloat(6 + (depth - 1) * 18)
|
||||
let ps = NSMutableParagraphStyle()
|
||||
ps.lineHeightMultiple = lineHeightMultiple
|
||||
ps.firstLineHeadIndent = indent
|
||||
ps.headIndent = indent
|
||||
ps.paragraphSpacing = 4
|
||||
let styled = NSMutableAttributedString(
|
||||
attributedString: inlineParse(quoteBody(line)),
|
||||
)
|
||||
styled.addAttribute(
|
||||
.paragraphStyle, value: ps,
|
||||
range: NSRange(location: 0, length: styled.length),
|
||||
)
|
||||
out.append(styled)
|
||||
if index < lines.count - 1 {
|
||||
out.append(NSAttributedString(string: "\n", attributes: ProseTypography.bodyAttributes))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/// Payload after the `>` marker run (markers + surrounding spaces).
|
||||
private static func quoteBody(_ line: String) -> String {
|
||||
let prefix = line.prefix { $0 == ">" || $0 == " " }
|
||||
return String(line.dropFirst(prefix.count)).trimmingCharacters(in: .whitespaces)
|
||||
}
|
||||
|
||||
// MARK: Tables (#69: mono grid — plain padded text; the canvas draws the
|
||||
|
||||
// grid lines from Decoration.table. NSTextTable cannot lay out on modern
|
||||
// TextKit: rows stack vertically, columns never align.)
|
||||
|
||||
private static func tableContent(_ lines: [String]) -> NSAttributedString? {
|
||||
let header = tableCells(lines[0])
|
||||
let aligns = tableAlignments(lines[1])
|
||||
guard !header.isEmpty, header.count == aligns.count else { return nil }
|
||||
let dataRows = lines.enumerated().filter { $0.offset != 1 }.map(\.element)
|
||||
let cellTexts = ([lines[0]] + dataRows.dropFirst()).map(tableCells)
|
||||
let columnCount = header.count
|
||||
var widths = Array(repeating: 0, count: columnCount)
|
||||
for row in cellTexts {
|
||||
for (column, cell) in row.enumerated() where column < columnCount {
|
||||
widths[column] = max(widths[column], cell.count)
|
||||
}
|
||||
}
|
||||
let pad = 3
|
||||
let codeAttrs: [NSAttributedString.Key: Any] = [
|
||||
.font: ProseTypography.codeFont,
|
||||
.foregroundColor: ProseTypography.foregroundColor,
|
||||
]
|
||||
let out = NSMutableAttributedString()
|
||||
func gridLine(_ cells: [String]) -> NSAttributedString {
|
||||
var line = ""
|
||||
for column in 0 ..< columnCount {
|
||||
let text = column < cells.count ? cells[column] : ""
|
||||
let width = widths[column]
|
||||
let padded: String
|
||||
switch aligns[column] {
|
||||
case .center where text.count < width:
|
||||
let left = (width - text.count) / 2
|
||||
padded = String(repeating: " ", count: left) + text
|
||||
+ String(repeating: " ", count: width - text.count - left)
|
||||
case .right:
|
||||
padded = String(repeating: " ", count: max(0, width - text.count)) + text
|
||||
default:
|
||||
padded = text + String(repeating: " ", count: max(0, width - text.count))
|
||||
}
|
||||
line += String(repeating: " ", count: pad) + padded + String(repeating: " ", count: pad)
|
||||
}
|
||||
return NSAttributedString(string: line, attributes: codeAttrs)
|
||||
}
|
||||
out.append(gridLine(cellTexts[0]))
|
||||
for row in cellTexts.dropFirst() {
|
||||
out.append(NSAttributedString(string: "\n", attributes: codeAttrs))
|
||||
out.append(gridLine(row))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/// Quote decoration: left hairline at the shallowest quote indent.
|
||||
private static func quoteDecoration(_ lines: [String]) -> Decoration {
|
||||
let minIndent = lines.compactMap { line -> CGFloat? in
|
||||
blockquoteDepth(line) > 0 ? CGFloat(6 + (blockquoteDepth(line) - 1) * 18) : nil
|
||||
}.min() ?? 6
|
||||
return .quote(indent: minIndent)
|
||||
}
|
||||
|
||||
/// Table decoration: column x-offsets (+ closing edge) in mono advance.
|
||||
private static func tableDecoration(_ lines: [String]) -> Decoration {
|
||||
let header = tableCells(lines[0])
|
||||
let dataRows = lines.enumerated().filter { $0.offset != 1 }.map(\.element)
|
||||
let cellTexts = ([lines[0]] + dataRows.dropFirst()).map(tableCells)
|
||||
var widths = Array(repeating: 0, count: header.count)
|
||||
for row in cellTexts {
|
||||
for (column, cell) in row.enumerated() where column < header.count {
|
||||
widths[column] = max(widths[column], cell.count)
|
||||
}
|
||||
}
|
||||
let advance = ("0" as NSString).size(withAttributes: [
|
||||
.font: ProseTypography.codeFont,
|
||||
]).width
|
||||
var offsets: [CGFloat] = []
|
||||
var running = 0.0
|
||||
for width in widths {
|
||||
offsets.append(running)
|
||||
running += CGFloat(width + 6) * advance // cell pad 3 + 3, matches gridLine
|
||||
}
|
||||
return .table(columns: offsets + [running])
|
||||
}
|
||||
|
||||
private static func tableCells(_ line: String) -> [String] {
|
||||
var trimmed = line.trimmingCharacters(in: .whitespaces)
|
||||
if trimmed.hasPrefix("|") {
|
||||
trimmed.removeFirst()
|
||||
}
|
||||
if trimmed.hasSuffix("|") {
|
||||
trimmed.removeLast()
|
||||
}
|
||||
return trimmed.components(separatedBy: "|").map { $0.trimmingCharacters(in: .whitespaces) }
|
||||
}
|
||||
|
||||
private static func tableAlignments(_ delimiter: String) -> [NSTextAlignment] {
|
||||
tableCells(delimiter).map { cell in
|
||||
let left = cell.hasPrefix(":")
|
||||
let right = cell.hasSuffix(":")
|
||||
if left == right {
|
||||
return left ? .center : .left
|
||||
} // --- = left, :---: = center
|
||||
return left ? .left : .right
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Inline (#69: marker glyphs never show; links styled + retained)
|
||||
|
||||
/// One `AttributedString(markdown:)` parse, presentation-interpreted:
|
||||
/// emphasis/strong → italic/bold body face, code spans → code face,
|
||||
/// links styled + kept for ⌘-click.
|
||||
static func inlineParse(_ raw: String) -> NSAttributedString {
|
||||
var opts = AttributedString.MarkdownParsingOptions()
|
||||
opts.interpretedSyntax = .inlineOnlyPreservingWhitespace
|
||||
guard let parsed = try? AttributedString(markdown: raw, options: opts) else {
|
||||
return NSAttributedString(string: raw, attributes: ProseTypography.bodyAttributes)
|
||||
}
|
||||
let out = NSMutableAttributedString()
|
||||
for run in parsed.runs {
|
||||
var attrs = ProseTypography.bodyAttributes
|
||||
if let intent = run.inlinePresentationIntent {
|
||||
if intent.contains(.code) {
|
||||
attrs = ProseTypography.codeAttributes
|
||||
} else {
|
||||
var font = ProseTypography.bodyFont
|
||||
if intent.contains(.emphasized) {
|
||||
font = ProseTypography.italicBodyFont
|
||||
}
|
||||
if intent.contains(.stronglyEmphasized) {
|
||||
font = ProseTypography.boldBodyFont
|
||||
}
|
||||
attrs[.font] = font
|
||||
}
|
||||
}
|
||||
if let link = run.link {
|
||||
attrs[.link] = link
|
||||
attrs[.underlineStyle] = NSUnderlineStyle.single.rawValue
|
||||
attrs[.cursor] = NSCursor.pointingHand
|
||||
}
|
||||
out.append(NSAttributedString(
|
||||
string: String(parsed[run.range].characters),
|
||||
attributes: attrs,
|
||||
))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/// Alt text of an `` chunk (empty when absent).
|
||||
private static func altText(in chunk: String) -> String {
|
||||
let trimmed = chunk.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard trimmed.hasPrefix("!["), let closeBracket = trimmed.firstIndex(of: "]") else { return "" }
|
||||
return String(trimmed[trimmed.index(trimmed.startIndex, offsetBy: 2) ..< closeBracket])
|
||||
}
|
||||
|
||||
// MARK: Construct matchers
|
||||
|
||||
private struct ListMarker {
|
||||
let level: Int
|
||||
let ordered: Bool
|
||||
let payload: String
|
||||
}
|
||||
|
||||
/// `- `/`* ` bullet or `N.`/`N)` ordered marker. Indent levels: 0–1 sp → 1,
|
||||
/// 2–3 sp → 2, 4+ sp → 3+ (2-space and 4-space styles both accepted, #69).
|
||||
private static func listItemMarker(_ line: String) -> ListMarker? {
|
||||
let indent = line.prefix { $0 == " " }.count
|
||||
let rest = line.dropFirst(indent)
|
||||
if rest.hasPrefix("- ") || rest.hasPrefix("* ") {
|
||||
return ListMarker(level: indentLevel(indent), ordered: false, payload: String(rest.dropFirst(2)))
|
||||
}
|
||||
let digits = rest.prefix { $0.isNumber }.count
|
||||
guard digits > 0 else { return nil }
|
||||
let after = rest.dropFirst(digits)
|
||||
guard after.hasPrefix(". ") || after.hasPrefix(") ") else { return nil }
|
||||
return ListMarker(level: indentLevel(indent), ordered: true, payload: String(after.dropFirst(2)))
|
||||
}
|
||||
|
||||
private static func indentLevel(_ spaces: Int) -> Int {
|
||||
spaces <= 1 ? 1 : (spaces <= 3 ? 2 : min(3 + (spaces - 4) / 2, 6))
|
||||
}
|
||||
|
||||
/// `>`-prefix depth (1 for `> `, 2 for `>> `; spaces tolerated).
|
||||
private static func blockquoteDepth(_ line: String) -> Int {
|
||||
line.prefix { $0 == ">" || $0 == " " }.filter { $0 == ">" }.count
|
||||
}
|
||||
|
||||
/// `# `-style heading with its level; requires a space after the hashes
|
||||
/// (so prose like `#hashtag` stays a paragraph).
|
||||
private static func headingLevel(_ line: String) -> Int? {
|
||||
let trimmed = line.drop { $0 == " " }
|
||||
let hashes = trimmed.prefix { $0 == "#" }.count
|
||||
guard hashes >= 1, hashes <= 6 else { return nil }
|
||||
let after = trimmed.dropFirst(hashes)
|
||||
return after.hasPrefix(" ") || after.isEmpty ? hashes : nil
|
||||
}
|
||||
|
||||
/// `| --- | :---: |` delimiter row under a header row.
|
||||
private static func isTableDelimiterRow(_ line: String) -> Bool {
|
||||
let trimmed = line.trimmingCharacters(in: .whitespaces)
|
||||
guard trimmed.hasPrefix("|"), trimmed.hasSuffix("|"), trimmed.count >= 4 else { return false }
|
||||
let cells = tableCells(trimmed)
|
||||
return !cells.isEmpty && cells.allSatisfy { cell in
|
||||
!cell.isEmpty && cell.allSatisfy { $0 == "-" || $0 == ":" }
|
||||
}
|
||||
}
|
||||
|
||||
private static func hasClosingFence(_ lines: [String]) -> Bool {
|
||||
guard let last = lines.last else { return false }
|
||||
return last.trimmingCharacters(in: .whitespaces).hasPrefix("```")
|
||||
}
|
||||
|
||||
/// `` → url when the chunk is exactly one image line (#69: the
|
||||
/// inline parser renders image syntax as bare alt text with no link
|
||||
/// attribute, so the URL is recovered at chunk level).
|
||||
private static func imageURL(in chunk: String) -> URL? {
|
||||
let trimmed = chunk.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard trimmed.hasPrefix("![") else { return nil }
|
||||
guard let closeBracket = trimmed.firstIndex(of: "]") else { return nil }
|
||||
let afterBracket = trimmed.index(after: closeBracket)
|
||||
guard afterBracket < trimmed.endIndex, trimmed[afterBracket] == "(" else { return nil }
|
||||
let start = trimmed.index(after: afterBracket)
|
||||
guard let closeParen = trimmed[start...].firstIndex(of: ")") else { return nil }
|
||||
return URL(string: String(trimmed[start ..< closeParen]))
|
||||
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); }
|
||||
"""
|
||||
}
|
||||
}
|
||||
+177
-285
@@ -2,16 +2,20 @@
|
||||
// ReadingSurface.swift
|
||||
// Museion
|
||||
//
|
||||
// #71 (S1.2, map #20): the reading-mode surface — the renderer's blocks set
|
||||
// into a read-only, selectable NSTextView (#68: reading is a presentation
|
||||
// of the same TextKit2 document, not a separate view stack). Interaction
|
||||
// per #68: drag-select stays native; a tap with no selection = edit intent
|
||||
// (drop to editing at the clicked block's source paragraph); ⌘-click opens
|
||||
// links; hovering an image block pops the loaded image (#69 floor).
|
||||
// #76 (S1.2, map #20; ADR-0011): the reading surface is one WKWebView,
|
||||
// reloaded in place — never remounted per document (the remount was the
|
||||
// dominant switch cost, #74). Loads ReadingPresenter's page (apex HTML +
|
||||
// data-source-line map). Interaction per #68: tap = edit intent at the
|
||||
// tapped block's source paragraph; ⌘-click opens links; scroll tracking
|
||||
// feeds the flip-back map. Typography/flow changes reload the page (CSS
|
||||
// vars are injected at load). The TextKit canvas (ReadingCanvasView,
|
||||
// decorations, framesForRange, ImagePopoverView) is deleted with the
|
||||
// pivot — ADR-0011: no fallbacks.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
import WebKit
|
||||
|
||||
/// Live reading-position state for flip-back scroll mapping (#68). Plain
|
||||
/// class held `@State` by the editor — reference identity survives renders.
|
||||
@@ -31,320 +35,208 @@ final class CaretHintBox {
|
||||
var consumed = true
|
||||
}
|
||||
|
||||
/// Reading surface: renders `text` via ReadingPresenter into a scrollable,
|
||||
/// read-only canvas. Rebuilds when `generation` moves (open / Yes-reload) or
|
||||
/// the text genuinely changes (draft edit path).
|
||||
/// Reading surface: renders `text` via ReadingPresenter (apex HTML) into a
|
||||
/// WKWebView reloaded in place. Re-renders when `generation` moves (open /
|
||||
/// Yes-reload), the text changes (draft path), or flow knobs move — never
|
||||
/// per keystroke.
|
||||
struct ReadingSurface: NSViewRepresentable {
|
||||
let text: String
|
||||
/// Session loadGeneration (0 for drafts) — rebuild key, never per keystroke.
|
||||
var generation: Int
|
||||
/// The post's folder — resolves relative image URLs. Nil for drafts.
|
||||
/// The post's folder — resolves relative image URLs (apex --base-dir).
|
||||
/// Nil for drafts.
|
||||
var postFolder: URL?
|
||||
/// UTF-16 caret location captured when reading opened; scrolls the
|
||||
/// containing block to the top (#68 mapping attempt).
|
||||
/// UTF-16 caret location captured when reading opened; scrolls that
|
||||
/// block to the top (#68 mapping attempt).
|
||||
var entryCaretLocation: Int?
|
||||
var onEditIntent: (Int) -> Void
|
||||
/// Flip-back scroll mapping target.
|
||||
var stateBox: ReadingStateBox?
|
||||
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let tv = ReadingCanvasView()
|
||||
tv.isEditable = false
|
||||
tv.isSelectable = true
|
||||
tv.isRichText = false
|
||||
tv.allowsUndo = false
|
||||
tv.isAutomaticQuoteSubstitutionEnabled = false
|
||||
tv.isAutomaticDashSubstitutionEnabled = false
|
||||
tv.isAutomaticTextReplacementEnabled = false
|
||||
tv.isAutomaticSpellingCorrectionEnabled = false
|
||||
tv.backgroundColor = NSColor.white
|
||||
tv.typingAttributes = ProseTypography.bodyAttributes
|
||||
tv.minSize = NSSize(width: 0, height: 0)
|
||||
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude)
|
||||
tv.isVerticallyResizable = true
|
||||
tv.isHorizontallyResizable = false
|
||||
tv.autoresizingMask = [.width]
|
||||
// Wrap to the editor column (#68/71 fix): the container tracks the
|
||||
// view width — a fixed 640pt measure clipped in narrower columns.
|
||||
tv.textContainer?.containerSize = NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude)
|
||||
tv.textContainer?.widthTracksTextView = true
|
||||
tv.textContainer?.lineFragmentPadding = 24
|
||||
tv.textContainerInset = NSSize(width: 0, height: 24)
|
||||
let scroll = NSScrollView()
|
||||
scroll.documentView = tv
|
||||
scroll.hasVerticalScroller = true
|
||||
scroll.autohidesScrollers = true
|
||||
scroll.drawsBackground = true
|
||||
scroll.backgroundColor = NSColor.white
|
||||
tv.onEditIntent = onEditIntent
|
||||
tv.stateBox = stateBox
|
||||
context.coordinator.canvas = tv
|
||||
context.coordinator.watchDefaults(tv, representable: self)
|
||||
return scroll
|
||||
}
|
||||
|
||||
func updateNSView(_ scroll: NSScrollView, context: Context) {
|
||||
guard let tv = scroll.documentView as? ReadingCanvasView else { return }
|
||||
tv.onEditIntent = onEditIntent
|
||||
tv.stateBox = stateBox
|
||||
tv.postFolder = postFolder
|
||||
guard context.coordinator.builtGeneration != generation || context.coordinator.builtText != text else { return }
|
||||
context.coordinator.builtGeneration = generation
|
||||
context.coordinator.builtText = text
|
||||
let doc = ReadingPresenter.document(for: text, resolvingImagesIn: postFolder)
|
||||
tv.textStorage?.setAttributedString(doc.content)
|
||||
tv.blockBounds = doc.bounds
|
||||
tv.needsLayout = true
|
||||
tv.layoutSubtreeIfNeeded()
|
||||
if let caret = entryCaretLocation, let bound = tv.bound(containing: caret) {
|
||||
tv.scrollRangeToVisible(NSRange(location: bound.docRange.location, length: 0))
|
||||
} else {
|
||||
tv.scroll(NSPoint(x: 0, y: 0))
|
||||
}
|
||||
}
|
||||
|
||||
func makeCoordinator() -> Coordinator {
|
||||
Coordinator()
|
||||
}
|
||||
|
||||
final class Coordinator {
|
||||
weak var canvas: ReadingCanvasView?
|
||||
var builtGeneration = -1
|
||||
var builtText = ""
|
||||
func makeNSView(context: Context) -> WKWebView {
|
||||
let cfg = WKWebViewConfiguration()
|
||||
let ucc = cfg.userContentController
|
||||
ucc.addUserScript(WKUserScript(source: Self.probeJS, injectionTime: .atDocumentEnd, forMainFrameOnly: true))
|
||||
ucc.add(context.coordinator, name: "sourceClick")
|
||||
ucc.add(context.coordinator, name: "sourceScroll")
|
||||
ucc.add(context.coordinator, name: "openLink")
|
||||
let wv = WKWebView(frame: .zero, configuration: cfg)
|
||||
wv.navigationDelegate = context.coordinator
|
||||
// Paint the page bg while loading instead of AppKit white (flash fix, #74).
|
||||
wv.underPageBackgroundColor = NSColor(red: 0.984, green: 0.984, blue: 0.992, alpha: 1)
|
||||
context.coordinator.webView = wv
|
||||
context.coordinator.watchDefaults()
|
||||
return wv
|
||||
}
|
||||
|
||||
func updateNSView(_ wv: WKWebView, context: Context) {
|
||||
let c = context.coordinator
|
||||
c.onEditIntent = onEditIntent
|
||||
c.stateBox = stateBox
|
||||
c.postFolder = postFolder
|
||||
let key = "\(generation):\(text.hashValue):\(ProseTypography.flowKey)"
|
||||
guard c.loadedKey != key else { return }
|
||||
c.load(text: text, generation: generation, entryCaret: entryCaretLocation, key: key)
|
||||
}
|
||||
|
||||
// Mapping probes: click → source line; ⌘-click → open; scroll → top
|
||||
// visible source line (same map → scroll-sync). Spike-verified (#74).
|
||||
static let probeJS = """
|
||||
function stamped(el){ return el.closest('[data-source-line]'); }
|
||||
document.addEventListener('click', function(e){
|
||||
const a = e.target.closest('a');
|
||||
if (a) {
|
||||
e.preventDefault(); // reading never navigates in-app
|
||||
if (e.metaKey || e.ctrlKey) window.webkit.messageHandlers.openLink.postMessage(a.href);
|
||||
else { const s = stamped(a); if (s) window.webkit.messageHandlers.sourceClick.postMessage(s.dataset.sourceLine); }
|
||||
return;
|
||||
}
|
||||
const s = stamped(e.target);
|
||||
if (s) window.webkit.messageHandlers.sourceClick.postMessage(s.dataset.sourceLine);
|
||||
}, true);
|
||||
let ticking = false;
|
||||
addEventListener('scroll', function(){
|
||||
if (ticking) return; ticking = true;
|
||||
requestAnimationFrame(function(){
|
||||
ticking = false;
|
||||
for (const el of document.querySelectorAll('[data-source-line]')) {
|
||||
const r = el.getBoundingClientRect();
|
||||
if (r.bottom > 44) { window.webkit.messageHandlers.sourceScroll.postMessage(el.dataset.sourceLine); return; }
|
||||
}
|
||||
});
|
||||
}, {passive: true});
|
||||
"""
|
||||
|
||||
/// Scroll the entry block to the top after paint (#68 entry mapping).
|
||||
static func entryScrollJS(_ line: Int) -> String {
|
||||
"""
|
||||
(function(line){
|
||||
for (const el of document.querySelectorAll('[data-source-line]')) {
|
||||
if (parseInt(el.dataset.sourceLine) === line) {
|
||||
window.scrollTo(0, el.getBoundingClientRect().top + window.scrollY - 24);
|
||||
return;
|
||||
}
|
||||
}
|
||||
})(\(line));
|
||||
"""
|
||||
}
|
||||
|
||||
// @MainActor: WKNavigationDelegate + WKScriptMessageHandler requirements
|
||||
// are MainActor in the SDK; the project is default-MainActor anyway.
|
||||
@MainActor
|
||||
final class Coordinator: NSObject, WKNavigationDelegate, WKScriptMessageHandler {
|
||||
weak var webView: WKWebView?
|
||||
var onEditIntent: ((Int) -> Void)?
|
||||
var stateBox: ReadingStateBox?
|
||||
var postFolder: URL?
|
||||
var loadedKey = ""
|
||||
/// Block map of the loaded page (source line + range).
|
||||
var blocks: [ReadingPresenter.Block] = []
|
||||
/// Line to scroll to once the page paints (entry mapping, #68).
|
||||
var pendingEntryScrollLine: Int?
|
||||
var painted = false
|
||||
private var lastText = ""
|
||||
private var defaultsObserver: NSObjectProtocol?
|
||||
private var appliedFlowKey = ""
|
||||
|
||||
/// Rebuild the rendered document when typography/flow knobs move
|
||||
/// (SwiftUI doesn't re-call updateNSView on UserDefaults writes).
|
||||
func watchDefaults(_: ReadingCanvasView, representable: ReadingSurface) {
|
||||
/// Build + load the page for `text`. All render paths land here
|
||||
/// (updateNSView, typography-change reload).
|
||||
func load(text: String, generation: Int, entryCaret: Int?, key: String) {
|
||||
loadedKey = key
|
||||
lastText = text
|
||||
painted = false
|
||||
let (pageHTML, blockMap) = ReadingPresenter.page(for: text, postFolder: postFolder)
|
||||
blocks = blockMap
|
||||
pendingEntryScrollLine = entryLine(for: entryCaret)
|
||||
webView?.loadHTMLString(pageHTML, baseURL: nil)
|
||||
}
|
||||
|
||||
/// The block whose source range holds the caret; else the next block
|
||||
/// at/after it (#68: jank fallback = top of page via nil).
|
||||
private func entryLine(for caret: Int?) -> Int? {
|
||||
guard let caret else { return nil }
|
||||
if let hit = blocks.first(where: { NSLocationInRange(caret, $0.sourceRange) }) {
|
||||
return hit.sourceLine
|
||||
}
|
||||
return blocks.first { $0.sourceRange.location >= caret }?.sourceLine
|
||||
}
|
||||
|
||||
/// Typography/flow knob moves reload the page (CSS vars are injected
|
||||
/// at load; SwiftUI doesn't re-call updateNSView on UserDefaults
|
||||
/// writes).
|
||||
func watchDefaults() {
|
||||
guard defaultsObserver == nil else { return }
|
||||
appliedFlowKey = ProseTypography.flowKey
|
||||
defaultsObserver = NotificationCenter.default.addObserver(
|
||||
forName: UserDefaults.didChangeNotification,
|
||||
object: nil,
|
||||
queue: .main,
|
||||
queue: .main
|
||||
) { [weak self] _ in
|
||||
guard let self, let canvas else { return }
|
||||
let key = ProseTypography.flowKey
|
||||
guard key != appliedFlowKey else { return }
|
||||
appliedFlowKey = key
|
||||
let doc = ReadingPresenter.document(for: representable.text, resolvingImagesIn: representable.postFolder)
|
||||
canvas.textStorage?.setAttributedString(doc.content)
|
||||
canvas.blockBounds = doc.bounds
|
||||
canvas.needsDisplay = true
|
||||
Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
let key = ProseTypography.flowKey
|
||||
guard key != appliedFlowKey else { return }
|
||||
appliedFlowKey = key
|
||||
self.load(
|
||||
text: lastText,
|
||||
generation: 0,
|
||||
entryCaret: nil,
|
||||
key: "\(loadedKey)|flow"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The reading canvas: click discrimination, ⌘-click links, image hover
|
||||
/// popover, top-block scroll tracking. Read-only over rendered content.
|
||||
final class ReadingCanvasView: NSTextView {
|
||||
typealias BlockBound = ReadingPresenter.Bound
|
||||
// ponytail: observer registration lives for the coordinator's
|
||||
// lifetime (app-scoped defaults notifications, same as ProseTextView's
|
||||
// coordinator — no removal, matching the codebase convention).
|
||||
|
||||
var blockBounds: [BlockBound] = []
|
||||
var onEditIntent: ((Int) -> Void)?
|
||||
var stateBox: ReadingStateBox?
|
||||
var postFolder: URL?
|
||||
// MARK: WKNavigationDelegate
|
||||
|
||||
private var popover: NSPopover?
|
||||
private var hoverTrackingArea: NSTrackingArea?
|
||||
|
||||
/// Last bound starting at or before `index` (spacing separators clamp to
|
||||
/// the preceding block).
|
||||
func bound(containing index: Int) -> BlockBound? {
|
||||
blockBounds.last { $0.docRange.location <= index }
|
||||
}
|
||||
|
||||
// MARK: Decorations (#69 fix: quote hairlines, HR rules, table grids —
|
||||
|
||||
// drawn from measured TK2 fragment geometry; NSTextBlock/NSTextTable
|
||||
// layout is broken on modern TextKit and the TK1-compat bridge reports
|
||||
// wrong rects. Enumeration pattern is probe-proven: walk ALL fragments
|
||||
// from document start, map each to a doc offset, slice per bound.)
|
||||
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
super.draw(dirtyRect)
|
||||
let origin = textContainerOrigin
|
||||
for bound in blockBounds {
|
||||
guard let decoration = bound.decoration else { continue }
|
||||
// frames arrive in CONTAINER space; the view draws text at
|
||||
// textContainerOrigin + frame (inset shifts it — the missing
|
||||
// +origin.y drew every decoration 20pt too high).
|
||||
let frames = framesForRange(bound.docRange)
|
||||
.map { CGRect(x: $0.minX + origin.x, y: $0.minY + origin.y, width: $0.width, height: $0.height) }
|
||||
guard let firstFrame = frames.first, let lastFrame = frames.last else { continue }
|
||||
switch decoration {
|
||||
case let .quote(indent):
|
||||
let x = (textContainer?.lineFragmentPadding ?? 0) + indent - 6
|
||||
let path = NSBezierPath()
|
||||
path.move(to: NSPoint(x: x, y: firstFrame.minY))
|
||||
path.line(to: NSPoint(x: x, y: lastFrame.maxY))
|
||||
path.lineWidth = 2
|
||||
ProseTypography.quoteRuleColor.setStroke()
|
||||
path.stroke()
|
||||
case .rule:
|
||||
let y = (firstFrame.minY + firstFrame.maxY) / 2
|
||||
let path = NSBezierPath()
|
||||
path.move(to: NSPoint(x: 0, y: y))
|
||||
path.line(to: NSPoint(x: (textContainer?.size.width ?? 0), y: y))
|
||||
path.lineWidth = 1
|
||||
ProseTypography.tableBorderColor.setStroke()
|
||||
path.stroke()
|
||||
case let .table(columns):
|
||||
let originX = (textContainer?.lineFragmentPadding ?? 0)
|
||||
let path = NSBezierPath()
|
||||
for offset in columns {
|
||||
let x = originX + offset
|
||||
path.move(to: NSPoint(x: x, y: firstFrame.minY))
|
||||
path.line(to: NSPoint(x: x, y: lastFrame.maxY))
|
||||
}
|
||||
let ys = [firstFrame.minY] + frames.map(\.maxY)
|
||||
for y in ys {
|
||||
path.move(to: NSPoint(x: originX, y: y))
|
||||
path.line(to: NSPoint(x: originX + (columns.last ?? 0), y: y))
|
||||
}
|
||||
path.lineWidth = 1
|
||||
ProseTypography.tableBorderColor.setStroke()
|
||||
path.stroke()
|
||||
}
|
||||
func webView(_ wv: WKWebView, didFinish nav: WKNavigation!) {
|
||||
guard !painted else { return }
|
||||
painted = true
|
||||
guard let line = pendingEntryScrollLine else { return }
|
||||
pendingEntryScrollLine = nil
|
||||
wv.evaluateJavaScript(ReadingSurface.entryScrollJS(line))
|
||||
}
|
||||
}
|
||||
|
||||
/// Line frames for a document character range, engine-agnostic: TK2
|
||||
/// fragments when present, else TK1 boundingRect per character line
|
||||
/// (lineFragmentRect returns degenerate rects mid-layout on TK1 here).
|
||||
func framesForRange(_ docRange: NSRange) -> [CGRect] {
|
||||
if let tlm = textLayoutManager, let tcm = tlm.textContentManager {
|
||||
let docStart = tcm.documentRange.location
|
||||
var frames: [CGRect] = []
|
||||
tlm.enumerateTextLayoutFragments(from: docStart) { fragment in
|
||||
let tr = fragment.rangeInElement
|
||||
let loc = tcm.offset(from: docStart, to: tr.location)
|
||||
let len = tcm.offset(from: tr.location, to: tr.endLocation)
|
||||
if NSIntersectionRange(NSRange(location: loc, length: len), docRange).length > 0 {
|
||||
frames.append(fragment.layoutFragmentFrame)
|
||||
}
|
||||
return true
|
||||
}
|
||||
return frames
|
||||
}
|
||||
guard let layoutManager, let container = textContainer else { return [] }
|
||||
let nsText = string as NSString
|
||||
var frames: [CGRect] = []
|
||||
var lineStart = docRange.location
|
||||
while lineStart < NSMaxRange(docRange) {
|
||||
let lineRange = nsText.lineRange(for: NSRange(location: lineStart, length: 0))
|
||||
let clamped = NSIntersectionRange(lineRange, docRange)
|
||||
guard clamped.length > 0 else { break }
|
||||
let glyphRange = layoutManager.glyphRange(forCharacterRange: clamped, actualCharacterRange: nil)
|
||||
frames.append(layoutManager.boundingRect(forGlyphRange: glyphRange, in: container))
|
||||
lineStart = NSMaxRange(lineRange)
|
||||
}
|
||||
return frames
|
||||
}
|
||||
|
||||
override func updateTrackingAreas() {
|
||||
super.updateTrackingAreas()
|
||||
if hoverTrackingArea == nil {
|
||||
let area = NSTrackingArea(
|
||||
rect: bounds, options: [.mouseMoved, .activeAlways, .inVisibleRect],
|
||||
owner: self, userInfo: nil,
|
||||
)
|
||||
addTrackingArea(area)
|
||||
hoverTrackingArea = area
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Click discrimination (#68)
|
||||
|
||||
override func mouseDown(with event: NSEvent) {
|
||||
let point = convert(event.locationInWindow, from: nil)
|
||||
if event.modifierFlags.contains(.command) {
|
||||
let index = characterIndex(for: point)
|
||||
if index != NSNotFound, let url = textStorage?.attribute(.link, at: index, effectiveRange: nil) as? URL {
|
||||
NSWorkspace.shared.open(url)
|
||||
// Allow our own loadHTMLString main-frame load (about:blank); a
|
||||
// blanket .cancel would kill the page before it paints. Everything
|
||||
// else is cancelled — reading never navigates in-app (#74 lesson).
|
||||
func webView(
|
||||
_ wv: WKWebView,
|
||||
decidePolicyFor nav: WKNavigationAction,
|
||||
decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void
|
||||
) {
|
||||
if nav.targetFrame?.isMainFrame == true,
|
||||
let u = nav.request.url, u.scheme == "file" || u.absoluteString == "about:blank" {
|
||||
decisionHandler(.allow)
|
||||
return
|
||||
}
|
||||
decisionHandler(.cancel)
|
||||
}
|
||||
super.mouseDown(with: event)
|
||||
// NSTextView's mouseDown consumes the mouse-up in its own tracking
|
||||
// loop — the click is complete once super returns. Tap = single
|
||||
// click, no drag, no selection formed (#68: drag-select never
|
||||
// registers; triple-click paragraph select has length > 0).
|
||||
let upScreen = NSEvent.mouseLocation
|
||||
let upWindow = window.map { $0.convertFromScreen(NSRect(origin: upScreen, size: .zero)).origin }
|
||||
?? event.locationInWindow
|
||||
let downWindow = event.locationInWindow
|
||||
let moved = hypot(upWindow.x - downWindow.x, upWindow.y - downWindow.y)
|
||||
guard event.clickCount == 1, moved < 4, selectedRange().length == 0 else { return }
|
||||
let index = characterIndex(for: point)
|
||||
guard index != NSNotFound, let bound = bound(containing: index) else { return }
|
||||
onEditIntent?(bound.sourceRange.location)
|
||||
}
|
||||
|
||||
// MARK: Scroll tracking (#68 flip-back mapping)
|
||||
// MARK: WKScriptMessageHandler — the source map in action
|
||||
|
||||
override func reflectScrolledClipView(_ clipView: NSClipView) {
|
||||
super.reflectScrolledClipView(clipView)
|
||||
let visible = NSPoint(x: 0, y: visibleRect.minY + 1)
|
||||
let index = characterIndex(for: visible)
|
||||
if index != NSNotFound, let bound = bound(containing: index) {
|
||||
stateBox?.topSourceLocation = bound.sourceRange.location
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Image hover popover (#69 floor)
|
||||
|
||||
override func mouseMoved(with event: NSEvent) {
|
||||
super.mouseMoved(with: event)
|
||||
let point = convert(event.locationInWindow, from: nil)
|
||||
let index = characterIndex(for: point)
|
||||
guard index != NSNotFound, let bound = bound(containing: index), let url = bound.imageURL else {
|
||||
popover?.close()
|
||||
popover = nil
|
||||
return
|
||||
}
|
||||
guard popover == nil else { return }
|
||||
let pop = NSPopover()
|
||||
pop.behavior = .transient
|
||||
pop.contentViewController = NSHostingController(rootView: ImagePopoverView(url: url))
|
||||
pop.contentSize = NSSize(width: 480, height: 360)
|
||||
pop.show(relativeTo: CGRect(origin: point, size: NSSize(width: 1, height: 1)), of: self, preferredEdge: .maxY)
|
||||
popover = pop
|
||||
}
|
||||
|
||||
override func mouseExited(with event: NSEvent) {
|
||||
super.mouseExited(with: event)
|
||||
popover?.close()
|
||||
popover = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// The hover popover's content: loads the image off-main, scaled to fit.
|
||||
private struct ImagePopoverView: View {
|
||||
let url: URL
|
||||
@State private var image: NSImage?
|
||||
|
||||
var body: some View {
|
||||
Group {
|
||||
if let image {
|
||||
Image(nsImage: image)
|
||||
.resizable()
|
||||
.scaledToFit()
|
||||
} else {
|
||||
ProgressView()
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: 480, maxHeight: 360)
|
||||
.task {
|
||||
// Data off-main (Sendable); NSImage decoded on-main.
|
||||
let data = await Task.detached(priority: .userInitiated) {
|
||||
try? Data(contentsOf: url)
|
||||
}.value
|
||||
if let data {
|
||||
image = NSImage(data: data)
|
||||
func userContentController(_ ucc: WKUserContentController, didReceive message: WKScriptMessage) {
|
||||
switch message.name {
|
||||
case "openLink":
|
||||
if let s = message.body as? String, let url = URL(string: s) { NSWorkspace.shared.open(url) }
|
||||
case "sourceClick", "sourceScroll":
|
||||
guard let s = message.body as? String, let line = Int(s),
|
||||
let block = blocks.first(where: { $0.sourceLine == line }) else { return }
|
||||
if message.name == "sourceClick" {
|
||||
onEditIntent?(block.sourceRange.location)
|
||||
} else {
|
||||
stateBox?.topSourceLocation = block.sourceRange.location
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Executable
BIN
Binary file not shown.
@@ -2,201 +2,172 @@
|
||||
// ReadingPresenterTests.swift
|
||||
// MuseionTests
|
||||
//
|
||||
// #71 (map #20): renderer coverage — the smallest checks that fail if the
|
||||
// block classification, auto-renumbering, source-range mapping, or inline
|
||||
// interpretation break. Kitchen-sink fixture strings inline (no file
|
||||
// fixtures per the suite's convention).
|
||||
// #76 (map #20, ADR-0011): apex HTML pipeline coverage — the smallest
|
||||
// checks that fail if the source map (chunker/stamper/blocks), the apex
|
||||
// invocation, or the page assembly break. Fixture strings inline (suite
|
||||
// convention); the pipeline tests run the real bundled apex binary.
|
||||
//
|
||||
|
||||
import AppKit
|
||||
import Foundation
|
||||
@testable import Museion
|
||||
import Testing
|
||||
|
||||
@MainActor
|
||||
struct ReadingPresenterTests {
|
||||
/// Blank-line split + heading fonting + markup hidden.
|
||||
// MARK: Source map
|
||||
|
||||
/// Chunker: sentinels before chunks, blank structure preserved (spike
|
||||
/// self-check fixture).
|
||||
@Test
|
||||
func `headings and paragraphs`() {
|
||||
let doc = ReadingPresenter.document(for: "# Title\n\nBody with _em_.\n\n### Deep", resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count == 3)
|
||||
let flat = doc.content.string
|
||||
#expect(!flat.contains("#"))
|
||||
#expect(flat.contains("Title"))
|
||||
#expect(flat.contains("Body with em."))
|
||||
func chunkerStampsSentinels() {
|
||||
let md = "# T\n\nA\n\nB\n1. x\n\n\nC"
|
||||
#expect(ReadingPresenter.stampSource(md) == "<!--S:1-->\n# T\n\n<!--S:3-->\nA\n\n<!--S:5-->\nB\n1. x\n\n<!--S:9-->\nC")
|
||||
}
|
||||
|
||||
/// Auto-renumbering: `1. 1. 1.` renders 1, 2, 3; source never rewritten.
|
||||
/// Stamper: sentinel → attribute on the following element; multi-digit.
|
||||
@Test
|
||||
func `ordered list auto renumbers`() {
|
||||
let src = "1. one\n1. two\n1. three"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count == 1)
|
||||
#expect(doc.content.string.contains("1. one"))
|
||||
#expect(doc.content.string.contains("2. two"))
|
||||
#expect(doc.content.string.contains("3. three"))
|
||||
#expect(!doc.content.string.contains("1. two"))
|
||||
func stamperRewritesAttributes() {
|
||||
let html = "<h1>T</h1>\n<!--S:1-->\n<p>A</p>\n<!--S:12-->\n<ul>\n<li>B</li>\n</ul>"
|
||||
#expect(ReadingPresenter.stampHTML(html) == "<h1>T</h1>\n<p data-source-line=\"1\">A</p>\n<ul data-source-line=\"12\">\n<li>B</li>\n</ul>")
|
||||
}
|
||||
|
||||
/// Nesting: deeper items indent further; mixed bullet/number nesting rides
|
||||
/// the same path.
|
||||
/// The #68 click→edit map: blocks are monotonic, lines are 1-based, and
|
||||
/// ranges point at the exact chunk offsets in the source.
|
||||
@Test
|
||||
func `list nesting`() {
|
||||
let src = "- top\n - nested\n- back"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count == 1)
|
||||
#expect(doc.content.string.contains("top"))
|
||||
#expect(doc.content.string.contains("nested"))
|
||||
}
|
||||
|
||||
/// The #68 click→edit map: block source ranges are monotonic and cover
|
||||
/// every block; a location mid-document maps to its containing block.
|
||||
@Test
|
||||
func `source ranges map blocks`() {
|
||||
func blocksMapChunks() {
|
||||
let src = "# A\n\nfirst para\n\n- l1\n- l2\n\nlast para"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count == 4)
|
||||
let locations = doc.bounds.map(\.sourceRange.location)
|
||||
#expect(locations == locations.sorted())
|
||||
// "last para" starts at its own chunk offset
|
||||
let blocks = ReadingPresenter.blocks(for: src)
|
||||
#expect(blocks.count == 4)
|
||||
#expect(blocks.map(\.sourceLine) == [1, 3, 5, 8])
|
||||
let nsSrc = src as NSString
|
||||
let expected = nsSrc.range(of: "last para").location
|
||||
#expect(doc.bounds[3].sourceRange.location == expected)
|
||||
#expect(blocks[3].sourceRange.location == nsSrc.range(of: "last para").location)
|
||||
#expect(blocks[0].sourceRange.location == 0)
|
||||
}
|
||||
|
||||
/// Tables render as a mono grid: decoration carries column offsets,
|
||||
/// header/body rows are padded columns of text.
|
||||
/// Blocks over CRLF and multi-blank separators stay monotonic.
|
||||
@Test
|
||||
func `table renders`() throws {
|
||||
let src = "| A | B |\n| --- | --- |\n| one | two |"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count == 1)
|
||||
let lines = doc.content.string.components(separatedBy: "\n")
|
||||
#expect(lines.count == 2)
|
||||
#expect(lines[0].contains("A"))
|
||||
#expect(lines[1].contains("one"))
|
||||
// alignment: same column starts across rows
|
||||
let colA0 = try lines[0].distance(from: lines[0].startIndex, to: #require(lines[0].firstIndex(of: "A")))
|
||||
let colA1 = try lines[1].distance(from: lines[1].startIndex, to: #require(lines[1].firstIndex(of: "o")))
|
||||
#expect(colA0 == colA1)
|
||||
guard case let .table(columns)? = doc.bounds[0].decoration else {
|
||||
Issue.record("expected table decoration")
|
||||
return
|
||||
}
|
||||
#expect(columns.count == 3) // two columns + closing edge
|
||||
func blocksSurviveBlankRuns() {
|
||||
let src = "one\n\n\n\n two"
|
||||
let blocks = ReadingPresenter.blocks(for: src)
|
||||
#expect(blocks.count == 2)
|
||||
#expect(blocks[0].sourceLine == 1)
|
||||
#expect(blocks[1].sourceLine == 5)
|
||||
}
|
||||
|
||||
/// Fenced code: mono face, markers hidden, content intact.
|
||||
// MARK: Pipeline (real apex binary)
|
||||
|
||||
/// Headings + paragraphs + inline marks render; markup never leaks.
|
||||
@Test
|
||||
func `fenced code`() {
|
||||
let src = "```swift\nlet x = 1\n```"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(!doc.content.string.contains("```"))
|
||||
#expect(doc.content.string.contains("let x = 1"))
|
||||
let attrs = doc.content.attributes(at: 0, effectiveRange: nil)
|
||||
#expect((attrs[.font] as? NSFont)?.fontName == ProseTypography.codeFont.fontName)
|
||||
func pipelineHeadingsAndInline() throws {
|
||||
let (html, blocks) = ReadingPresenter.page(for: "# Title\n\nBody with _em_ and `code`.", postFolder: nil)
|
||||
try assertRendered(html, blocks: blocks, count: 2)
|
||||
#expect(html.contains("<h1 data-source-line=\"1\""))
|
||||
#expect(html.contains("<em>em</em>"))
|
||||
#expect(html.contains("<code>code</code>"))
|
||||
#expect(!html.contains("_em_"))
|
||||
}
|
||||
|
||||
/// Blockquote: markers hidden, quote decoration on the bound.
|
||||
/// `1. 1. 1.` renumbers via native <ol> (the #69 hard requirement).
|
||||
@Test
|
||||
func blockquote() {
|
||||
let src = "> quoted _words_\n>> deeper"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(!doc.content.string.contains(">"))
|
||||
#expect(doc.content.string.contains("quoted words"))
|
||||
guard case .quote? = doc.bounds[0].decoration else {
|
||||
Issue.record("expected quote decoration")
|
||||
return
|
||||
}
|
||||
func pipelineOrderedRenumber() throws {
|
||||
let src = "1. one\n1. two\n1. three"
|
||||
let (html, blocks) = ReadingPresenter.page(for: src, postFolder: nil)
|
||||
try assertRendered(html, blocks: blocks, count: 1)
|
||||
#expect(html.contains("<ol data-source-line=\"1\">"))
|
||||
#expect(html.contains("<li>one</li>"))
|
||||
#expect(html.contains("<li>two</li>"))
|
||||
#expect(html.contains("<li>three</li>"))
|
||||
#expect(!html.contains("1. one"))
|
||||
}
|
||||
|
||||
/// Links styled + attribute retained (⌘-click opens).
|
||||
/// `--no-mixed-lists`: an ordered list after a bullet list stays two
|
||||
/// lists (default apex merges them — kills renumbering).
|
||||
@Test
|
||||
func `links retained`() {
|
||||
let src = "See [the docs](https://example.de) now"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
let range = (doc.content.string as NSString).range(of: "the docs")
|
||||
#expect(range.location != NSNotFound)
|
||||
let attrs = doc.content.attributes(at: range.location, effectiveRange: nil)
|
||||
#expect(attrs[.link] != nil)
|
||||
func pipelineMixedListsStaySplit() throws {
|
||||
let src = "- bullet\n- another\n\n1. one\n1. two"
|
||||
let (html, _) = ReadingPresenter.page(for: src, postFolder: nil)
|
||||
#expect(html.contains("<ul"))
|
||||
#expect(html.contains("<ol"))
|
||||
#expect(!html.contains("<li>one</li></ul>"))
|
||||
}
|
||||
|
||||
/// Images: hover payload carried on the bound, syntax stays text.
|
||||
/// Tables, quotes, fenced code, HR, links — the #69 set on one page.
|
||||
@Test
|
||||
func `image hover payload`() {
|
||||
let src = ""
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count == 1)
|
||||
#expect(doc.bounds[0].imageURL != nil)
|
||||
#expect(doc.content.string.contains("alt text"))
|
||||
}
|
||||
func pipelineConstructs() throws {
|
||||
let src = """
|
||||
| A | B |
|
||||
| --- | --- |
|
||||
| one | two |
|
||||
|
||||
/// Image URL resolution against the post folder (#71).
|
||||
@Test
|
||||
func `image URL resolves against post folder`() {
|
||||
let src = ""
|
||||
let folder = URL(fileURLWithPath: "/tmp/posts/example")
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: folder)
|
||||
#expect(doc.bounds[0].imageURL?.path == "/tmp/posts/example/assets/img.png")
|
||||
}
|
||||
|
||||
/// Footnotes are the one fallback: source text, no transformation.
|
||||
@Test
|
||||
func `footnotes stay fallback`() {
|
||||
let src = "Text with note[^1]\n\n[^1]: the note"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(doc.content.string.contains("[^1]"))
|
||||
}
|
||||
|
||||
/// HR: rule decoration, matcher shared with editing.
|
||||
@Test
|
||||
func `horizontal rule`() {
|
||||
let src = "above\n\n* * *\n\nbelow"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count == 3)
|
||||
guard case .rule? = doc.bounds[1].decoration else {
|
||||
Issue.record("expected rule decoration")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
/// Soft-joined lines: one paragraph, single spaces.
|
||||
@Test
|
||||
func `soft joined lines`() {
|
||||
let src = "line one\nline two"
|
||||
let doc = ReadingPresenter.document(for: src, resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count == 1)
|
||||
#expect(doc.content.string == "line one line two")
|
||||
}
|
||||
|
||||
/// Kitchen-sink smoke: every construct in one document without crashing.
|
||||
@Test
|
||||
func `kitchen sink renders`() {
|
||||
let sink = """
|
||||
# Sink
|
||||
|
||||
- bullet
|
||||
- another
|
||||
|
||||
1. one
|
||||
1. two
|
||||
|
||||
> quote
|
||||
> quoted
|
||||
|
||||
```txt
|
||||
code
|
||||
let x = 1
|
||||
```
|
||||
|
||||
| H |
|
||||
| --- |
|
||||
| c |
|
||||
|
||||

|
||||
|
||||
[link](https://x.de)
|
||||
See [the docs](https://example.net) now
|
||||
|
||||
* * *
|
||||
"""
|
||||
let doc = ReadingPresenter.document(for: sink, resolvingImagesIn: nil)
|
||||
#expect(doc.bounds.count >= 9)
|
||||
let (html, blocks) = ReadingPresenter.page(for: src, postFolder: nil)
|
||||
try assertRendered(html, blocks: blocks, count: 5)
|
||||
#expect(html.contains("<table data-source-line=\"1\">"))
|
||||
#expect(html.contains("<blockquote data-source-line=\"5\">"))
|
||||
#expect(html.contains("<pre"))
|
||||
#expect(html.contains("let x = 1"))
|
||||
#expect(!html.contains("```"))
|
||||
#expect(html.contains("<a href=\"https://example.net\">the docs</a>"))
|
||||
#expect(html.contains("<hr"))
|
||||
}
|
||||
|
||||
/// Images embed as base64 data URLs against the post folder (#69/#74).
|
||||
@Test
|
||||
func pipelineImageEmbeds() throws {
|
||||
let prose = URL(fileURLWithPath: #filePath) // …/MuseionTests/ReadingPresenterTests.swift
|
||||
.deletingLastPathComponent().deletingLastPathComponent()
|
||||
.appendingPathComponent("spike/prose")
|
||||
let src = ""
|
||||
let (html, blocks) = ReadingPresenter.page(for: src, postFolder: prose)
|
||||
try assertRendered(html, blocks: blocks, count: 1)
|
||||
#expect(html.contains("src=\"data:image/png;base64,"))
|
||||
}
|
||||
|
||||
/// Footnotes render natively (apex upgrade over #69's fallback).
|
||||
@Test
|
||||
func pipelineFootnotes() throws {
|
||||
let src = "Text with note[^1]\n\n[^1]: the note"
|
||||
let (html, _) = ReadingPresenter.page(for: src, postFolder: nil)
|
||||
#expect(html.contains("footnote"))
|
||||
#expect(html.contains("the note"))
|
||||
}
|
||||
|
||||
/// Fallback: apex failure → editing-treated source (#69 rule), escaped.
|
||||
@Test
|
||||
func fallbackIsSourceText() {
|
||||
let page = ReadingPresenter.fallbackPage("a < b & c > d")
|
||||
#expect(page.contains("<pre data-source-line=\"1\">a < b & c > d</pre>"))
|
||||
}
|
||||
|
||||
/// The stylesheet carries the live slot values as CSS variables.
|
||||
@Test
|
||||
func stylesheetCarriesSlots() {
|
||||
let css = ReadingPresenter.styleSheet()
|
||||
#expect(css.contains("--body-face:"))
|
||||
#expect(css.contains("--headings-size:"))
|
||||
#expect(css.contains("--code-face:"))
|
||||
#expect(css.contains("--lh:"))
|
||||
#expect(css.contains("[data-source-line]:hover"))
|
||||
}
|
||||
|
||||
private func assertRendered(_ html: String, blocks: [ReadingPresenter.Block], count: Int) throws {
|
||||
let stamped = try XCTRegexMatches(html, pattern: "data-source-line=\"\\d+\"")
|
||||
#expect(stamped == count)
|
||||
#expect(blocks.count == count)
|
||||
#expect(!html.contains("<!--S:"))
|
||||
}
|
||||
}
|
||||
|
||||
/// Regex count helper (Swift Testing has no XCTest import here).
|
||||
private func XCTRegexMatches(_ s: String, pattern: String) throws -> Int {
|
||||
let re = try NSRegularExpression(pattern: pattern)
|
||||
return re.numberOfMatches(in: s, range: NSRange(s.startIndex..., in: s))
|
||||
}
|
||||
Reference in new issue
Block a user