// // ProsePresenter.swift // Museion // // #19 (S1.2): line-based markdown presentation for the editor — lifted from // the proven spike (spike/textkit2, ADR-0010: ≤1.1 ms full-doc attribute load // on PERF-3k). Presentation-only: the plain `isRichText = false` store stays // the source of truth; attributes ride on top and re-apply per edited // paragraph. The Fix-Card anchor search stays with M2 (#25) — not lifted. // // #77: reading-parity rework — the editing surface now mirrors the calm-ruled // reading.css values (#78): leading 1.8-equivalent, heading ladder 30/22/19 // (h3) with h4+ flooring at bold body, half-height blank separators, quote // secondary ink + indent, fence interiors as mono code, dimmed list markers, // and real traits (bold/italic/code/link) on inline content. Marks stay // visible-dimmed everywhere — the plain store is the source of truth. // import AppKit /// Styled-source presentation (ADR-0010 mode B): pure functions over text; no /// AppKit view state. Colors mirror reading.css tokens in ProseTypography. nonisolated enum ProsePresenter { enum LineKind { case heading1, heading2, heading3, heading4Plus case quote case fence, fenceInterior case listMarker case syntaxOnly case blank case body } // MARK: Classification /// Context-free kind (no fence state) — headings/lists/quotes/rules/blank. static func lineKind(_ line: String) -> LineKind { classify(line, inFence: false) } /// A fence delimiter line (``` or ~~~ prefix) — delimiter lines are /// fences even inside a fence (they close it). static func isFenceDelimiter(_ trimmed: Substring) -> Bool { trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") } /// Pure rule/mark syntax (horizontal rules, dinkus) — no content. static func isRuleSyntax(_ trimmed: Substring) -> Bool { trimmed.allSatisfy { $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" } } /// CommonMark ATX heading level (1–6) of a trimmed line — a heading /// needs 1–6 hashes followed by a space or end-of-line; 7+ hashes or a /// glued-on word is body text. static func headingLevel(of trimmed: Substring) -> Int? { let hashes = trimmed.prefix(while: { $0 == "#" }).count guard hashes > 0, hashes <= 6 else { return nil } // CommonMark caps at 6; 7+ is body let after = trimmed.dropFirst(hashes) guard after.hasPrefix(" ") || after.isEmpty else { return nil } return hashes } /// Heading ladder for a valid ATX level — 1–3 are named steps, 4–6 /// share the h4+ rung (CommonMark). private static func headingKind(_ hashes: Int) -> LineKind { switch hashes { case 1: .heading1 case 2: .heading2 case 3: .heading3 default: .heading4Plus } } /// Delimiter lines are fences even inside a fence (they close it) — so the /// delim test runs before the inFence shortcut and `applyStyles` toggles /// on `kind == .fence` instead of re-deriving the prefix. static func classify(_ line: String, inFence: Bool) -> LineKind { let trimmed = line.drop(while: { $0 == " " || $0 == "\t" }) if trimmed.isEmpty { return .blank } if isFenceDelimiter(trimmed) { return .fence } if inFence { return .fenceInterior } if let hashes = headingLevel(of: trimmed) { return headingKind(hashes) } if trimmed.hasPrefix(">") { return .quote } if isRuleSyntax(trimmed) { return .syntaxOnly } if line.firstMatch(of: listMarkerPattern) != nil { return .listMarker } return .body } // MARK: Entry points /// Attribute a whole text (initial load). static func attribute(_ text: String) -> NSAttributedString { let out = NSMutableAttributedString(string: text, attributes: ProseTypography.bodyAttributes) let nsText = text as NSString applyStyles(out, range: NSRange(location: 0, length: nsText.length)) return out } /// Attribute one paragraph (editing-time re-apply). Cheap: the paragraph's /// lines plus a fence-state scan of the prefix. /// NOTE fence state crosses paragraphs: the coordinator (PostEditorView) /// compares the delimiter count per edit and routes to a full-document /// `attribute` pass when it moved — typing/deleting a ``` flips every line /// until the matching delimiter. static func reattribute(_ out: NSMutableAttributedString, paragraphRange: NSRange) { applyStyles(out, range: paragraphRange) } /// Number of fence delimiter lines (``` or ~~~ prefixes) — the cheap /// fingerprint the coordinator compares per edit. static func fenceDelimCount(_ text: String) -> Int { var count = 0 for line in text.split(separator: "\n", omittingEmptySubsequences: false) { let trimmed = line.drop(while: { $0 == " " || $0 == "\t" }) if isFenceDelimiter(trimmed) { count += 1 } } return count } // MARK: Styling pass private static func applyStyles(_ out: NSMutableAttributedString, range: NSRange) { let nsText = out.string as NSString guard range.length > 0, range.location >= 0 else { return } var inFence = false if range.location > 0, out.string.contains("```") || out.string.contains("~~~") { inFence = fenceState(nsText, upTo: range.location) } // Title detection (#ui-r1): the title is the document's FIRST // non-blank line (Post.scan's rule — blank lines above it are // skipped, so paragraph edits anchor past 0 and a location-0 test // would miss them). Absolute position match: whichever range is // styled, the line sitting at the title location takes the title // step; lines outside the range keep what the full pass gave them. let titleLocation = firstContentLocation(nsText) for line in contentLines(nsText, in: range) { let kind = classify(line.text, inFence: inFence) if kind == .fence { inFence.toggle() } let isTitle = titleLocation == line.content.location && kind == .body styleLine(out, line: line, kind: kind, isTitle: isTitle) } } private struct Line { let full: NSRange // content + terminator (blank lines attribute their terminator) let content: NSRange let text: String } /// Every line in `range` — including empty ones — as (full, content, text). private static func contentLines(_ nsText: NSString, in range: NSRange) -> [Line] { var lines: [Line] = [] var loc = range.location let end = NSMaxRange(range) while loc < end { let full = nsText.lineRange(for: NSRange(location: loc, length: 0)) var len = full.length while len > 0 { let char = nsText.character(at: full.location + len - 1) if char == 0x0A || char == 0x0D { len -= 1 } else { break } } let content = NSRange(location: full.location, length: len) lines.append(Line( full: full, content: content, text: len > 0 ? nsText.substring(with: content) : "", )) loc = NSMaxRange(full) } return lines } /// Count unclosed fences before `end` (``` or ~~~ delim lines toggle). private static func fenceState(_ nsText: NSString, upTo end: Int) -> Bool { var inFence = false let prefix = NSRange(location: 0, length: min(end, nsText.length)) for line in contentLines(nsText, in: prefix) where classify(line.text, inFence: inFence) == .fence { inFence.toggle() } return inFence } /// The #…​ ATX marker of a heading line, dimmed to the code face. private static func dimHeadingMarker(_ out: NSMutableAttributedString, line: Line) { let lead = line.text.prefix(while: { $0 == " " || $0 == "\t" }).utf16.count let hashes = line.text.dropFirst(lead).prefix(while: { $0 == "#" }).utf16.count let marker = NSRange(location: line.content.location + lead, length: min(hashes + 1, line.content.length - lead)) if marker.length > 0 { out.addAttributes(ProseTypography.codeAttributes, range: marker) } } /// Kinds whose text content carries inline trait styling (bold/italic/ /// code/link spans). static func carriesInlineTraits(_ kind: LineKind) -> Bool { kind == .body || kind == .quote || kind == .listMarker } /// Non-empty UTF-16 marker range of `pattern` at the line start, or nil. private static func markerRange(_ pattern: Regex, in line: Line) -> NSRange? { guard let marker = markerRangeUTF16(pattern, in: line.text), marker.length > 0 else { return nil } return marker } /// List marker dim + hanging indent: wrapped list lines align with the /// item's text, not the paragraph margin — the marker prefix (leading /// whitespace + "- "/"1. ") sets headIndent, mirroring reading.css's /// hanging lists (padding-left + outside markers; #ui-r1, sol#13; #ui-r2 /// argon#53 flush fix). Nested items hang at their own prefix width. /// The prefix is measured in the EXACT attributes it renders in /// (listMarkerAttributes — the line's face and size), so the /// continuation lands flush; a different measuring face drifts /// per-glyph (~4pt left in r1). ponytail: a tab in the prefix measures /// at the default tab stop; the corpus uses spaces — widen if tabbed /// lists drift. private static func applyListMarker(_ out: NSMutableAttributedString, line: Line) { guard let marker = markerRange(listMarkerPattern, in: line) else { return } out.addAttributes(ProseTypography.listMarkerAttributes, range: shifted(marker, into: line.content)) let prefix = String(line.text.prefix(NSMaxRange(marker))) let indent = NSAttributedString( string: prefix, attributes: ProseTypography.listMarkerAttributes, ).size().width let hanging = NSMutableParagraphStyle() hanging.setParagraphStyle(paragraph(.body)) hanging.headIndent = indent // #ui-r7 sol#29: inter-item rhythm (reading.css list margins) // — before-space only, the CSS block has no bottom margin. hanging.paragraphSpacingBefore = ProseTypography.listSpacingBefore out.addAttribute(.paragraphStyle, value: hanging, range: line.full) } private static func styleLine(_ out: NSMutableAttributedString, line: Line, kind: LineKind, isTitle: Bool = false) { guard line.full.length > 0 else { return } out.setAttributes(isTitle ? ProseTypography.titleAttributes : attributes(for: kind), range: line.full) let dim = ProseTypography.codeAttributes // codeFont + syntaxColor switch kind { case .heading1, .heading2, .heading3, .heading4Plus: dimHeadingMarker(out, line: line) case .quote: if let marker = markerRange(quoteMarkerPattern, in: line) { out.addAttributes(dim, range: shifted(marker, into: line.content)) } case .listMarker: applyListMarker(out, line: line) case .syntaxOnly: if line.content.length > 0 { out.addAttributes(dim, range: line.content) } case .fence: break // attributes(for: .fence) already carries codeFont + syntaxColor case .fenceInterior, .blank, .body: break } if carriesInlineTraits(kind) { styleInline(out, content: line.content, text: line.text) } } private static func shifted(_ marker: NSRange, into content: NSRange) -> NSRange { NSRange( location: content.location + marker.location, length: min(marker.length, max(0, content.length - marker.location)), ) } // MARK: Inline spans (bold / italic / code / links) // ponytail: Regex literals aren't Sendable; they're immutable de-facto. // No lookbehind in swift-regex — overlap-claim ordering + a manual // boundary check replace it. private nonisolated(unsafe) static let boldPattern = /\*\*[^*\n]+?\*\*/ private nonisolated(unsafe) static let emStarPattern = /\*[^*\n]+?\*/ private nonisolated(unsafe) static let emUnderPattern = /_[^_\n]+?_/ private nonisolated(unsafe) static let codePattern = /`[^`\n]+?`/ private nonisolated(unsafe) static let linkPattern = /\[[^\]\n]*\]\([^)\n]*\)/ /// Trait-style inline constructs. Marks dim; content gets real traits. /// Priority: code > link > bold > italic; later matches skip claimed /// spans (`claim` is the shared overlap gate, so each family's loop /// stays honest about the ones before it). private static func styleInline(_ out: NSMutableAttributedString, content: NSRange, text: String) { guard content.length > 0 else { return } var claimed: [Range] = [] styleCodeAndLinks(out, content: content, text: text, claimed: &claimed) styleEmphasis(out, content: content, text: text, claimed: &claimed) dimStraySyntax(out, content: content, text: text, claimed: &claimed) } /// Claim `span` unless an earlier (higher-priority) match overlaps it. private static func claim(_ claimed: inout [Range], _ span: Range) -> Bool { guard !claimed.contains(where: { $0.overlaps(span) }) else { return false } claimed.append(span) return true } /// Dim a utf16 span in the code face (marks, brackets, stray syntax). private static func dim(_ out: NSMutableAttributedString, content: NSRange, _ utf16: Range) { let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count) out.addAttributes(ProseTypography.codeAttributes, range: range) } /// Apply `attrs` to a utf16 span. private static func attr(_ out: NSMutableAttributedString, content: NSRange, _ utf16: Range, _ attrs: [NSAttributedString.Key: Any]) { let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count) out.addAttributes(attrs, range: range) } /// Inline code + links (priority 1–2). Code: marks + content in the code /// face, content at ink. Links: label ink + underline (CSS: ink text, /// muted rule); the brackets, ]( and the URL dim (reading hides them; /// dim is the editor's closest parity move). private static func styleCodeAndLinks( _ out: NSMutableAttributedString, content: NSRange, text: String, claimed: inout [Range], ) { let codeFont = ProseTypography.codeFont let ink: [NSAttributedString.Key: Any] = [.foregroundColor: ProseTypography.foregroundColor] let linkAttrs: [NSAttributedString.Key: Any] = [ .underlineStyle: NSUnderlineStyle.single.rawValue, .underlineColor: ProseTypography.mutedColor, ] // inline code — marks + content in the code face, content at ink for match in text.matches(of: codePattern) { let span = match.range.utf16Range(in: text) guard claim(&claimed, span) else { continue } dim(out, content: content, span.lowerBound ..< span.lowerBound + 1) dim(out, content: content, span.upperBound - 1 ..< span.upperBound) attr(out, content: content, span.lowerBound + 1 ..< span.upperBound - 1, [.font: codeFont].merging(ink) { _, new in new }) } for match in text.matches(of: linkPattern) { let span = match.range.utf16Range(in: text) guard claim(&claimed, span) else { continue } let whole = match.output // whole match (no capture groups) guard let sep = whole.firstRange(of: "](") else { continue } // sep indices are valid in text (Substring shares indices) let sepOffset = text.utf16.distance(from: text.utf16.startIndex, to: sep.lowerBound.samePosition(in: text.utf16)!) let label = span.lowerBound + 1 ..< sepOffset dim(out, content: content, span.lowerBound ..< span.lowerBound + 1) // [ attr(out, content: content, label, linkAttrs) dim(out, content: content, sepOffset ..< span.upperBound) // ](url) } } /// Bold + italic (priority 3–4). CommonMark: intraword `_` never /// emphasizes (file_name_here); intraword `*` does. No lookbehind in /// swift-regex, so boundary chars are checked by hand. private static func styleEmphasis( _ out: NSMutableAttributedString, content: NSRange, text: String, claimed: inout [Range], ) { let boldFont = ProseTypography.boldBodyFont let italicFont = ProseTypography.italicBodyFont for match in text.matches(of: boldPattern) { let span = match.range.utf16Range(in: text) guard claim(&claimed, span) else { continue } dim(out, content: content, span.lowerBound ..< span.lowerBound + 2) dim(out, content: content, span.upperBound - 2 ..< span.upperBound) attr(out, content: content, span.lowerBound + 2 ..< span.upperBound - 2, [.font: boldFont]) } for match in text.matches(of: emStarPattern) { let span = match.range.utf16Range(in: text) guard claim(&claimed, span) else { continue } let lo = charBefore(text, span.lowerBound) let hi = charAfter(text, span.upperBound) if isMarkAdjacent(lo, hi) { continue } dim(out, content: content, span.lowerBound ..< span.lowerBound + 1) dim(out, content: content, span.upperBound - 1 ..< span.upperBound) attr(out, content: content, span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont]) } for match in text.matches(of: emUnderPattern) { let span = match.range.utf16Range(in: text) guard claim(&claimed, span) else { continue } let lo = charBefore(text, span.lowerBound) let hi = charAfter(text, span.upperBound) if isMarkAdjacent(lo, hi) { continue } if isIntraword(lo, hi) { continue } dim(out, content: content, span.lowerBound ..< span.lowerBound + 1) dim(out, content: content, span.upperBound - 1 ..< span.upperBound) attr(out, content: content, span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont]) } } /// Fallback: dim stray syntax chars outside claimed spans. private static func dimStraySyntax( _ out: NSMutableAttributedString, content: NSRange, text: String, claimed: inout [Range], ) { let syntax = inlineSyntax for (offset, codeUnit) in text.utf16.enumerated() { guard let scalar = Unicode.Scalar(codeUnit).map({ Character($0) }), syntax.contains(scalar) else { continue } let unit = offset ..< offset + 1 if claimed.contains(where: { $0.overlaps(unit) }) { continue } dim(out, content: content, unit) } } /// True when the char at either boundary of an emphasis span is itself /// a mark (`**foo**`'s inner `*` is bold, not emphasis). private static func isMarkAdjacent(_ lo: Character?, _ hi: Character?) -> Bool { lo == "*" || hi == "*" || lo == "_" || hi == "_" } /// True when an `_…_` span sits inside a word (file_name_here never /// emphasizes). private static func isIntraword(_ lo: Character?, _ hi: Character?) -> Bool { lo?.isLetter == true || lo?.isNumber == true || hi?.isLetter == true || hi?.isNumber == true } // MARK: Base attributes static func attributes(for kind: LineKind) -> [NSAttributedString.Key: Any] { switch kind { case .heading1: [.font: ProseTypography.headingFont, .paragraphStyle: paragraph(.heading1)] case .heading2: [.font: ProseTypography.heading2Font, .paragraphStyle: paragraph(.heading2)] case .heading3: [.font: ProseTypography.heading3Font, .paragraphStyle: paragraph(.heading3)] case .heading4Plus: [.font: ProseTypography.headingBoldFont, .paragraphStyle: paragraph(.heading4Plus)] case .quote: [ .font: ProseTypography.bodyFont, .foregroundColor: ProseTypography.secondaryColor, .paragraphStyle: paragraph(.quote), ] case .fence: [ .font: ProseTypography.codeFont, .foregroundColor: ProseTypography.syntaxColor, .backgroundColor: ProseTypography.substrateColor, .paragraphStyle: paragraph(.fence), ] case .fenceInterior: [ .font: ProseTypography.codeFont, .foregroundColor: ProseTypography.foregroundColor, .backgroundColor: ProseTypography.substrateColor, .paragraphStyle: paragraph(.fenceInterior), ] case .listMarker, .syntaxOnly, .body: ProseTypography.bodyAttributes case .blank: [.font: ProseTypography.blankFont, .paragraphStyle: paragraph(.blank)] } } /// Paragraph spacing per line kind. Blank source lines are the separator /// (#77: at half height); spacing knobs stay 0 unless the visual check /// asks for more. static func paragraph(_ kind: LineKind) -> NSParagraphStyle { let style = NSMutableParagraphStyle() let font: NSFont let cssLineHeight: CGFloat switch kind { case .heading1, .heading2, .heading3, .heading4Plus: font = ProseTypography.headingFont cssLineHeight = 1.15 // CSS: h1–h6 line-height 1.15 case .fence, .fenceInterior: font = ProseTypography.codeFont cssLineHeight = 1.5 // CSS: pre line-height 1.5 case .blank: font = ProseTypography.blankFont cssLineHeight = 1.8 default: font = ProseTypography.bodyFont cssLineHeight = 1.8 // CSS: --lh 1.8 } style.lineHeightMultiple = ProseTypography.lineHeightMultiple(font: font, cssLineHeight: cssLineHeight) if kind == .quote { style.firstLineHeadIndent = 20 // CSS: blockquote padding-left 20px style.headIndent = 20 // wrapped quote lines align under the text } if kind == .heading1 || kind == .heading2 || kind == .heading3 || kind == .heading4Plus { // Reading parity: head-space-before 90 / after 30 MINUS the blank // separator line's own height (~15pt), which the editor shows and // reading collapses. Alexander ruled blank-only "a bit tight". style.paragraphSpacingBefore = 75 style.paragraphSpacing = 30 } return style } // MARK: Pattern helpers // Marker patterns (regex literals, like the inline ones below). // listMarkerPattern is internal — ProseList's marker math must agree // with classify()'s list detection (#115). nonisolated(unsafe) static let listMarkerPattern = /^\s*(?:[-*+]|\d{1,9}[.)])(?:\s+|$)/ private nonisolated(unsafe) static let quoteMarkerPattern = /^(?:\s*>(?:\s|$))*/ /// UTF-16 NSRange of the marker in `lineText`, or nil. private static func markerRangeUTF16(_ pattern: Regex, in lineText: String) -> NSRange? { guard let match = lineText.firstMatch(of: pattern) else { return nil } let utf16 = match.range.utf16Range(in: lineText) return NSRange(location: utf16.lowerBound, length: utf16.count) } /// Mark-boundary helpers (no lookbehind in swift-regex): the Character /// just before / just after a UTF-16 offset, or nil at the edges. private static func charBefore(_ text: String, _ offset: Int) -> Character? { guard offset > 0 else { return nil } let idx = text.utf16.index(text.utf16.startIndex, offsetBy: offset - 1, limitedBy: text.utf16.endIndex) ?? text.utf16.startIndex guard let scalar = Unicode.Scalar(text.utf16[idx]) else { return nil } return Character(scalar) } private static func charAfter(_ text: String, _ offset: Int) -> Character? { let idx = text.utf16.index(text.utf16.startIndex, offsetBy: offset, limitedBy: text.utf16.endIndex) ?? text.utf16.endIndex guard idx < text.utf16.endIndex, let scalar = Unicode.Scalar(text.utf16[idx]) else { return nil } return Character(scalar) } static let inlineSyntax: Set = ["*", "_", "`", "[", "]", "(", ")", "!", "<", ">"] } nonisolated extension Range { func utf16Range(in base: String) -> Range { let lo = base.utf16.distance(from: base.utf16.startIndex, to: lowerBound.samePosition(in: base.utf16)!) let hi = base.utf16.distance(from: base.utf16.startIndex, to: upperBound.samePosition(in: base.utf16)!) return lo ..< hi } } // MARK: - Title detection (#ui-r1 — file scope: the enum body sits at its ceiling) nonisolated extension ProsePresenter { /// UTF-16 start of the first non-blank line, or nil when the whole /// buffer is blank. Walks only the leading blank lines. Post.scan /// skips leading blanks to find the title; the editor styles the same /// line the library shows. static func firstContentLocation(_ nsText: NSString) -> Int? { var lineStart = 0 while lineStart < nsText.length { let line = nsText.lineRange(for: NSRange(location: lineStart, length: 0)) let lineText = nsText.substring(with: line) if !lineText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return line.location } lineStart = NSMaxRange(line) } return nil } }