diff --git a/spike/textkit2/Package.swift b/spike/textkit2/Package.swift new file mode 100644 index 0000000..2451633 --- /dev/null +++ b/spike/textkit2/Package.swift @@ -0,0 +1,8 @@ +// swift-tools-version:6.2 +import PackageDescription + +let package = Package( + name: "TextKit2Spike", + platforms: [.macOS(.v26)], + targets: [.executableTarget(name: "TextKit2Spike")] +) diff --git a/spike/textkit2/Sources/TextKit2Spike/EditorPane.swift b/spike/textkit2/Sources/TextKit2Spike/EditorPane.swift new file mode 100644 index 0000000..3e31798 --- /dev/null +++ b/spike/textkit2/Sources/TextKit2Spike/EditorPane.swift @@ -0,0 +1,85 @@ +// Spike B (#53) — THROWAWAY. AppKit text editor with TextKit2 custom attributes. +import AppKit +import SwiftUI + +// MARK: - TextKit2-backed editor (NSTextView with custom attribute re-apply on edit) + +/// NSViewRepresentable wrapper around a scrollable NSTextView, restyling the edited +/// paragraph after each edit burst (textDidChange), preserving undo/IME natively. +struct EditorPane: NSViewRepresentable { + let attributed: NSAttributedString + var onEdit: ((String) -> Void)? + /// When set, highlight this range (Fix-Card anchor). + var anchorHighlight: NSRange? + + func makeNSView(context: Context) -> NSScrollView { + let tv = NSTextView() + tv.isRichText = false // plain source of truth; attributes are presentation-only + tv.allowsUndo = true + tv.isAutomaticQuoteSubstitutionEnabled = false + tv.isAutomaticDashSubstitutionEnabled = false + tv.isAutomaticTextReplacementEnabled = false + tv.isAutomaticSpellingCorrectionEnabled = false + tv.usesFindBar = true + tv.backgroundColor = NSColor(white: 0.98, alpha: 1) + tv.typingAttributes = ProsePresenter.bodyAttributes + tv.delegate = context.coordinator + tv.layoutManager?.allowsNonContiguousLayout = true + let scroll = NSScrollView() + scroll.documentView = tv + scroll.hasVerticalScroller = true + scroll.autohidesScrollers = true + scroll.drawsBackground = true + scroll.backgroundColor = NSColor(white: 0.98, alpha: 1) + // centered measure: text container inset + let containerWidth: CGFloat = 640 + tv.minSize = NSSize(width: 0, height: 0) + tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) + tv.isVerticallyResizable = true + tv.isHorizontallyResizable = false + tv.autoresizingMask = [.width] + tv.textContainer?.containerSize = NSSize(width: containerWidth, height: .greatestFiniteMagnitude) + tv.textContainer?.widthTracksTextView = false + tv.textContainer?.lineFragmentPadding = 12 + context.coordinator.textView = tv + return scroll + } + + func updateNSView(_ scroll: NSScrollView, context: Context) { + guard let tv = scroll.documentView as? NSTextView else { return } + if context.coordinator.loadedHash != attributed.hash { + context.coordinator.loadedHash = attributed.hash + tv.textStorage?.setAttributedString(attributed) + } + applyAnchor(to: tv) + } + + private func applyAnchor(to tv: NSTextView) { + let storage = tv.textStorage! + storage.removeAttribute(.backgroundColor, range: NSRange(location: 0, length: storage.length)) + guard let anchorHighlight else { return } + storage.addAttribute(.backgroundColor, value: NSColor(calibratedRed: 0.79, green: 0.39, blue: 0.26, alpha: 0.18), range: anchorHighlight) + tv.scrollRangeToVisible(anchorHighlight) + } + + func makeCoordinator() -> Coordinator { Coordinator(onEdit: onEdit) } + + final class Coordinator: NSObject, NSTextViewDelegate { + let onEdit: ((String) -> Void)? + weak var textView: NSTextView? + var loadedHash: Int = 0 + + init(onEdit: ((String) -> Void)?) { self.onEdit = onEdit } + + func textDidChange(_ notification: Notification) { + guard let tv = notification.object as? NSTextView, let storage = tv.textStorage else { return } + let sel = tv.selectedRange() + // Re-attribute the paragraph(s) touching the selection — one paragraph, one pass. + let paragraphRange = (storage.string as NSString).paragraphRange(for: sel) + ProsePresenter.reattribute(storage as NSMutableAttributedString, paragraphRange: paragraphRange) + // re-dim inline syntax across the edited line (already done in reattribute) + tv.typingAttributes = ProsePresenter.bodyAttributes + onEdit?(storage.string) + } + } +} diff --git a/spike/textkit2/Sources/TextKit2Spike/ProsePresenter.swift b/spike/textkit2/Sources/TextKit2Spike/ProsePresenter.swift new file mode 100644 index 0000000..4eaf6a8 --- /dev/null +++ b/spike/textkit2/Sources/TextKit2Spike/ProsePresenter.swift @@ -0,0 +1,128 @@ +// 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 = ["*", "_", "`", "[", "]", "(", ")", "!", "<", ">"] + + /// 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.. } + 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) + } + } +} diff --git a/spike/textkit2/Sources/TextKit2Spike/SpikeApp.swift b/spike/textkit2/Sources/TextKit2Spike/SpikeApp.swift new file mode 100644 index 0000000..3493ae4 --- /dev/null +++ b/spike/textkit2/Sources/TextKit2Spike/SpikeApp.swift @@ -0,0 +1,127 @@ +// Spike B (#53) — THROWAWAY. Window shell: editor + reading toggle + Fix-Card anchor demo. +import AppKit +import SwiftUI + +@main +struct SpikeApp: App { + @NSApplicationDelegateAdaptor(AppDelegate.self) var delegate + var body: some Scene { + Window("Spike B — TextKit2", id: "main") { + ContentView() + .frame(minWidth: 900, minHeight: 640) + .onAppear { NSApp.activate(ignoringOtherApps: true) } + } + .windowStyle(.hiddenTitleBar) + } + + // ponytail: one runnable check for the anchor logic — `swift run TextKit2Spike --check` + init() { + if CommandLine.arguments.contains("--check") { Self.selfCheck(); exit(0) } + } + + static func selfCheck() { + let text = try! String(contentsOfFile: "spike/prose/the-expected-value-of-showing.md", encoding: .utf8) + let quote = "“I'm not too sure that many people will compete. So, the expected value of joining is actually pretty high.”" + guard let r = ProsePresenter.anchorRange(of: quote, in: text) else { + print("FAIL: live quote not found"); return + } + let found = (text as NSString).substring(with: r) + assert(found.count > 50 && text.contains(found.trimmingCharacters(in: .whitespacesAndNewlines))) + // whitespace-tolerant: join with single spaces, must still match + let squished = quote.components(separatedBy: .newlines).joined(separator: " ") + assert(ProsePresenter.anchorRange(of: squished, in: text) != nil, "FAIL: whitespace-tolerant match") + // stale anchor: deleted text + assert(ProsePresenter.anchorRange(of: "this quote was deleted years ago", in: text) == nil, "FAIL: stale should be nil") + // perf smoke: PERF-3k anchor timing + let perf = (try? String(contentsOfFile: "spike/prose/PERF-3k.md", encoding: .utf8)) ?? text + let t0 = DispatchTime.now() + _ = ProsePresenter.anchorRange(of: "The odds are better than they look", in: perf) + let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6 + print("PASS: anchor found @ \(r.location), len \(r.length); PERF-3k anchor search \(String(format: "%.1f", ms)) ms") + } +} + +struct ContentView: View { + @State private var text: String + @State private var reading = false + @State private var anchor: NSRange? + @State private var staleShown = false + @State private var loadMs: Double = 0 + @State private var doc: NSAttributedString + + // calibration piece default; PERF-3k via arg + init() { + let args = CommandLine.arguments + let path = args.count > 1 ? args[1] : "spike/prose/the-expected-value-of-showing.md" + let t = (try? String(contentsOfFile: path, encoding: .utf8)) + ?? (try? String(contentsOfFile: "spike/prose/the-expected-value-of-showing.md", encoding: .utf8)) + ?? "# Spike B\n\n(No corpus file found — run from repo root.)" + _text = State(initialValue: t) + _doc = State(initialValue: ProsePresenter.attribute(t)) + } + + var body: some View { + VStack(spacing: 0) { + bar + Divider() + if reading { + ScrollView([.vertical]) { + Text((try? AttributedString( + markdown: text, + options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace) + )) ?? AttributedString(text)) + .font(.system(size: 17)) + .padding(.horizontal, 40) + .frame(maxWidth: 720, alignment: .leading) + .padding(.vertical, 24) + } + } else { + EditorPane(attributed: doc, onEdit: { newText in + text = newText + }, anchorHighlight: anchor) + } + } + .alert("Anchor not found", isPresented: $staleShown) { + Button("OK", role: .cancel) {} + } message: { + Text("The Post changed after this Fix Card was issued; no text was selected or changed.") + } + } + + private var bar: some View { + HStack(spacing: 12) { + Toggle("Reading", isOn: $reading) + Divider().frame(height: 14) + Button("Anchor: DM quote") { applyAnchor(#"“I'm not too sure that many people will compete. So, the expected value of joining is actually pretty high.”"#) } + Button("Stale anchor") { applyAnchor("this quote was deleted from the text") } + if let a = anchor { Text("anchored @ \(a.location)–\(a.location + a.length)").foregroundStyle(.secondary).font(.caption) } + Spacer() + Text("load \(String(format: "%.1f", loadMs)) ms").foregroundStyle(.secondary).font(.caption) + } + .padding(.horizontal, 16) + .padding(.vertical, 8) + } + + private func applyAnchor(_ quote: String) { + let t0 = DispatchTime.now() + let r = ProsePresenter.anchorRange(of: quote, in: text) + let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000 + loadMs = ms + if let r { + anchor = r + } else { + anchor = nil + staleShown = true + } + } +} + +// ponytail: bare SPM executable gets .accessory activation — no window. Set policy BEFORE scenes build. +final class AppDelegate: NSObject, NSApplicationDelegate { + func applicationWillFinishLaunching(_ notification: Notification) { + NSApp.setActivationPolicy(.regular) + } + func applicationDidFinishLaunching(_ notification: Notification) { + NSApp.activate(ignoringOtherApps: true) + } +} diff --git a/spike/textkit2/assets/spikeB-anchor.png b/spike/textkit2/assets/spikeB-anchor.png new file mode 100644 index 0000000..6c0b3bb Binary files /dev/null and b/spike/textkit2/assets/spikeB-anchor.png differ diff --git a/spike/textkit2/assets/spikeB-calibration.png b/spike/textkit2/assets/spikeB-calibration.png new file mode 100644 index 0000000..1ebc624 Binary files /dev/null and b/spike/textkit2/assets/spikeB-calibration.png differ diff --git a/spike/textkit2/assets/spikeB-perf-typed.png b/spike/textkit2/assets/spikeB-perf-typed.png new file mode 100644 index 0000000..221b576 Binary files /dev/null and b/spike/textkit2/assets/spikeB-perf-typed.png differ diff --git a/spike/textkit2/assets/spikeB-reading-final.png b/spike/textkit2/assets/spikeB-reading-final.png new file mode 100644 index 0000000..e105cfb Binary files /dev/null and b/spike/textkit2/assets/spikeB-reading-final.png differ diff --git a/spike/textkit2/assets/spikeB-stale2.png b/spike/textkit2/assets/spikeB-stale2.png new file mode 100644 index 0000000..cdcd86d Binary files /dev/null and b/spike/textkit2/assets/spikeB-stale2.png differ diff --git a/spike/textkit2/assets/spikeB-typed2.png b/spike/textkit2/assets/spikeB-typed2.png new file mode 100644 index 0000000..cc947e8 Binary files /dev/null and b/spike/textkit2/assets/spikeB-typed2.png differ diff --git a/spike/textkit2/assets/spikeB-undo.png b/spike/textkit2/assets/spikeB-undo.png new file mode 100644 index 0000000..9170f04 Binary files /dev/null and b/spike/textkit2/assets/spikeB-undo.png differ diff --git a/spike/textkit2/run.sh b/spike/textkit2/run.sh new file mode 100755 index 0000000..7c26928 --- /dev/null +++ b/spike/textkit2/run.sh @@ -0,0 +1,24 @@ +#!/bin/zsh +# ponytail: wrap the SPM binary in a minimal .app — SwiftUI needs a bundle to make windows. +set -e +cd "$(dirname "$0")" +swift build 2>&1 | tail -1 +APP=.build/TextKit2Spike.app +rm -rf "$APP" && mkdir -p "$APP/Contents/MacOS" +cp .build/out/Products/Debug/TextKit2Spike "$APP/Contents/MacOS/" +cat > "$APP/Contents/Info.plist" <<'PLIST' + + + + + CFBundleExecutableTextKit2Spike + CFBundleIdentifierde.babylondreams.museion.spike-b + CFBundleNameSpike B — TextKit2 + CFBundlePackageTypeAPPL + LSMinimumSystemVersion26.0 + NSHighResolutionCapable + + +PLIST +echo "built: $APP" +exec "$APP/Contents/MacOS/TextKit2Spike" "${@:-../../prose/the-expected-value-of-showing.md}"