Files
museion/Museion/ProsePresenter.swift
T
AlexKucera 46441438a2 feat(editor): 66ch measure + heading spacing (#77 follow-up)
- editor text centers at reading.css --measure 66ch (zero-advance × 66
  + 2×24pt padding), scroll view still fills the column
- headings get paragraphSpacingBefore 75 / after 30 (CSS 90/30 minus
  the visible blank separator's ~15pt)
2026-10-08 13:51:07 +02:00

448 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)
}
static func classify(_ line: String, inFence: Bool) -> LineKind {
if inFence {
return .fenceInterior
}
let trimmed = line.drop(while: { $0 == " " || $0 == "\t" })
if trimmed.isEmpty {
return .blank
}
if trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~") {
return .fence
}
let hashes = trimmed.prefix(while: { $0 == "#" }).count
if hashes > 0 {
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 listMarkerRegex.firstMatch(in: line, range: NSRange(location: 0, length: (line as NSString).length)) != 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.
static func reattribute(_ out: NSMutableAttributedString, paragraphRange: NSRange) {
applyStyles(out, range: paragraphRange)
}
// 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 trimmed = line.text.drop(while: { $0 == " " || $0 == "\t" })
let isDelim = !line.text.isEmpty && !trimmed.isEmpty && (trimmed.hasPrefix("```") || trimmed.hasPrefix("~~~"))
let kind = isDelim ? LineKind.fence : classify(line.text, inFence: inFence)
if isDelim {
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
var loc = 0
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
}
}
if len > 0 {
let line = (nsText.substring(with: NSRange(location: full.location, length: len)) as String)
.drop(while: { $0 == " " || $0 == "\t" })
if line.hasPrefix("```") || line.hasPrefix("~~~") {
inFence.toggle()
}
}
loc = NSMaxRange(full)
}
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 == " " }).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 = markerRange(quoteMarkerRegex, in: line.text), marker.length > 0 {
out.addAttributes(dim, range: shifted(marker, into: line.content))
}
case .listMarker:
if let marker = markerRange(listMarkerRegex, in: line.text), marker.length > 0 {
out.addAttributes(dim, range: shifted(marker, into: line.content))
}
case .syntaxOnly, .fence:
if line.content.length > 0 {
out.addAttributes(dim, range: line.content)
}
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 var bodyFont: NSFont {
ProseTypography.bodyFont
}
static var bodyAttributes: [NSAttributedString.Key: Any] {
ProseTypography.bodyAttributes
}
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 dimming for quote / list lines — returns the marker's NSRange in
/// `line.text`, or nil.
// Static literal patterns — compile by construction.
// swiftlint:disable:next force_try
private static let listMarkerRegex = try! NSRegularExpression(pattern: #"^\s*(?:[-*+]|\d{1,9}[.)])(?:\s+|$)"#)
// swiftlint:disable:next force_try
private static let quoteMarkerRegex = try! NSRegularExpression(pattern: #"^(?:\s*>(?:\s|$))*"#)
private static func markerRange(_ regex: NSRegularExpression, in lineText: String) -> NSRange? {
regex.firstMatch(in: lineText, range: NSRange(location: 0, length: (lineText as NSString).length))?.range
}
/// 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 where Bound == 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
}
}