Files
museion/spike/textkit2/Sources/TextKit2Spike/ProsePresenter.swift
T
AlexKucera dd3542a720
CI / ci (push) Canceled after 0s
spike(textkit2): Spike B — NSTextView/TextKit2 custom-attribute prose editor (#53)
- ProsePresenter: line-kind markdown→attributes (serif body 17pt, H1/H2/H3 26/21/18pt bold, dimmed mono syntax, paragraph spacing), whitespace-tolerant quote-anchor search
- EditorPane: NSViewRepresentable NSTextView, per-paragraph reattribute on edit, undo, non-contiguous layout, 640pt measure
- SpikeApp: Reading toggle (inline md render), anchor/stale-anchor demo, exact web-proto alert wording, --check self-test
- run.sh wraps SPM binary in .app (bare executables show no windows)
- assets/: verification screenshots

Wayfinder map #16 — throwaway spike, not for main.
2026-09-30 13:18:00 +02:00

129 lines
6.5 KiB
Swift

// Spike B (#53): NSTextView/TextKit2 with custom attributes — THROWAWAY, answers a question, not product code.
// Question: what does TextKit2 + custom attributes cost and buy for calm prose editing (mode B)?
// Run: swift run --package-path spike/textkit2 (from repo root, branch spike/editor-presentation)
import AppKit
// MARK: - Markdown presentation (the lift-if-it-wins module)
/// Line-based markdown presenter for prose: dimmed syntax, heading scale, paragraph spacing.
/// Pure functions over text; no AppKit state. Applied post-load and re-applied per edited paragraph.
nonisolated enum ProsePresenter {
enum LineKind { case heading1, heading2, quote, syntaxOnly, body }
static func lineKind(_ line: String) -> LineKind {
let t = line.drop(while: { $0 == " " })
if t.hasPrefix("## ") { return .heading2 }
if t.hasPrefix("# ") { return .heading1 }
if t.hasPrefix("> ") { return .quote }
if !t.isEmpty && t.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) { return .syntaxOnly }
return .body
}
static let inlineSyntax: Set<Character> = ["*", "_", "`", "[", "]", "(", ")", "!", "<", ">"]
/// Paragraph spacing + font for a line kind, applied via NSParagraphStyle.
static func paragraph(_ kind: LineKind) -> NSParagraphStyle {
let p = NSMutableParagraphStyle()
switch kind {
case .heading1: p.paragraphSpacing = 18; p.paragraphSpacingBefore = 26
case .heading2: p.paragraphSpacing = 12; p.paragraphSpacingBefore = 20
case .quote: p.paragraphSpacing = 10; p.paragraphSpacingBefore = 10
case .syntaxOnly, .body: p.paragraphSpacing = 10
}
return p
}
/// Attribute a whole text (initial load). Headings/body/quote styling + dimmed inline syntax.
static func attribute(_ text: String) -> NSAttributedString {
let out = NSMutableAttributedString(string: text, attributes: bodyAttributes)
let ns = text as NSString
ns.enumerateSubstrings(in: NSRange(location: 0, length: ns.length), options: [.byLines]) { line, range, _, _ in
guard let line else { return }
let kind = lineKind(line)
out.setAttributes(Self.attributes(for: kind), range: range)
dimSyntax(in: out, range: range)
}
return out
}
/// Attribute one paragraph (editing-time re-apply). Cheap: one line, one pass.
static func reattribute(_ out: NSMutableAttributedString, paragraphRange: NSRange) {
let line = (out.string as NSString).substring(with: paragraphRange)
let kind = lineKind(line)
out.setAttributes(Self.attributes(for: kind), range: paragraphRange)
dimSyntax(in: out, range: paragraphRange)
}
// Typography: system serif for prose (New York), 17pt body, scaled headings — the web proto's Iowan/Charter stance.
static var serif: NSFont { NSFont.systemFont(ofSize: 17, weight: .regular, width: .compressed) }
static var bodyFont: NSFont { NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17)
?? NSFont.systemFont(ofSize: 17) }
static var bodyAttributes: [NSAttributedString.Key: Any] { [
.font: bodyFont, .paragraphStyle: paragraph(.body), .foregroundColor: NSColor(red: 0.10, green: 0.10, blue: 0.09, alpha: 1),
] }
static func attributes(for kind: LineKind) -> [NSAttributedString.Key: Any] {
switch kind {
case .heading1: [.font: NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [.boldFontMask], weight: 9, size: 26) ?? .boldSystemFont(ofSize: 26), .paragraphStyle: paragraph(.heading1)]
case .heading2: [.font: NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [.boldFontMask], weight: 8, size: 20) ?? .boldSystemFont(ofSize: 20), .paragraphStyle: paragraph(.heading2)]
case .quote: bodyAttributes
case .syntaxOnly, .body: bodyAttributes
}
}
/// Dim markdown syntax characters within a line range (marker prefixes + inline marks).
static func dimSyntax(in out: NSMutableAttributedString, range: NSRange) {
let ns = out.string as NSString
guard range.length > 0 else { return }
let line = ns.substring(with: range)
let kind = lineKind(line)
// prefix markers
let markerLen: Int
switch kind {
case .heading1: markerLen = 2
case .heading2: markerLen = 3
case .quote: markerLen = 2
default: markerLen = 0
}
let dim: [NSAttributedString.Key: Any] = [.foregroundColor: NSColor(white: 0.55, alpha: 1), .font: NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)]
if markerLen > 0 { out.addAttributes(dim, range: NSRange(location: range.location, length: min(markerLen, range.length))) }
// inline marks in body/quote
if kind == .body || kind == .quote {
for (offset, ch) in line.utf16.enumerated() {
if let c = Unicode.Scalar(ch).map({ Character($0) }), inlineSyntax.contains(c) {
out.addAttributes(dim, range: NSRange(location: range.location + offset, length: 1))
}
}
}
}
// MARK: Quote anchor (Fix-Card feasibility note for the ADR)
/// Word-tokenized, whitespace/punctuation-tolerant search for `quote` in `text`.
/// Returns nil when not found — the stale-anchor case. O(n·m) worst case, fine at 3k words.
static func anchorRange(of quote: String, in text: String) -> NSRange? {
let textWords = words(text)
let quoteWords = words(quote)
guard !quoteWords.isEmpty, textWords.count >= quoteWords.count else { return nil }
for start in 0...(textWords.count - quoteWords.count) {
if (start..<start + quoteWords.count).allSatisfy({ textWords[$0].norm == quoteWords[$0 - start].norm }) {
let from = textWords[start].range.lowerBound
let to = textWords[start + quoteWords.count - 1].range.upperBound
let loc = text.utf16.distance(from: text.startIndex, to: from)
let len = text.utf16.distance(from: from, to: to)
return NSRange(location: loc, length: len)
}
}
return nil
}
private struct Word { let norm: String; let range: Range<String.Index> }
private static func words(_ s: String) -> [Word] {
s.split(whereSeparator: \.isWhitespace).map { sub in
Word(norm: sub.lowercased().trimmingCharacters(in: .punctuationCharacters), range: sub.startIndex ..< sub.endIndex)
}
}
}