diff --git a/Museion/ReadingPresenter.swift b/Museion/ReadingPresenter.swift index 020d12f..1ec0525 100644 --- a/Museion/ReadingPresenter.swift +++ b/Museion/ReadingPresenter.swift @@ -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 `` 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: 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 `![alt](url)` 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 `` (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("") + while i < lines.count && !isBlank(lines[i]) { out.append(String(lines[i])); i += 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 { + let re = try! NSRegularExpression(pattern: #"\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 `")) } - /// 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 = "![alt text](assets/img.png)" - 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 = "![x](assets/img.png)" - 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 | - - ![i](a.png) - - [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("")) + #expect(html.contains("
    ")) + #expect(html.contains("the docs")) + #expect(html.contains(" d") + #expect(page.contains("
    a < b & c > d
    ")) + } + + /// 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("