// // 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). // import AppKit /// Reading-mode presentation: text → rendered blocks. Pure over its input; /// called on the main actor (NSTextTable construction is MainActor). enum ReadingPresenter { /// One rendered block. `sourceRange` is the block's UTF-16 range in the /// source text (delimiter-exclusive) — the #68 click→edit map. struct Block { let content: NSAttributedString let sourceRange: NSRange /// Popover image URL for an `![alt](url)` chunk (#69 hover floor). let imageURL: URL? } /// 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? } /// 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) { if out.length > 0, !out.string.hasSuffix("\n") { out.append(NSAttributedString(string: "\n", attributes: ProseTypography.bodyAttributes)) } let start = out.length out.append(block.content) let image = block.imageURL.flatMap { raw -> URL? in guard raw.scheme == nil, let postFolder else { return raw } return postFolder.appendingPathComponent(raw.path) } bounds.append(Bound( docRange: NSRange(location: start, length: out.length - start), sourceRange: block.sourceRange, imageURL: image, )) } 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). static func blocks(for text: String) -> [Block] { var out: [Block] = [] let ns = text as NSString var loc = 0 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)) } loc = delim.location == NSNotFound ? ns.length : delim.location + 2 } return out } /// Classify one chunk and render it. private static func block(chunk: String, sourceRange: NSRange) -> Block { if let url = imageURL(in: chunk) { return Block(content: inlineParse(chunk), sourceRange: sourceRange, imageURL: url) } 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) } 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) } return Block(content: flowContent(lines, first: first), sourceRange: sourceRange, imageURL: nil) } // MARK: Flow blocks private static func flowContent(_ lines: [String], first: String) -> NSAttributedString { if let level = headingLevel(first) { let body = first.drop { $0 == "#" }.trimmingCharacters(in: .whitespaces) return headingContent(body, level: level) } if first.hasPrefix("```") { let inner = lines.dropFirst().dropLast(hasClosingFence(lines) ? 1 : 0) return codeContent(inner.joined(separator: "\n")) } if lines.count >= 2, isTableDelimiterRow(lines[1]), let table = tableContent(lines) { return table } // 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: " ") return inlineParse(joined) } 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.paragraphSpacing = level <= 2 ? 10 : 8 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.paragraphSpacing = 10 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 { let ps = NSMutableParagraphStyle() ps.textBlocks = [RuleTextBlock()] 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.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 { let out = NSMutableAttributedString() let quoteBlock = QuoteTextBlock() for (index, line) in lines.enumerated() { let depth = blockquoteDepth(line) let indent = CGFloat(6 + (depth - 1) * 18) let ps = NSMutableParagraphStyle() ps.textBlocks = [quoteBlock] 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: simple 1px-bordered NSTextTable; delimiter-row // alignment honored — cheap once the delimiter is parsed anyway) 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 table = NSTextTable() table.numberOfColumns = header.count table.collapsesBorders = true table.setBorderColor(ProseTypography.tableBorderColor) table.setWidth(1, type: .absolute, for: .border) let out = NSMutableAttributedString() var row = 0 for (index, line) in lines.enumerated() { if index == 1 { continue } // delimiter row let cells = tableCells(line) for column in 0 ..< header.count { let text = column < cells.count ? cells[column] : "" let cell = NSTextTableBlock( table: table, startingRow: row, rowSpan: 1, startingColumn: column, columnSpan: 1 ) cell.setWidth(1, type: .absolute, for: .border) let ps = NSMutableParagraphStyle() ps.textBlocks = [cell] ps.alignment = aligns[column] let attrs: [NSAttributedString.Key: Any] = [ .font: row == 0 ? ProseTypography.boldBodyFont : ProseTypography.bodyFont, .paragraphStyle: ps, .foregroundColor: ProseTypography.foregroundColor, ] out.append(NSAttributedString( string: text + (column == header.count - 1 ? "\n" : ""), attributes: attrs )) } row += 1 } return out } 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 } // 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("```") } /// `![alt](url)` → 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])) } } /// Hairline-left text block for blockquotes (#69). final nonisolated class QuoteTextBlock: NSTextBlock { override func drawBackground( withFrame frameRect: NSRect, in _: NSView?, characterRange _: NSRange, layoutManager _: NSLayoutManager, ) { let path = NSBezierPath() path.move(to: NSPoint(x: frameRect.minX + 2, y: frameRect.minY)) path.line(to: NSPoint(x: frameRect.minX + 2, y: frameRect.maxY)) path.lineWidth = 2 ProseTypography.quoteRuleColor.setStroke() path.stroke() } } /// Full-width hairline text block for horizontal rules (#69). final nonisolated class RuleTextBlock: NSTextBlock { override func drawBackground( withFrame frameRect: NSRect, in _: NSView?, characterRange _: NSRange, layoutManager _: NSLayoutManager, ) { let midY = frameRect.midY let path = NSBezierPath() path.move(to: NSPoint(x: frameRect.minX, y: midY)) path.line(to: NSPoint(x: frameRect.maxX, y: midY)) path.lineWidth = 1 ProseTypography.tableBorderColor.setStroke() path.stroke() } }