Files
museion/Museion/ProsePresenter.swift
T
AlexKucera a4ea914690
CI / ci (push) Canceled after 0s
style: swiftformat pass — drift from the format gate
Whole-tree swiftformat/swiftlint run during #136 flagged 9 files
drifted (/// doc markers on private members, one force-unwrap to
#require). Comment- and lint-only, no code change.
2026-10-27 18:32:30 +01:00

445 lines
17 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// 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)
}
/// 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 trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") {
return .fence
}
if inFence {
return .fenceInterior
}
let hashes = trimmed.prefix(while: { $0 == "#" }).count
if hashes > 0, hashes <= 6 { // CommonMark caps at 6; 7+ is body
let after = trimmed.dropFirst(hashes)
if after.hasPrefix(" ") || after.isEmpty {
switch hashes {
case 1: return .heading1
case 2: return .heading2
case 3: return .heading3
default: return .heading4Plus
}
}
}
if trimmed.hasPrefix(">") {
return .quote
}
if trimmed.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) {
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 trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") {
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)
}
for line in contentLines(nsText, in: range) {
let kind = classify(line.text, inFence: inFence)
if kind == .fence {
inFence.toggle()
}
styleLine(out, line: line, kind: kind)
}
}
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
for line in contentLines(nsText, in: NSRange(location: 0, length: min(end, nsText.length))) {
if classify(line.text, inFence: inFence) == .fence {
inFence.toggle()
}
}
return inFence
}
private static func styleLine(_ out: NSMutableAttributedString, line: Line, kind: LineKind) {
guard line.full.length > 0 else { return }
out.setAttributes(attributes(for: kind), range: line.full)
let dim = ProseTypography.codeAttributes // codeFont + syntaxColor
switch kind {
case .heading1, .heading2, .heading3, .heading4Plus:
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(dim, range: marker)
}
case .quote:
if let marker = markerRangeUTF16(quoteMarkerPattern, in: line.text), marker.length > 0 {
out.addAttributes(dim, range: shifted(marker, into: line.content))
}
case .listMarker:
if let marker = markerRangeUTF16(listMarkerPattern, in: line.text), marker.length > 0 {
out.addAttributes(dim, range: shifted(marker, into: line.content))
}
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 kind == .body || kind == .quote || kind == .listMarker {
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.
private static func styleInline(_ out: NSMutableAttributedString, content: NSRange, text: String) {
guard content.length > 0 else { return }
var claimed: [Range<Int>] = []
func claim(_ span: Range<Int>) -> Bool {
guard !claimed.contains(where: { $0.overlaps(span) }) else { return false }
claimed.append(span)
return true
}
func dim(_ utf16: Range<Int>) {
let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count)
out.addAttributes(ProseTypography.codeAttributes, range: range)
}
func attr(_ utf16: Range<Int>, _ attrs: [NSAttributedString.Key: Any]) {
let range = NSRange(location: content.location + utf16.lowerBound, length: utf16.count)
out.addAttributes(attrs, range: range)
}
let boldFont = ProseTypography.boldBodyFont
let italicFont = ProseTypography.italicBodyFont
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(span) else { continue }
dim(span.lowerBound ..< span.lowerBound + 1)
dim(span.upperBound - 1 ..< span.upperBound)
attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: codeFont].merging(ink) { _, new in new })
}
// 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).
for match in text.matches(of: linkPattern) {
let span = match.range.utf16Range(in: text)
guard claim(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(span.lowerBound ..< span.lowerBound + 1) // [
attr(label, linkAttrs)
dim(sepOffset ..< span.upperBound) // ](url)
}
// bold
for match in text.matches(of: boldPattern) {
let span = match.range.utf16Range(in: text)
guard claim(span) else { continue }
dim(span.lowerBound ..< span.lowerBound + 2)
dim(span.upperBound - 2 ..< span.upperBound)
attr(span.lowerBound + 2 ..< span.upperBound - 2, [.font: boldFont])
}
// italic — two forms. CommonMark: intraword `_` never emphasizes
// (file_name_here); intraword `*` does. No lookbehind in swift-regex,
// so boundary chars are checked by hand.
for match in text.matches(of: emStarPattern) {
let span = match.range.utf16Range(in: text)
guard claim(span) else { continue }
let lo = charBefore(text, span.lowerBound)
let hi = charAfter(text, span.upperBound)
if lo == "*" || hi == "*" || lo == "_" || hi == "_" {
continue
}
dim(span.lowerBound ..< span.lowerBound + 1)
dim(span.upperBound - 1 ..< span.upperBound)
attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont])
}
for match in text.matches(of: emUnderPattern) {
let span = match.range.utf16Range(in: text)
guard claim(span) else { continue }
let lo = charBefore(text, span.lowerBound)
let hi = charAfter(text, span.upperBound)
if lo == "*" || hi == "*" || lo == "_" || hi == "_" {
continue
}
if lo?.isLetter == true || lo?.isNumber == true || hi?.isLetter == true || hi?.isNumber == true {
continue
}
dim(span.lowerBound ..< span.lowerBound + 1)
dim(span.upperBound - 1 ..< span.upperBound)
attr(span.lowerBound + 1 ..< span.upperBound - 1, [.font: italicFont])
}
// fallback: dim stray syntax chars outside claimed spans
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(unit)
}
}
// 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<Substring>, 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<Character> = ["*", "_", "`", "[", "]", "(", ")", "!", "<", ">"]
}
nonisolated extension Range<String.Index> {
func utf16Range(in base: String) -> Range<Int> {
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
}
}