Files
museion/spike/textkit2/Sources/TextKit2Spike/SpikeApp.swift
T
AlexKucera d722820fc8 chore: swiftformat drift + xcode 27 settings leftovers
Format-only pass over spikes, the gate prototype, and three app
files (brace style, wrapping — no semantic change), plus the 4-line
pbxproj alignment finishing the Xcode 27 settings pass (test-target
deployment target parity with 8e70f69).

[Generated by AI]
2026-10-16 14:49:26 +02:00

154 lines
5.8 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.
// 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")
// reading blocks: heading detected, markup hidden
let blocks = SpikeApp.readingBlocks(text)
assert(String(blocks[0].text.characters).hasPrefix("The expected value"), "FAIL: H1 block")
assert(blocks.allSatisfy { !String($0.text.characters).contains("#") }, "FAIL: markup leaked into reading view")
// 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")
}
// ponytail: blank-line split + inline parse per block; no AST. Setext/list blocks not handled — corpus has none.
static func readingBlocks(_ md: String) -> [(level: Int, text: AttributedString)] {
md.components(separatedBy: "\n\n").map { para in
var level = 0, p = para.trimmingCharacters(in: .whitespacesAndNewlines)
if p.hasPrefix("#") {
let hashes = p.prefix { $0 == "#" }.count
p = String(p.dropFirst(hashes)).trimmingCharacters(in: .whitespaces)
level = hashes
}
let attr = (try? AttributedString(markdown: p)) ?? AttributedString(p)
return (level, attr)
}
}
}
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]) {
VStack(alignment: .leading, spacing: 14) {
ForEach(Array(SpikeApp.readingBlocks(text).enumerated()), id: \.offset) { _, block in
Text(block.text)
.font(block.level > 0
? .system(size: CGFloat(32 - block.level * 3), weight: .bold, design: .serif)
: .system(size: 17))
}
}
.frame(maxWidth: 720, alignment: .leading)
.padding(.horizontal, 40)
.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) {
NSApp.setActivationPolicy(.regular)
}
func applicationDidFinishLaunching(_: Notification) {
NSApp.activate(ignoringOtherApps: true)
}
}