diff --git a/Museion.xcodeproj/project.pbxproj b/Museion.xcodeproj/project.pbxproj
index eaf92a6..0963ca4 100644
--- a/Museion.xcodeproj/project.pbxproj
+++ b/Museion.xcodeproj/project.pbxproj
@@ -331,7 +331,7 @@
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
- MACOSX_DEPLOYMENT_TARGET = 26.5;
+ MACOSX_DEPLOYMENT_TARGET = 27.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES;
@@ -391,7 +391,7 @@
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
- MACOSX_DEPLOYMENT_TARGET = 26.5;
+ MACOSX_DEPLOYMENT_TARGET = 27.0;
MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES;
SDKROOT = macosx;
@@ -481,7 +481,7 @@
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 3M7APDAAC5;
GENERATE_INFOPLIST_FILE = YES;
- MACOSX_DEPLOYMENT_TARGET = 26.5;
+ MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests;
PRODUCT_NAME = "$(TARGET_NAME)";
@@ -503,7 +503,7 @@
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 3M7APDAAC5;
GENERATE_INFOPLIST_FILE = YES;
- MACOSX_DEPLOYMENT_TARGET = 26.5;
+ MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests;
PRODUCT_NAME = "$(TARGET_NAME)";
diff --git a/Museion/ProfileBackup.swift b/Museion/ProfileBackup.swift
index 1d9f82c..ef349fd 100644
--- a/Museion/ProfileBackup.swift
+++ b/Museion/ProfileBackup.swift
@@ -70,7 +70,8 @@ nonisolated enum ProfileBackup {
// Age check against the newest existing snapshot (#15: skips record no
// state; the normal age check governs retry).
if let newest = sortedSnapshots(in: backupsRoot).first,
- now.timeIntervalSince(newest.timestamp) < snapshotInterval {
+ now.timeIntervalSince(newest.timestamp) < snapshotInterval
+ {
return .skippedFresh
}
diff --git a/Museion/ReadingPresenter.swift b/Museion/ReadingPresenter.swift
index 4c7bb7c..d202cc8 100644
--- a/Museion/ReadingPresenter.swift
+++ b/Museion/ReadingPresenter.swift
@@ -176,12 +176,12 @@ nonisolated enum ReadingPresenter {
/// the bundle without any config).
static func styleSheet() -> String {
#if DEBUG
- let repoCSS = URL(fileURLWithPath: #filePath) // …/Museion/ReadingPresenter.swift
- .deletingLastPathComponent()
- .appendingPathComponent("Resources/reading.css")
- if let live = try? String(contentsOf: repoCSS, encoding: .utf8), !live.isEmpty {
- return live
- }
+ let repoCSS = URL(fileURLWithPath: #filePath) // …/Museion/ReadingPresenter.swift
+ .deletingLastPathComponent()
+ .appendingPathComponent("Resources/reading.css")
+ if let live = try? String(contentsOf: repoCSS, encoding: .utf8), !live.isEmpty {
+ return live
+ }
#endif
return Bundle.main.path(forResource: "reading", ofType: "css").flatMap {
try? String(contentsOf: URL(fileURLWithPath: $0), encoding: .utf8)
diff --git a/Museion/ReadingSurface.swift b/Museion/ReadingSurface.swift
index 19b79a9..4c00754 100644
--- a/Museion/ReadingSurface.swift
+++ b/Museion/ReadingSurface.swift
@@ -162,7 +162,6 @@ struct ReadingSurface: NSViewRepresentable {
return blocks.first { $0.sourceRange.location >= caret }?.sourceLine
}
-
// MARK: WKNavigationDelegate
func webView(_ wv: WKWebView, didFinish _: WKNavigation!) {
diff --git a/MuseionTests/ProfileBackupTests.swift b/MuseionTests/ProfileBackupTests.swift
index 04464c7..357c4af 100644
--- a/MuseionTests/ProfileBackupTests.swift
+++ b/MuseionTests/ProfileBackupTests.swift
@@ -29,13 +29,13 @@ func makeProfileFixture(at root: String) -> String {
for dir in ["skills/serif-writing", "logs", "cache", "sessions/xyz/cache"] {
try? fileManager.createDirectory(
atPath: (profile as NSString).appendingPathComponent(dir),
- withIntermediateDirectories: true
+ withIntermediateDirectories: true,
)
}
func write(_ text: String, _ rel: String) {
try? text.write(
toFile: (profile as NSString).appendingPathComponent(rel),
- atomically: true, encoding: .utf8
+ atomically: true, encoding: .utf8,
)
}
write("{\"token\": \"secret\"}", "auth.json")
diff --git a/prototypes/GateUIPrototype.swift b/prototypes/GateUIPrototype.swift
index ece5540..3853964 100644
--- a/prototypes/GateUIPrototype.swift
+++ b/prototypes/GateUIPrototype.swift
@@ -11,522 +11,534 @@
import SwiftUI
// MARK: - Tokens (from ref/Web-Prototype/museion-workspace.html)
-enum Tok {
- static let bg = Color(hex: 0xFAFAF7)
- static let surface = Color(hex: 0xFFFFFF)
- static let fg = Color(hex: 0x1A1916)
- static let muted = Color(hex: 0x6B6964)
- static let border = Color(hex: 0xE8E5DF)
- static let accent = Color(hex: 0xC96442)
- static let fgSoft = Color(hex: 0x1A1916).opacity(0.06)
- static let accentSoft = Color(hex: 0xC96442).opacity(0.14)
- static func display(_ size: CGFloat, _ weight: Font.Weight = .regular) -> Font {
- .custom("Iowan Old Style", size: size).weight(weight)
- }
- static func mono(_ size: CGFloat) -> Font {
- .system(size: size, design: .monospaced)
- }
+enum Tok {
+ static let bg = Color(hex: 0xFAFAF7)
+ static let surface = Color(hex: 0xFFFFFF)
+ static let fg = Color(hex: 0x1A1916)
+ static let muted = Color(hex: 0x6B6964)
+ static let border = Color(hex: 0xE8E5DF)
+ static let accent = Color(hex: 0xC96442)
+ static let fgSoft = Color(hex: 0x1A1916).opacity(0.06)
+ static let accentSoft = Color(hex: 0xC96442).opacity(0.14)
+
+ static func display(_ size: CGFloat, _ weight: Font.Weight = .regular) -> Font {
+ .custom("Iowan Old Style", size: size).weight(weight)
+ }
+
+ static func mono(_ size: CGFloat) -> Font {
+ .system(size: size, design: .monospaced)
+ }
}
extension Color {
- init(hex: UInt32) {
- self.init(.sRGB,
- red: Double((hex >> 16) & 0xFF) / 255,
- green: Double((hex >> 8) & 0xFF) / 255,
- blue: Double(hex & 0xFF) / 255)
- }
+ init(hex: UInt32) {
+ self.init(.sRGB,
+ red: Double((hex >> 16) & 0xFF) / 255,
+ green: Double((hex >> 8) & 0xFF) / 255,
+ blue: Double(hex & 0xFF) / 255)
+ }
}
// MARK: - Mock state
-final class GateModel: ObservableObject {
- enum Phase: Equatable { case checking, passed, failed }
- @Published var phase: Phase = .checking
- @Published var firstRun = true
- @Published var nextPass = false // outcome of the NEXT check (scenario control)
- let version = "0.42.1"
- private var token = 0
- func check() {
- token += 1
- let myToken = token
- phase = .checking
- DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { [weak self] in
- guard let self, self.token == myToken else { return }
- self.phase = self.nextPass ? .passed : .failed
- }
- }
+final class GateModel: ObservableObject {
+ enum Phase: Equatable { case checking, passed, failed }
+ @Published var phase: Phase = .checking
+ @Published var firstRun = true
+ @Published var nextPass = false // outcome of the NEXT check (scenario control)
+ let version = "0.42.1"
+ private var token = 0
+
+ func check() {
+ token += 1
+ let myToken = token
+ phase = .checking
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { [weak self] in
+ guard let self, token == myToken else { return }
+ phase = nextPass ? .passed : .failed
+ }
+ }
}
// MARK: - Shared pieces
+
struct EnginePill: View {
- @EnvironmentObject var model: GateModel
+ @EnvironmentObject var model: GateModel
- var body: some View {
- HStack(spacing: 7) {
- Circle()
- .fill(dotColor)
- .frame(width: 7, height: 7)
- .modifier(Pulse(active: model.phase == .checking))
- Text("Hermes")
- .font(Tok.mono(11))
- .foregroundStyle(Tok.fg)
- if model.phase == .passed {
- Text(model.version)
- .font(Tok.mono(11))
- .foregroundStyle(Tok.muted)
- }
- }
- .padding(.horizontal, 10)
- .frame(minHeight: 30)
- .background(Tok.surface, in: RoundedRectangle(cornerRadius: 10))
- .overlay(
- RoundedRectangle(cornerRadius: 10)
- .strokeBorder(model.phase == .failed ? Tok.accent : Tok.border, lineWidth: 1)
- )
- }
+ var body: some View {
+ HStack(spacing: 7) {
+ Circle()
+ .fill(dotColor)
+ .frame(width: 7, height: 7)
+ .modifier(Pulse(active: model.phase == .checking))
+ Text("Hermes")
+ .font(Tok.mono(11))
+ .foregroundStyle(Tok.fg)
+ if model.phase == .passed {
+ Text(model.version)
+ .font(Tok.mono(11))
+ .foregroundStyle(Tok.muted)
+ }
+ }
+ .padding(.horizontal, 10)
+ .frame(minHeight: 30)
+ .background(Tok.surface, in: RoundedRectangle(cornerRadius: 10))
+ .overlay(
+ RoundedRectangle(cornerRadius: 10)
+ .strokeBorder(model.phase == .failed ? Tok.accent : Tok.border, lineWidth: 1),
+ )
+ }
- private var dotColor: Color {
- switch model.phase {
- case .checking: Tok.accent
- case .passed: Tok.fg
- case .failed: Tok.accent
- }
- }
+ private var dotColor: Color {
+ switch model.phase {
+ case .checking: Tok.accent
+ case .passed: Tok.fg
+ case .failed: Tok.accent
+ }
+ }
}
struct Pulse: ViewModifier {
- let active: Bool
- func body(content: Content) -> some View {
- if active {
- content.opacity(0.35).animation(
- Animation.easeInOut(duration: 0.55).repeatForever(autoreverses: true),
- value: active)
- } else {
- content
- }
- }
+ let active: Bool
+ func body(content: Content) -> some View {
+ if active {
+ content.opacity(0.35).animation(
+ Animation.easeInOut(duration: 0.55).repeatForever(autoreverses: true),
+ value: active,
+ )
+ } else {
+ content
+ }
+ }
}
/// Placeholder install steps — the real copy is a graduated ticket, not this one.
struct InstallSteps: View {
- var numbered = true
+ var numbered = true
- var body: some View {
- VStack(alignment: .leading, spacing: 7) {
- ForEach(Array(steps.enumerated()), id: \.offset) { idx, step in
- HStack(alignment: .top, spacing: 8) {
- if numbered {
- Text("\(idx + 1).").font(Tok.mono(11)).foregroundStyle(Tok.muted)
- }
- Text(step)
- .font(.system(size: 12))
- .foregroundStyle(Tok.fg)
- }
- }
- }
- .frame(maxWidth: .infinity, alignment: .leading)
- .padding(12)
- .background(Tok.bg, in: RoundedRectangle(cornerRadius: 10))
- .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Tok.border))
- }
+ var body: some View {
+ VStack(alignment: .leading, spacing: 7) {
+ ForEach(Array(steps.enumerated()), id: \.offset) { idx, step in
+ HStack(alignment: .top, spacing: 8) {
+ if numbered {
+ Text("\(idx + 1).").font(Tok.mono(11)).foregroundStyle(Tok.muted)
+ }
+ Text(step)
+ .font(.system(size: 12))
+ .foregroundStyle(Tok.fg)
+ }
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .padding(12)
+ .background(Tok.bg, in: RoundedRectangle(cornerRadius: 10))
+ .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Tok.border))
+ }
- private var steps: [String] {
- [
- "Install Hermes: brew install hermes",
- "Check the install: hermes acp --check",
- "Then click Re-check below.",
- ]
- }
+ private var steps: [String] {
+ [
+ "Install Hermes: brew install hermes",
+ "Check the install: hermes acp --check",
+ "Then click Re-check below.",
+ ]
+ }
}
struct RecheckButton: View {
- @EnvironmentObject var model: GateModel
- var label = "Re-check"
+ @EnvironmentObject var model: GateModel
+ var label = "Re-check"
- var body: some View {
- Button {
- model.check()
- } label: {
- HStack(spacing: 6) {
- if model.phase == .checking {
- ProgressView().controlSize(.small)
- }
- Text(model.phase == .checking ? "Checking…" : label)
- }
- .frame(maxWidth: 180)
- }
- .buttonStyle(.borderedProminent)
- .tint(Tok.accent)
- .disabled(model.phase == .checking)
- }
+ var body: some View {
+ Button {
+ model.check()
+ } label: {
+ HStack(spacing: 6) {
+ if model.phase == .checking {
+ ProgressView().controlSize(.small)
+ }
+ Text(model.phase == .checking ? "Checking…" : label)
+ }
+ .frame(maxWidth: 180)
+ }
+ .buttonStyle(.borderedProminent)
+ .tint(Tok.accent)
+ .disabled(model.phase == .checking)
+ }
}
// MARK: - Mock workspace (context for the gate to sit over)
+
struct MockWorkspace: View {
- @EnvironmentObject var model: GateModel
- var banner: AnyView? = nil
+ @EnvironmentObject var model: GateModel
+ var banner: AnyView?
- var body: some View {
- VStack(spacing: 0) {
- toolbar
- if let banner { banner }
- HStack(spacing: 0) {
- rail
- editor
- }
- }
- .background(Tok.bg)
- }
+ var body: some View {
+ VStack(spacing: 0) {
+ toolbar
+ if let banner {
+ banner
+ }
+ HStack(spacing: 0) {
+ rail
+ editor
+ }
+ }
+ .background(Tok.bg)
+ }
- private var toolbar: some View {
- HStack(spacing: 12) {
- Text("M")
- .font(Tok.display(17, .semibold))
- .foregroundStyle(Tok.accent)
- .frame(width: 26, height: 26)
- .background(Tok.accentSoft, in: RoundedRectangle(cornerRadius: 7))
- Text("On rereading Orwell")
- .font(.system(size: 13))
- .foregroundStyle(Tok.muted)
- .lineLimit(1)
- Spacer()
- EnginePill()
- }
- .padding(.horizontal, 14)
- .frame(height: 48)
- .background(Tok.surface)
- .overlay(alignment: .bottom) { Divider().overlay(Tok.border) }
- }
+ private var toolbar: some View {
+ HStack(spacing: 12) {
+ Text("M")
+ .font(Tok.display(17, .semibold))
+ .foregroundStyle(Tok.accent)
+ .frame(width: 26, height: 26)
+ .background(Tok.accentSoft, in: RoundedRectangle(cornerRadius: 7))
+ Text("On rereading Orwell")
+ .font(.system(size: 13))
+ .foregroundStyle(Tok.muted)
+ .lineLimit(1)
+ Spacer()
+ EnginePill()
+ }
+ .padding(.horizontal, 14)
+ .frame(height: 48)
+ .background(Tok.surface)
+ .overlay(alignment: .bottom) { Divider().overlay(Tok.border) }
+ }
- private var rail: some View {
- VStack(spacing: 6) {
- ForEach(["square.stack.3d.up", "bubble.left.and.bubble.right", "sparkles", "gearshape"], id: \.self) { icon in
- Image(systemName: icon)
- .font(.system(size: 15))
- .foregroundStyle(Tok.muted)
- .frame(width: 40, height: 40)
- }
- Spacer()
- }
- .padding(.top, 10)
- .frame(width: 56)
- .background(Tok.bg)
- .overlay(alignment: .trailing) { Divider().overlay(Tok.border) }
- }
+ private var rail: some View {
+ VStack(spacing: 6) {
+ ForEach(["square.stack.3d.up", "bubble.left.and.bubble.right", "sparkles", "gearshape"], id: \.self) { icon in
+ Image(systemName: icon)
+ .font(.system(size: 15))
+ .foregroundStyle(Tok.muted)
+ .frame(width: 40, height: 40)
+ }
+ Spacer()
+ }
+ .padding(.top, 10)
+ .frame(width: 56)
+ .background(Tok.bg)
+ .overlay(alignment: .trailing) { Divider().overlay(Tok.border) }
+ }
- private var editor: some View {
- ScrollView {
- VStack(alignment: .leading, spacing: 18) {
- Text("On rereading Orwell")
- .font(Tok.display(26, .semibold))
- Text(previewText)
- .font(.system(size: 14))
- .foregroundStyle(Tok.fg)
- .lineSpacing(5)
- }
- .padding(36)
- .frame(maxWidth: 720, alignment: .leading)
- .frame(maxWidth: .infinity, alignment: .center)
- }
- }
+ private var editor: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 18) {
+ Text("On rereading Orwell")
+ .font(Tok.display(26, .semibold))
+ Text(previewText)
+ .font(.system(size: 14))
+ .foregroundStyle(Tok.fg)
+ .lineSpacing(5)
+ }
+ .padding(36)
+ .frame(maxWidth: 720, alignment: .leading)
+ .frame(maxWidth: .infinity, alignment: .center)
+ }
+ }
- private var previewText: String {
- String(repeating: "The essay argues itself into a corner by the third paragraph, and the prose knows it. Sentences shorten. Claims retreat. ", count: 6)
- }
+ private var previewText: String {
+ String(repeating: "The essay argues itself into a corner by the third paragraph, and the prose knows it. Sentences shorten. Claims retreat. ", count: 6)
+ }
}
// MARK: - Variant A — blocking sheet, every launch
+
struct VariantA: View {
- @EnvironmentObject var model: GateModel
- @State private var showSteps = false
+ @EnvironmentObject var model: GateModel
+ @State private var showSteps = false
- var body: some View {
- ZStack {
- MockWorkspace().disabled(true)
- Rectangle().fill(Tok.fg.opacity(0.28)).ignoresSafeArea()
- card
- .padding(30)
- .frame(maxWidth: 430)
- .background(Tok.surface, in: RoundedRectangle(cornerRadius: 14))
- .overlay(
- RoundedRectangle(cornerRadius: 14)
- .strokeBorder(model.phase == .failed ? Tok.accent : Tok.border, lineWidth: 1)
- )
- .shadow(radius: 24, y: 8)
- }
- }
+ var body: some View {
+ ZStack {
+ MockWorkspace().disabled(true)
+ Rectangle().fill(Tok.fg.opacity(0.28)).ignoresSafeArea()
+ card
+ .padding(30)
+ .frame(maxWidth: 430)
+ .background(Tok.surface, in: RoundedRectangle(cornerRadius: 14))
+ .overlay(
+ RoundedRectangle(cornerRadius: 14)
+ .strokeBorder(model.phase == .failed ? Tok.accent : Tok.border, lineWidth: 1),
+ )
+ .shadow(radius: 24, y: 8)
+ }
+ }
- private var card: some View {
- VStack(spacing: 14) {
- Image(systemName: model.phase == .failed ? "exclamationmark.triangle.fill" : "checkmark.circle.fill")
- .font(.system(size: 30))
- .foregroundStyle(model.phase == .failed ? Tok.accent : Tok.fg)
- .opacity(model.phase == .checking ? 0 : 1)
+ private var card: some View {
+ VStack(spacing: 14) {
+ Image(systemName: model.phase == .failed ? "exclamationmark.triangle.fill" : "checkmark.circle.fill")
+ .font(.system(size: 30))
+ .foregroundStyle(model.phase == .failed ? Tok.accent : Tok.fg)
+ .opacity(model.phase == .checking ? 0 : 1)
- Text(title)
- .font(Tok.display(19, .semibold))
- .multilineTextAlignment(.center)
+ Text(title)
+ .font(Tok.display(19, .semibold))
+ .multilineTextAlignment(.center)
- Text(subtitle)
- .font(.system(size: 12.5))
- .foregroundStyle(Tok.muted)
- .multilineTextAlignment(.center)
- .fixedSize(horizontal: false, vertical: true)
+ Text(subtitle)
+ .font(.system(size: 12.5))
+ .foregroundStyle(Tok.muted)
+ .multilineTextAlignment(.center)
+ .fixedSize(horizontal: false, vertical: true)
- if model.phase == .failed {
- if showSteps {
- InstallSteps()
- } else {
- Button("How do I install Hermes?") { showSteps = true }
- .buttonStyle(.link)
- .font(.system(size: 12))
- }
- }
+ if model.phase == .failed {
+ if showSteps {
+ InstallSteps()
+ } else {
+ Button("How do I install Hermes?") { showSteps = true }
+ .buttonStyle(.link)
+ .font(.system(size: 12))
+ }
+ }
- RecheckButton(label: model.phase == .passed ? "Re-check anyway" : "Re-check")
+ RecheckButton(label: model.phase == .passed ? "Re-check anyway" : "Re-check")
- if model.phase == .passed {
- Text("Checked on launch · Hermes \(model.version)")
- .font(Tok.mono(10))
- .foregroundStyle(Tok.muted)
- }
- }
- .padding(24)
- }
+ if model.phase == .passed {
+ Text("Checked on launch · Hermes \(model.version)")
+ .font(Tok.mono(10))
+ .foregroundStyle(Tok.muted)
+ }
+ }
+ .padding(24)
+ }
- private var title: String {
- switch model.phase {
- case .checking: "Checking the engine…"
- case .passed: "Engine ready"
- case .failed: "Museion needs its engine"
- }
- }
+ private var title: String {
+ switch model.phase {
+ case .checking: "Checking the engine…"
+ case .passed: "Engine ready"
+ case .failed: "Museion needs its engine"
+ }
+ }
- private var subtitle: String {
- switch model.phase {
- case .checking: "Running hermes acp --check."
- case .passed: "Hermes \(model.version) answered the health check. The mentor is available."
- case .failed: "The Hermes engine wasn't found or didn't answer. Museion can't run Passes or Sessions without it — the editor below stays available."
- }
- }
+ private var subtitle: String {
+ switch model.phase {
+ case .checking: "Running hermes acp --check."
+ case .passed: "Hermes \(model.version) answered the health check. The mentor is available."
+ case .failed: "The Hermes engine wasn't found or didn't answer. Museion can't run Passes or Sessions without it — the editor below stays available."
+ }
+ }
}
// MARK: - Variant B — gate window (first run), pill (repeat runs)
-struct VariantB: View {
- @EnvironmentObject var model: GateModel
- var body: some View {
- if model.firstRun {
- GateWindow()
- } else {
- MockWorkspace()
- }
- }
+struct VariantB: View {
+ @EnvironmentObject var model: GateModel
+
+ var body: some View {
+ if model.firstRun {
+ GateWindow()
+ } else {
+ MockWorkspace()
+ }
+ }
}
private struct GateWindow: View {
- @EnvironmentObject var model: GateModel
+ @EnvironmentObject var model: GateModel
- var body: some View {
- VStack(spacing: 0) {
- Spacer(minLength: 40)
- VStack(spacing: 16) {
- Text("Museion")
- .font(Tok.display(34, .semibold))
- Text("The Agentic Writing Environment")
- .font(Tok.mono(11))
- .foregroundStyle(Tok.muted)
- .textCase(.uppercase)
+ var body: some View {
+ VStack(spacing: 0) {
+ Spacer(minLength: 40)
+ VStack(spacing: 16) {
+ Text("Museion")
+ .font(Tok.display(34, .semibold))
+ Text("The Agentic Writing Environment")
+ .font(Tok.mono(11))
+ .foregroundStyle(Tok.muted)
+ .textCase(.uppercase)
- Divider().frame(width: 60).overlay(Tok.border)
+ Divider().frame(width: 60).overlay(Tok.border)
- status
+ status
- if model.phase == .failed {
- InstallSteps()
- }
- if model.phase == .passed {
- Text("First run complete — the workspace opens next.")
- .font(.system(size: 12))
- .foregroundStyle(Tok.muted)
- }
- }
- .padding(34)
- .frame(maxWidth: 470)
- .background(Tok.surface, in: RoundedRectangle(cornerRadius: 14))
- .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Tok.border))
- .shadow(radius: 18, y: 6)
- Spacer(minLength: 40)
- }
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(Tok.bg)
- }
+ if model.phase == .failed {
+ InstallSteps()
+ }
+ if model.phase == .passed {
+ Text("First run complete — the workspace opens next.")
+ .font(.system(size: 12))
+ .foregroundStyle(Tok.muted)
+ }
+ }
+ .padding(34)
+ .frame(maxWidth: 470)
+ .background(Tok.surface, in: RoundedRectangle(cornerRadius: 14))
+ .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Tok.border))
+ .shadow(radius: 18, y: 6)
+ Spacer(minLength: 40)
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .background(Tok.bg)
+ }
- @ViewBuilder private var status: some View {
- switch model.phase {
- case .checking:
- VStack(spacing: 10) {
- ProgressView().controlSize(.regular)
- Text("Looking for the Hermes engine…")
- .font(.system(size: 13))
- .foregroundStyle(Tok.muted)
- }
- case .passed:
- VStack(spacing: 10) {
- Image(systemName: "checkmark.circle.fill")
- .font(.system(size: 26))
- .foregroundStyle(Tok.fg)
- Text("Engine ready — Hermes \(model.version)")
- .font(Tok.display(15, .semibold))
- }
- case .failed:
- VStack(spacing: 10) {
- Image(systemName: "exclamationmark.triangle.fill")
- .font(.system(size: 26))
- .foregroundStyle(Tok.accent)
- Text("Engine missing")
- .font(Tok.display(15, .semibold))
- }
- }
- }
+ @ViewBuilder private var status: some View {
+ switch model.phase {
+ case .checking:
+ VStack(spacing: 10) {
+ ProgressView().controlSize(.regular)
+ Text("Looking for the Hermes engine…")
+ .font(.system(size: 13))
+ .foregroundStyle(Tok.muted)
+ }
+ case .passed:
+ VStack(spacing: 10) {
+ Image(systemName: "checkmark.circle.fill")
+ .font(.system(size: 26))
+ .foregroundStyle(Tok.fg)
+ Text("Engine ready — Hermes \(model.version)")
+ .font(Tok.display(15, .semibold))
+ }
+ case .failed:
+ VStack(spacing: 10) {
+ Image(systemName: "exclamationmark.triangle.fill")
+ .font(.system(size: 26))
+ .foregroundStyle(Tok.accent)
+ Text("Engine missing")
+ .font(Tok.display(15, .semibold))
+ }
+ }
+ }
}
// MARK: - Variant C — inline banner, never blocks
+
struct VariantC: View {
- @EnvironmentObject var model: GateModel
+ @EnvironmentObject var model: GateModel
- var body: some View {
- MockWorkspace(banner: AnyView(banner))
- }
+ var body: some View {
+ MockWorkspace(banner: AnyView(banner))
+ }
- @ViewBuilder private var banner: some View {
- if model.phase == .failed {
- failBanner
- } else if model.firstRun, model.phase == .passed {
- passBanner
- }
- }
+ @ViewBuilder private var banner: some View {
+ if model.phase == .failed {
+ failBanner
+ } else if model.firstRun, model.phase == .passed {
+ passBanner
+ }
+ }
- private var failBanner: some View {
- HStack(alignment: .top, spacing: 12) {
- Image(systemName: "exclamationmark.triangle.fill")
- .foregroundStyle(Tok.accent)
- VStack(alignment: .leading, spacing: 8) {
- (Text("Engine unavailable. ").font(.system(size: 12.5, weight: .semibold))
- + Text("Passes and Sessions need Hermes; the editor keeps working.")
- .font(.system(size: 12.5))
- .foregroundStyle(Tok.muted))
- InstallSteps()
- }
- Spacer(minLength: 12)
- RecheckButton()
- }
- .padding(14)
- .background(Tok.accent.opacity(0.08))
- .overlay(alignment: .bottom) { Rectangle().fill(Tok.accent).frame(height: 1) }
- }
+ private var failBanner: some View {
+ HStack(alignment: .top, spacing: 12) {
+ Image(systemName: "exclamationmark.triangle.fill")
+ .foregroundStyle(Tok.accent)
+ VStack(alignment: .leading, spacing: 8) {
+ Text("Engine unavailable. ").font(.system(size: 12.5, weight: .semibold))
+ + Text("Passes and Sessions need Hermes; the editor keeps working.")
+ .font(.system(size: 12.5))
+ .foregroundStyle(Tok.muted)
+ InstallSteps()
+ }
+ Spacer(minLength: 12)
+ RecheckButton()
+ }
+ .padding(14)
+ .background(Tok.accent.opacity(0.08))
+ .overlay(alignment: .bottom) { Rectangle().fill(Tok.accent).frame(height: 1) }
+ }
- private var passBanner: some View {
- HStack(spacing: 8) {
- Image(systemName: "checkmark.circle.fill").foregroundStyle(Tok.fg)
- Text("Engine ready — Hermes \(model.version)")
- .font(.system(size: 12.5))
- Spacer()
- }
- .padding(.horizontal, 14).padding(.vertical, 8)
- .background(Tok.surface)
- .overlay(alignment: .bottom) { Divider().overlay(Tok.border) }
- }
+ private var passBanner: some View {
+ HStack(spacing: 8) {
+ Image(systemName: "checkmark.circle.fill").foregroundStyle(Tok.fg)
+ Text("Engine ready — Hermes \(model.version)")
+ .font(.system(size: 12.5))
+ Spacer()
+ }
+ .padding(.horizontal, 14).padding(.vertical, 8)
+ .background(Tok.surface)
+ .overlay(alignment: .bottom) { Divider().overlay(Tok.border) }
+ }
}
// MARK: - Root + switcher
+
struct GatePrototypeRoot: View {
- @StateObject private var model = GateModel()
- @State private var variant = "A"
- let variants: [(String, String)] = [
- ("A", "Blocking sheet"),
- ("B", "Gate window"),
- ("C", "Inline banner"),
- ]
+ @StateObject private var model = GateModel()
+ @State private var variant = "A"
+ let variants: [(String, String)] = [
+ ("A", "Blocking sheet"),
+ ("B", "Gate window"),
+ ("C", "Inline banner"),
+ ]
- var body: some View {
- ZStack(alignment: .bottom) {
- currentView.environmentObject(model)
- SwitcherBar(variant: $variant, model: model)
- }
- .frame(minWidth: 1100, minHeight: 680)
- .background(Tok.bg)
- .onAppear { model.check() }
- }
+ var body: some View {
+ ZStack(alignment: .bottom) {
+ currentView.environmentObject(model)
+ SwitcherBar(variant: $variant, model: model)
+ }
+ .frame(minWidth: 1100, minHeight: 680)
+ .background(Tok.bg)
+ .onAppear { model.check() }
+ }
- private var currentView: some View {
- switch variant {
- case "A": AnyView(VariantA())
- case "B": AnyView(VariantB())
- default: AnyView(VariantC())
- }
- }
+ private var currentView: some View {
+ switch variant {
+ case "A": AnyView(VariantA())
+ case "B": AnyView(VariantB())
+ default: AnyView(VariantC())
+ }
+ }
}
struct SwitcherBar: View {
- @Binding var variant: String
- @ObservedObject var model: GateModel
+ @Binding var variant: String
+ @ObservedObject var model: GateModel
- var body: some View {
- HStack(spacing: 14) {
- arrow("chevron.left") { cycle(-1) }
- .keyboardShortcut(.leftArrow, modifiers: [])
- Text("\(variant) — \(variants.first { $0.0 == variant }?.1 ?? "")")
- .font(Tok.mono(12))
- arrow("chevron.right") { cycle(1) }
- .keyboardShortcut(.rightArrow, modifiers: [])
+ var body: some View {
+ HStack(spacing: 14) {
+ arrow("chevron.left") { cycle(-1) }
+ .keyboardShortcut(.leftArrow, modifiers: [])
+ Text("\(variant) — \(variants.first { $0.0 == variant }?.1 ?? "")")
+ .font(Tok.mono(12))
+ arrow("chevron.right") { cycle(1) }
+ .keyboardShortcut(.rightArrow, modifiers: [])
- Divider().frame(height: 16).overlay(Tok.border)
- Toggle("First run", isOn: $model.firstRun)
- .toggleStyle(.checkbox).font(Tok.mono(11))
- Toggle("Next check passes", isOn: $model.nextPass)
- .toggleStyle(.checkbox).font(Tok.mono(11))
- Divider().frame(height: 16).overlay(Tok.border)
- Text(phaseLabel)
- .font(Tok.mono(11)).foregroundStyle(.tertiary)
- }
- .padding(.horizontal, 14).padding(.vertical, 9)
- .background(Tok.fg, in: RoundedRectangle(cornerRadius: 10))
- .foregroundStyle(Tok.bg)
- .padding(.bottom, 14)
- .shadow(radius: 12, y: 4)
- .onAppear { NSApp.appearance = NSAppearance(named: .aqua) } // prototype: force light so tokens read as designed
- }
+ Divider().frame(height: 16).overlay(Tok.border)
+ Toggle("First run", isOn: $model.firstRun)
+ .toggleStyle(.checkbox).font(Tok.mono(11))
+ Toggle("Next check passes", isOn: $model.nextPass)
+ .toggleStyle(.checkbox).font(Tok.mono(11))
+ Divider().frame(height: 16).overlay(Tok.border)
+ Text(phaseLabel)
+ .font(Tok.mono(11)).foregroundStyle(.tertiary)
+ }
+ .padding(.horizontal, 14).padding(.vertical, 9)
+ .background(Tok.fg, in: RoundedRectangle(cornerRadius: 10))
+ .foregroundStyle(Tok.bg)
+ .padding(.bottom, 14)
+ .shadow(radius: 12, y: 4)
+ .onAppear { NSApp.appearance = NSAppearance(named: .aqua) } // prototype: force light so tokens read as designed
+ }
- private var variants: [(String, String)] {
- [("A", "Blocking sheet"), ("B", "Gate window"), ("C", "Inline banner")]
- }
+ private var variants: [(String, String)] {
+ [("A", "Blocking sheet"), ("B", "Gate window"), ("C", "Inline banner")]
+ }
- private var phaseLabel: String {
- switch model.phase {
- case .checking: "checking"
- case .passed: "passed · hermes \(model.version)"
- case .failed: "failed"
- }
- }
+ private var phaseLabel: String {
+ switch model.phase {
+ case .checking: "checking"
+ case .passed: "passed · hermes \(model.version)"
+ case .failed: "failed"
+ }
+ }
- private func cycle(_ dir: Int) {
- let idx = variants.firstIndex { $0.0 == variant } ?? 0
- variant = variants[(idx + dir + variants.count) % variants.count].0
- }
+ private func cycle(_ dir: Int) {
+ let idx = variants.firstIndex { $0.0 == variant } ?? 0
+ variant = variants[(idx + dir + variants.count) % variants.count].0
+ }
- private func arrow(_ system: String, action: @escaping () -> Void) -> some View {
- Button(action: action) {
- Image(systemName: system).font(.system(size: 11, weight: .semibold))
- }
- .buttonStyle(.plain)
- }
+ private func arrow(_ system: String, action: @escaping () -> Void) -> some View {
+ Button(action: action) {
+ Image(systemName: system).font(.system(size: 11, weight: .semibold))
+ }
+ .buttonStyle(.plain)
+ }
}
@main
struct GateUIPrototypeApp: App {
- var body: some Scene {
- WindowGroup { GatePrototypeRoot() }
- }
+ var body: some Scene {
+ WindowGroup { GatePrototypeRoot() }
+ }
}
diff --git a/spike/apexhtml/Package.swift b/spike/apexhtml/Package.swift
index eb53cd9..b256b45 100644
--- a/spike/apexhtml/Package.swift
+++ b/spike/apexhtml/Package.swift
@@ -2,7 +2,7 @@
import PackageDescription
let package = Package(
- name: "ApexHTMLSpike",
- platforms: [.macOS(.v26)],
- targets: [.executableTarget(name: "ApexHTMLSpike")]
+ name: "ApexHTMLSpike",
+ platforms: [.macOS(.v26)],
+ targets: [.executableTarget(name: "ApexHTMLSpike")],
)
diff --git a/spike/apexhtml/Sources/ApexHTMLSpike/ApexHTMLSpike.swift b/spike/apexhtml/Sources/ApexHTMLSpike/ApexHTMLSpike.swift
index 471f318..7b4c02f 100644
--- a/spike/apexhtml/Sources/ApexHTMLSpike/ApexHTMLSpike.swift
+++ b/spike/apexhtml/Sources/ApexHTMLSpike/ApexHTMLSpike.swift
@@ -8,399 +8,444 @@ import WebKit
/// ponytail: sentinel pre-pass — apex passes HTML comments through verbatim, we stamp after.
enum MarkdownChunker {
- /// Prepend `` (N = 1-based source line) before every blank-line chunk.
- nonisolated static func stamp(_ source: String) -> String {
- let isBlank = { (l: Substring) in l.allSatisfy { $0 == " " || $0 == "\t" || $0 == "\r" } }
- let lines = source.split(separator: "\n", omittingEmptySubsequences: false)
- var out: [String] = []
- var i = 0
- while i < lines.count {
- if isBlank(lines[i]) { i += 1; continue }
- if !out.isEmpty { out.append("") }
- out.append("")
- while i < lines.count && !isBlank(lines[i]) { out.append(String(lines[i])); i += 1 }
- }
- return out.joined(separator: "\n")
- }
+ /// Prepend `` (N = 1-based source line) before every blank-line chunk.
+ nonisolated static func stamp(_ source: String) -> String {
+ let isBlank = { (l: Substring) in l.allSatisfy { $0 == " " || $0 == "\t" || $0 == "\r" } }
+ let lines = source.split(separator: "\n", omittingEmptySubsequences: false)
+ var out: [String] = []
+ var i = 0
+ while i < lines.count {
+ if isBlank(lines[i]) {
+ i += 1; continue
+ }
+ if !out.isEmpty {
+ out.append("")
+ }
+ out.append("")
+ while i < lines.count, !isBlank(lines[i]) {
+ out.append(String(lines[i])); i += 1
+ }
+ }
+ return out.joined(separator: "\n")
+ }
}
/// Rewrites `` into `data-source-line="N"` on the element that follows.
enum HTMLStamper {
- nonisolated static func stamp(_ html: String) -> String {
- let re = try! NSRegularExpression(pattern: #"\s*\n<([a-zA-Z][a-zA-Z0-9]*)"#)
- let ms = NSMutableString(string: html)
- re.replaceMatches(in: ms, range: NSMakeRange(0, ms.length), withTemplate: "<$2 data-source-line=\"$1\"")
- return ms as String
- }
+ nonisolated static func stamp(_ html: String) -> String {
+ let re = try! NSRegularExpression(pattern: #"\s*\n<([a-zA-Z][a-zA-Z0-9]*)"#)
+ let ms = NSMutableString(string: html)
+ re.replaceMatches(in: ms, range: NSMakeRange(0, ms.length), withTemplate: "<$2 data-source-line=\"$1\"")
+ return ms as String
+ }
}
// MARK: - Apex runner
enum Apex {
- nonisolated static func binaryPath() -> String? {
- if let env = ProcessInfo.processInfo.environment["APEX_PATH"] { return env }
- for p in ["/opt/homebrew/bin/apex", "/usr/local/bin/apex"] where FileManager.default.isExecutableFile(atPath: p) { return p }
- return nil
- }
+ nonisolated static func binaryPath() -> String? {
+ if let env = ProcessInfo.processInfo.environment["APEX_PATH"] {
+ return env
+ }
+ for p in ["/opt/homebrew/bin/apex", "/usr/local/bin/apex"] where FileManager.default.isExecutableFile(atPath: p) {
+ return p
+ }
+ return nil
+ }
- /// markdown → HTML fragment with images embedded (base64). Returns (html, milliseconds).
- nonisolated static func render(_ markdown: String, baseDir: URL) throws -> (String, Double) {
- guard let bin = binaryPath() else { throw CocoaError(.fileNoSuchFile) }
- let t0 = DispatchTime.now()
- let p = Process()
- p.executableURL = URL(fileURLWithPath: bin)
- // --no-mixed-lists: apex default merges an ordered list after a bullet list into one
— kills `1. 1. 1.` renumbering.
- // --embed-images: apex inlines images as base64 data URLs (base-dir resolves the
- // relative paths on our stdin flow) — WKWebView then needs NO file access at all.
- p.arguments = ["-t", "html", "--no-mixed-lists", "--embed-images", "--base-dir", baseDir.path]
- let stdin = Pipe(), stdout = Pipe(), stderr = Pipe()
- p.standardInput = stdin; p.standardOutput = stdout; p.standardError = stderr
- try p.run()
- stdin.fileHandleForWriting.write(Data(markdown.utf8))
- stdin.fileHandleForWriting.closeFile()
- let data = stdout.fileHandleForReading.readDataToEndOfFile()
- let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000
- // stdout EOF = conversion done (~18 ms). The ~65 ms after is apex's own teardown —
- // don't wait for it: reap via terminationHandler, hand the HTML over immediately.
- guard !data.isEmpty else {
- p.waitUntilExit()
- throw NSError(domain: "apex", code: Int(p.terminationStatus),
- userInfo: [NSLocalizedDescriptionKey: String(data: stderr.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "no stderr"])
- }
- p.terminationHandler = { _ in }
- return (String(decoding: data, as: UTF8.self), ms)
- }
+ /// markdown → HTML fragment with images embedded (base64). Returns (html, milliseconds).
+ nonisolated static func render(_ markdown: String, baseDir: URL) throws -> (String, Double) {
+ guard let bin = binaryPath() else { throw CocoaError(.fileNoSuchFile) }
+ let t0 = DispatchTime.now()
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: bin)
+ // --no-mixed-lists: apex default merges an ordered list after a bullet list into one — kills `1. 1. 1.` renumbering.
+ // --embed-images: apex inlines images as base64 data URLs (base-dir resolves the
+ // relative paths on our stdin flow) — WKWebView then needs NO file access at all.
+ p.arguments = ["-t", "html", "--no-mixed-lists", "--embed-images", "--base-dir", baseDir.path]
+ let stdin = Pipe(), stdout = Pipe(), stderr = Pipe()
+ p.standardInput = stdin; p.standardOutput = stdout; p.standardError = stderr
+ try p.run()
+ stdin.fileHandleForWriting.write(Data(markdown.utf8))
+ stdin.fileHandleForWriting.closeFile()
+ let data = stdout.fileHandleForReading.readDataToEndOfFile()
+ let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000
+ // stdout EOF = conversion done (~18 ms). The ~65 ms after is apex's own teardown —
+ // don't wait for it: reap via terminationHandler, hand the HTML over immediately.
+ guard !data.isEmpty else {
+ p.waitUntilExit()
+ throw NSError(domain: "apex", code: Int(p.terminationStatus),
+ userInfo: [NSLocalizedDescriptionKey: String(data: stderr.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? "no stderr"])
+ }
+ p.terminationHandler = { _ in }
+ return (String(decoding: data, as: UTF8.self), ms)
+ }
}
// MARK: - Reading surface
struct ReadingWebView: NSViewRepresentable {
- let fileURL: URL
- var onStats: (Stats) -> Void
- var onSourceLine: (String, Int) -> Void // ("click"|"top", line)
+ let fileURL: URL
+ var onStats: (Stats) -> Void
+ var onSourceLine: (String, Int) -> Void // ("click"|"top", line)
- struct Stats: Equatable {
- var apexMS: Double = 0
- var paintMS: Double = 0
- var htmlBytes: Int = 0
- var error: String?
- }
+ struct Stats: Equatable {
+ var apexMS: Double = 0
+ var paintMS: Double = 0
+ var htmlBytes: Int = 0
+ var error: String?
+ }
- func makeNSView(context: Context) -> WKWebView {
- let cfg = WKWebViewConfiguration()
- let ucc = cfg.userContentController
- ucc.addUserScript(WKUserScript(source: Self.probeJS, injectionTime: .atDocumentEnd, forMainFrameOnly: true))
- ucc.add(context.coordinator, name: "sourceClick")
- ucc.add(context.coordinator, name: "sourceScroll")
- ucc.add(context.coordinator, name: "openLink")
- let wv = WKWebView(frame: .zero, configuration: cfg)
- wv.navigationDelegate = context.coordinator
- // Kill the white reload flash: paint the page bg while loading instead of AppKit white.
- wv.underPageBackgroundColor = NSColor(red: 0.984, green: 0.984, blue: 0.992, alpha: 1) // #fbfbfd
- context.coordinator.webView = wv
- return wv
- }
+ func makeNSView(context: Context) -> WKWebView {
+ let cfg = WKWebViewConfiguration()
+ let ucc = cfg.userContentController
+ ucc.addUserScript(WKUserScript(source: Self.probeJS, injectionTime: .atDocumentEnd, forMainFrameOnly: true))
+ ucc.add(context.coordinator, name: "sourceClick")
+ ucc.add(context.coordinator, name: "sourceScroll")
+ ucc.add(context.coordinator, name: "openLink")
+ let wv = WKWebView(frame: .zero, configuration: cfg)
+ wv.navigationDelegate = context.coordinator
+ // Kill the white reload flash: paint the page bg while loading instead of AppKit white.
+ wv.underPageBackgroundColor = NSColor(red: 0.984, green: 0.984, blue: 0.992, alpha: 1) // #fbfbfd
+ context.coordinator.webView = wv
+ return wv
+ }
- func updateNSView(_ wv: WKWebView, context: Context) {
- guard context.coordinator.loadedURL != fileURL else { return }
- context.coordinator.loadedURL = fileURL
- render(into: wv, coordinator: context.coordinator)
- }
+ func updateNSView(_ wv: WKWebView, context: Context) {
+ guard context.coordinator.loadedURL != fileURL else { return }
+ context.coordinator.loadedURL = fileURL
+ render(into: wv, coordinator: context.coordinator)
+ }
- private func render(into wv: WKWebView, coordinator: Coordinator) {
- let url = fileURL
- Task {
- var stats = Stats()
- do {
- let source = try String(contentsOf: url, encoding: .utf8)
- let (html, ms) = try Apex.render(MarkdownChunker.stamp(source), baseDir: url.deletingLastPathComponent())
- stats.apexMS = ms
- stats.htmlBytes = html.utf8.count
- // loadHTMLString fast path is safe again: images are base64 data URLs now,
- // no file:// subresources → no restricted-origin block, no sandbox negotiation.
- coordinator.paintStart = DispatchTime.now()
- wv.loadHTMLString(Self.page(html: HTMLStamper.stamp(html)), baseURL: nil)
- } catch {
- stats.error = String(describing: error)
- }
- onStats(stats)
- }
- }
+ private func render(into wv: WKWebView, coordinator: Coordinator) {
+ let url = fileURL
+ Task {
+ var stats = Stats()
+ do {
+ let source = try String(contentsOf: url, encoding: .utf8)
+ let (html, ms) = try Apex.render(MarkdownChunker.stamp(source), baseDir: url.deletingLastPathComponent())
+ stats.apexMS = ms
+ stats.htmlBytes = html.utf8.count
+ // loadHTMLString fast path is safe again: images are base64 data URLs now,
+ // no file:// subresources → no restricted-origin block, no sandbox negotiation.
+ coordinator.paintStart = DispatchTime.now()
+ wv.loadHTMLString(Self.page(html: HTMLStamper.stamp(html)), baseURL: nil)
+ } catch {
+ stats.error = String(describing: error)
+ }
+ onStats(stats)
+ }
+ }
- // CSS custom properties fed from the ProseTypography slots (#70 defaults) + flow knobs (#71).
- static let css = """
- :root {
- --body-face: "Concourse OT", "Iowan Old Style", serif;
- --body-size: 17px;
- --headings-face: "Iowan Old Style", serif;
- --headings-size: 26px;
- --code-face: "UbuntuMono Nerd Font Mono", "UbuntuMonoNFM", monospace;
- --code-size: 13px;
- --lh: 1.25;
- --para-space: 17px; /* 1 line */
- --head-space: 34px; /* 2 lines */
- --measure: 640px;
- --ink: #1d1d1f; --muted: #6e6e73; --hairline: #d2d2d7;
- }
- html { background: #fbfbfd; }
- body {
- margin: 24px auto; padding: 0 24px; width: var(--measure); max-width: calc(100vw - 48px);
- color: var(--ink); font-family: var(--body-face); font-size: var(--body-size);
- line-height: var(--lh); -webkit-font-smoothing: antialiased;
- }
- p { margin: var(--para-space) 0 0; }
- h1, h2, h3, h4, h5, h6 { font-family: var(--headings-face); font-weight: 700; line-height: 1.15; margin: var(--head-space) 0 0; }
- h1 { font-size: var(--headings-size); }
- h2 { font-size: calc(var(--headings-size) * 0.77); }
- h3 { font-size: calc(var(--body-size) + 1px); }
- h4, h5, h6 { font-family: var(--body-face); font-size: var(--body-size); font-weight: 700; }
- ul, ol { margin: var(--para-space) 0 0; padding-left: 1.6em; }
- li { margin: 0; }
- li > ul, li > ol { margin: 0; }
- pre { font-family: var(--code-face); font-size: var(--code-size); margin: var(--para-space) 0 0;
- padding: 8px 12px; border: 1px solid var(--hairline); border-radius: 6px; white-space: pre-wrap; }
- code { font-family: var(--code-face); font-size: var(--code-size); }
- blockquote { margin: var(--para-space) 0 0; padding-left: 14px; border-left: 1.5px solid var(--hairline); color: var(--muted); }
- blockquote p { margin: 0; }
- hr { border: none; border-top: 1px solid var(--hairline); margin: var(--head-space) 0 0; }
- a { color: var(--ink); text-decoration: underline; text-decoration-color: var(--hairline); text-underline-offset: 3px; }
- table { border-collapse: collapse; margin: var(--para-space) 0 0; }
- th, td { border: 1px solid var(--hairline); padding: 4px 10px; text-align: left; }
- figure { margin: var(--para-space) 0 0; }
- figure img { max-height: 1.6em; transition: max-height .25s ease; vertical-align: middle; }
- figure:hover img { max-height: 420px; }
- figcaption { display: none; }
- [data-source-line]:hover { background: rgba(0,122,255,.05); }
- """
+ /// CSS custom properties fed from the ProseTypography slots (#70 defaults) + flow knobs (#71).
+ static let css = """
+ :root {
+ --body-face: "Concourse OT", "Iowan Old Style", serif;
+ --body-size: 17px;
+ --headings-face: "Iowan Old Style", serif;
+ --headings-size: 26px;
+ --code-face: "UbuntuMono Nerd Font Mono", "UbuntuMonoNFM", monospace;
+ --code-size: 13px;
+ --lh: 1.25;
+ --para-space: 17px; /* 1 line */
+ --head-space: 34px; /* 2 lines */
+ --measure: 640px;
+ --ink: #1d1d1f; --muted: #6e6e73; --hairline: #d2d2d7;
+ }
+ html { background: #fbfbfd; }
+ body {
+ margin: 24px auto; padding: 0 24px; width: var(--measure); max-width: calc(100vw - 48px);
+ color: var(--ink); font-family: var(--body-face); font-size: var(--body-size);
+ line-height: var(--lh); -webkit-font-smoothing: antialiased;
+ }
+ p { margin: var(--para-space) 0 0; }
+ h1, h2, h3, h4, h5, h6 { font-family: var(--headings-face); font-weight: 700; line-height: 1.15; margin: var(--head-space) 0 0; }
+ h1 { font-size: var(--headings-size); }
+ h2 { font-size: calc(var(--headings-size) * 0.77); }
+ h3 { font-size: calc(var(--body-size) + 1px); }
+ h4, h5, h6 { font-family: var(--body-face); font-size: var(--body-size); font-weight: 700; }
+ ul, ol { margin: var(--para-space) 0 0; padding-left: 1.6em; }
+ li { margin: 0; }
+ li > ul, li > ol { margin: 0; }
+ pre { font-family: var(--code-face); font-size: var(--code-size); margin: var(--para-space) 0 0;
+ padding: 8px 12px; border: 1px solid var(--hairline); border-radius: 6px; white-space: pre-wrap; }
+ code { font-family: var(--code-face); font-size: var(--code-size); }
+ blockquote { margin: var(--para-space) 0 0; padding-left: 14px; border-left: 1.5px solid var(--hairline); color: var(--muted); }
+ blockquote p { margin: 0; }
+ hr { border: none; border-top: 1px solid var(--hairline); margin: var(--head-space) 0 0; }
+ a { color: var(--ink); text-decoration: underline; text-decoration-color: var(--hairline); text-underline-offset: 3px; }
+ table { border-collapse: collapse; margin: var(--para-space) 0 0; }
+ th, td { border: 1px solid var(--hairline); padding: 4px 10px; text-align: left; }
+ figure { margin: var(--para-space) 0 0; }
+ figure img { max-height: 1.6em; transition: max-height .25s ease; vertical-align: middle; }
+ figure:hover img { max-height: 420px; }
+ figcaption { display: none; }
+ [data-source-line]:hover { background: rgba(0,122,255,.05); }
+ """
- static func page(html: String) -> String {
- "\(html)"
- }
+ static func page(html: String) -> String {
+ "\(html)"
+ }
- // Mapping probes: click → source line; ⌘-click → open; scroll → top visible source line.
- static let probeJS = """
- function stamped(el){ return el.closest('[data-source-line]'); }
- document.addEventListener('click', function(e){
- const a = e.target.closest('a');
- if (a) {
- e.preventDefault(); // reading never navigates in-app
- if (e.metaKey || e.ctrlKey) window.webkit.messageHandlers.openLink.postMessage(a.href);
- else { const s = stamped(a); if (s) window.webkit.messageHandlers.sourceClick.postMessage(s.dataset.sourceLine); }
- return;
- }
- const s = stamped(e.target);
- if (s) window.webkit.messageHandlers.sourceClick.postMessage(s.dataset.sourceLine);
- }, true);
- let ticking = false;
- addEventListener('scroll', function(){
- if (ticking) return; ticking = true;
- requestAnimationFrame(function(){
- ticking = false;
- for (const el of document.querySelectorAll('[data-source-line]')) {
- const r = el.getBoundingClientRect();
- if (r.bottom > 44) { window.webkit.messageHandlers.sourceScroll.postMessage(el.dataset.sourceLine); return; }
- }
- });
- }, {passive: true});
- """
+ /// Mapping probes: click → source line; ⌘-click → open; scroll → top visible source line.
+ static let probeJS = """
+ function stamped(el){ return el.closest('[data-source-line]'); }
+ document.addEventListener('click', function(e){
+ const a = e.target.closest('a');
+ if (a) {
+ e.preventDefault(); // reading never navigates in-app
+ if (e.metaKey || e.ctrlKey) window.webkit.messageHandlers.openLink.postMessage(a.href);
+ else { const s = stamped(a); if (s) window.webkit.messageHandlers.sourceClick.postMessage(s.dataset.sourceLine); }
+ return;
+ }
+ const s = stamped(e.target);
+ if (s) window.webkit.messageHandlers.sourceClick.postMessage(s.dataset.sourceLine);
+ }, true);
+ let ticking = false;
+ addEventListener('scroll', function(){
+ if (ticking) return; ticking = true;
+ requestAnimationFrame(function(){
+ ticking = false;
+ for (const el of document.querySelectorAll('[data-source-line]')) {
+ const r = el.getBoundingClientRect();
+ if (r.bottom > 44) { window.webkit.messageHandlers.sourceScroll.postMessage(el.dataset.sourceLine); return; }
+ }
+ });
+ }, {passive: true});
+ """
- // @MainActor: WKNavigationDelegate + WKScriptMessageHandler requirements are MainActor in the SDK.
- @MainActor
- final class Coordinator: NSObject, WKNavigationDelegate, WKScriptMessageHandler {
- weak var webView: WKWebView?
- var loadedURL: URL?
- var paintStart: DispatchTime?
- var onStats: (Stats) -> Void
- var onSourceLine: (String, Int) -> Void
+ // @MainActor: WKNavigationDelegate + WKScriptMessageHandler requirements are MainActor in the SDK.
+ @MainActor
+ final class Coordinator: NSObject, WKNavigationDelegate, WKScriptMessageHandler {
+ weak var webView: WKWebView?
+ var loadedURL: URL?
+ var paintStart: DispatchTime?
+ var onStats: (Stats) -> Void
+ var onSourceLine: (String, Int) -> Void
- init(onStats: @escaping (Stats) -> Void, onSourceLine: @escaping (String, Int) -> Void) {
- self.onStats = onStats
- self.onSourceLine = onSourceLine
- }
+ init(onStats: @escaping (Stats) -> Void, onSourceLine: @escaping (String, Int) -> Void) {
+ self.onStats = onStats
+ self.onSourceLine = onSourceLine
+ }
- func webView(_ wv: WKWebView, didFinish: WKNavigation!) {
- if let t0 = paintStart {
- let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000
- onStats(Stats(paintMS: ms))
- }
- }
+ func webView(_: WKWebView, didFinish _: WKNavigation!) {
+ if let t0 = paintStart {
+ let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000
+ onStats(Stats(paintMS: ms))
+ }
+ }
- // Spike diagnostics: surface the silent-load failure path.
- func webView(_ wv: WKWebView, didFail na: WKNavigation!, withError error: Error) {
- FileHandle.standardError.write(Data("didFail: \(error)\n".utf8))
- }
+ /// Spike diagnostics: surface the silent-load failure path.
+ func webView(_: WKWebView, didFail _: WKNavigation!, withError error: Error) {
+ FileHandle.standardError.write(Data("didFail: \(error)\n".utf8))
+ }
- func webView(_ wv: WKWebView, didFailProvisionalNavigation na: WKNavigation!, withError error: Error) {
- FileHandle.standardError.write(Data("didFailProvisional: \(error)\n".utf8))
- }
+ func webView(_: WKWebView, didFailProvisionalNavigation _: WKNavigation!, withError error: Error) {
+ FileHandle.standardError.write(Data("didFailProvisional: \(error)\n".utf8))
+ }
- nonisolated func webViewWebContentProcessDidTerminate(_ wv: WKWebView) {
- FileHandle.standardError.write(Data("webContentProcessDidTerminate\n".utf8))
- }
+ nonisolated func webViewWebContentProcessDidTerminate(_: WKWebView) {
+ FileHandle.standardError.write(Data("webContentProcessDidTerminate\n".utf8))
+ }
- // Allow our own loadHTMLString (file:// baseURL / about:blank main frame); cancel the rest.
- // The initial load is a navigation too — a blanket .cancel kills the page before it paints.
- func webView(_ wv: WKWebView, decidePolicyFor na: WKNavigationAction,
- decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void) {
- if na.targetFrame?.isMainFrame == true,
- let u = na.request.url, u.scheme == "file" || u.absoluteString == "about:blank" {
- decisionHandler(.allow); return
- }
- if na.modifierFlags.contains(.command), let url = na.request.url, url.scheme?.hasPrefix("http") == true {
- NSWorkspace.shared.open(url)
- }
- decisionHandler(.cancel)
- }
+ /// Allow our own loadHTMLString (file:// baseURL / about:blank main frame); cancel the rest.
+ /// The initial load is a navigation too — a blanket .cancel kills the page before it paints.
+ func webView(_: WKWebView, decidePolicyFor na: WKNavigationAction,
+ decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void)
+ {
+ if na.targetFrame?.isMainFrame == true,
+ let u = na.request.url, u.scheme == "file" || u.absoluteString == "about:blank"
+ {
+ decisionHandler(.allow); return
+ }
+ if na.modifierFlags.contains(.command), let url = na.request.url, url.scheme?.hasPrefix("http") == true {
+ NSWorkspace.shared.open(url)
+ }
+ decisionHandler(.cancel)
+ }
- func userContentController(_ ucc: WKUserContentController, didReceive message: WKScriptMessage) {
- switch message.name {
- case "openLink":
- if let s = message.body as? String, let url = URL(string: s) { NSWorkspace.shared.open(url) }
- case "sourceClick", "sourceScroll":
- if let s = message.body as? String, let n = Int(s) { onSourceLine(message.name == "sourceClick" ? "click" : "top", n) }
- default: break
- }
- }
- }
+ func userContentController(_: WKUserContentController, didReceive message: WKScriptMessage) {
+ switch message.name {
+ case "openLink":
+ if let s = message.body as? String, let url = URL(string: s) {
+ NSWorkspace.shared.open(url)
+ }
+ case "sourceClick", "sourceScroll":
+ if let s = message.body as? String, let n = Int(s) {
+ onSourceLine(message.name == "sourceClick" ? "click" : "top", n)
+ }
+ default: break
+ }
+ }
+ }
- func makeCoordinator() -> Coordinator { Coordinator(onStats: onStats, onSourceLine: onSourceLine) }
+ func makeCoordinator() -> Coordinator {
+ Coordinator(onStats: onStats, onSourceLine: onSourceLine)
+ }
}
// MARK: - Shell
@main
struct SpikeApp: App {
- @NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
- var body: some Scene {
- Window("Spike — apex HTML reading", id: "main") {
- ContentView()
- .frame(minWidth: 960, minHeight: 720)
- .onAppear { NSApp.activate(ignoringOtherApps: true) }
- }
- }
+ @NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
+ var body: some Scene {
+ Window("Spike — apex HTML reading", id: "main") {
+ ContentView()
+ .frame(minWidth: 960, minHeight: 720)
+ .onAppear { NSApp.activate(ignoringOtherApps: true) }
+ }
+ }
- // ponytail: one runnable check for the mapping logic — `swift run ApexHTMLSpike --check`
- init() {
- let args = CommandLine.arguments
- if args.contains("--check") { Self.selfCheck(); exit(0) }
- if let i = args.firstIndex(of: "--pipeline"), args.count > i + 1 { Self.pipeline(path: args[i + 1]); exit(0) }
- }
+ // ponytail: one runnable check for the mapping logic — `swift run ApexHTMLSpike --check`
+ init() {
+ let args = CommandLine.arguments
+ if args.contains("--check") {
+ Self.selfCheck(); exit(0)
+ }
+ if let i = args.firstIndex(of: "--pipeline"), args.count > i + 1 {
+ Self.pipeline(path: args[i + 1]); exit(0)
+ }
+ }
- /// Headless end-to-end: chunk → apex → stamp → validate coverage. Prints per-file numbers.
- static func pipeline(path: String) {
- let url = URL(fileURLWithPath: path)
- guard let source = try? String(contentsOf: url, encoding: .utf8) else { print("unreadable: \(path)"); exit(1) }
- let lines = source.split(separator: "\n", omittingEmptySubsequences: false) as [Substring]
- do {
- let (html, ms) = try Apex.render(MarkdownChunker.stamp(source), baseDir: url.deletingLastPathComponent())
- let stamped = HTMLStamper.stamp(html)
- // coverage: every data-source-line points at a non-blank source line
- let re = try NSRegularExpression(pattern: #"data-source-line="(\d+)""#)
- var bad = 0, count = 0, lineSum = 0
- re.enumerateMatches(in: stamped, range: NSMakeRange(0, (stamped as NSString).length)) { m, _, _ in
- guard let m else { return }
- let n = Int((stamped as NSString).substring(with: m.range(at: 1)))!
- count += 1; lineSum += n
- let idx = n - 1
- if idx < 0 || idx >= lines.count || lines[idx].allSatisfy({ $0 == " " || $0 == "\t" || $0 == "\r" }) { bad += 1 }
- }
- print("\(url.lastPathComponent): apex \(String(format: "%.1f", ms)) ms, html \(html.utf8.count) B, \(count) blocks stamped, \(bad) mis-stamped, avg line \(count > 0 ? lineSum / count : 0)")
- exit(bad == 0 ? 0 : 2)
- } catch {
- print("apex failed: \(error)"); exit(1)
- }
- }
+ /// Headless end-to-end: chunk → apex → stamp → validate coverage. Prints per-file numbers.
+ static func pipeline(path: String) {
+ let url = URL(fileURLWithPath: path)
+ guard let source = try? String(contentsOf: url, encoding: .utf8) else { print("unreadable: \(path)"); exit(1) }
+ let lines = source.split(separator: "\n", omittingEmptySubsequences: false) as [Substring]
+ do {
+ let (html, ms) = try Apex.render(MarkdownChunker.stamp(source), baseDir: url.deletingLastPathComponent())
+ let stamped = HTMLStamper.stamp(html)
+ // coverage: every data-source-line points at a non-blank source line
+ let re = try NSRegularExpression(pattern: #"data-source-line="(\d+)""#)
+ var bad = 0, count = 0, lineSum = 0
+ re.enumerateMatches(in: stamped, range: NSMakeRange(0, (stamped as NSString).length)) { m, _, _ in
+ guard let m else { return }
+ let n = Int((stamped as NSString).substring(with: m.range(at: 1)))!
+ count += 1; lineSum += n
+ let idx = n - 1
+ if idx < 0 || idx >= lines.count || lines[idx].allSatisfy({ $0 == " " || $0 == "\t" || $0 == "\r" }) {
+ bad += 1
+ }
+ }
+ print("\(url.lastPathComponent): apex \(String(format: "%.1f", ms)) ms, html \(html.utf8.count) B, \(count) blocks stamped, \(bad) mis-stamped, avg line \(count > 0 ? lineSum / count : 0)")
+ exit(bad == 0 ? 0 : 2)
+ } catch {
+ print("apex failed: \(error)"); exit(1)
+ }
+ }
- static func selfCheck() {
- // chunker: sentinels before chunks, blank structure preserved
- let md = "# T\n\nA\n\nB\n1. x\n\n\nC"
- let stamped = MarkdownChunker.stamp(md)
- assert(stamped == "\n# T\n\n\nA\n\n\nB\n1. x\n\n\nC", stamped)
- // stamper: sentinel → attribute on following element; multi-digit lines
- let html = "T
\n\nA
\n\n"
- let out = HTMLStamper.stamp(html)
- assert(out == "T
\nA
\n", out)
- print("self-check OK")
- }
+ static func selfCheck() {
+ // chunker: sentinels before chunks, blank structure preserved
+ let md = "# T\n\nA\n\nB\n1. x\n\n\nC"
+ let stamped = MarkdownChunker.stamp(md)
+ assert(stamped == "\n# T\n\n\nA\n\n\nB\n1. x\n\n\nC", stamped)
+ // stamper: sentinel → attribute on following element; multi-digit lines
+ let html = "T
\n\nA
\n\n"
+ let out = HTMLStamper.stamp(html)
+ assert(out == "T
\nA
\n", out)
+ print("self-check OK")
+ }
}
final class AppDelegate: NSObject, NSApplicationDelegate {
- nonisolated func applicationDidFinishLaunching(_ n: Notification) {}
+ nonisolated func applicationDidFinishLaunching(_: Notification) {}
}
struct ContentView: View {
- @State private var files: [URL] = []
- @State private var selected: URL?
- @State private var stats = ReadingWebView.Stats()
- @State private var clickedLine: Int?
- @State private var topLine: Int?
+ @State private var files: [URL] = []
+ @State private var selected: URL?
+ @State private var stats = ReadingWebView.Stats()
+ @State private var clickedLine: Int?
+ @State private var topLine: Int?
- var body: some View {
- Group {
- if files.isEmpty {
- Text("pass a corpus .md path (or use Open…)").padding()
- } else {
- HStack(spacing: 0) {
- List(selection: $selected) {
- ForEach(files, id: \.self) { f in
- Text(f.deletingPathExtension().lastPathComponent).tag(f)
- }
- }
- .listStyle(.sidebar).frame(width: 220)
- Divider()
- if let sel = selected {
- // No .id(sel) remount: ONE WKWebView, reloaded in place. Remounting per
- // document re-spawns the web view (~hundreds of ms) and blanks the pane —
- // the dominant switch cost, far bigger than apex itself.
- ReadingWebView(fileURL: sel, onStats: { s in
- if s.apexMS > 0 || s.error != nil { stats = s } else { stats.paintMS = s.paintMS }
- }, onSourceLine: { kind, line in
- if kind == "click" { clickedLine = line } else { topLine = line }
- })
- } else { Text("pick a post").frame(maxWidth: .infinity) }
- }
- }
- }
- .safeAreaInset(edge: .bottom) { statsBar }
- .toolbar {
- Button("Open…") { openPanel() }
- if let apex = Apex.binaryPath() { Text("apex: \(apex)") }
- }
- .onAppear { load(arg: CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : nil) }
- }
+ var body: some View {
+ Group {
+ if files.isEmpty {
+ Text("pass a corpus .md path (or use Open…)").padding()
+ } else {
+ HStack(spacing: 0) {
+ List(selection: $selected) {
+ ForEach(files, id: \.self) { f in
+ Text(f.deletingPathExtension().lastPathComponent).tag(f)
+ }
+ }
+ .listStyle(.sidebar).frame(width: 220)
+ Divider()
+ if let sel = selected {
+ // No .id(sel) remount: ONE WKWebView, reloaded in place. Remounting per
+ // document re-spawns the web view (~hundreds of ms) and blanks the pane —
+ // the dominant switch cost, far bigger than apex itself.
+ ReadingWebView(fileURL: sel, onStats: { s in
+ if s.apexMS > 0 || s.error != nil {
+ stats = s
+ } else {
+ stats.paintMS = s.paintMS
+ }
+ }, onSourceLine: { kind, line in
+ if kind == "click" {
+ clickedLine = line
+ } else {
+ topLine = line
+ }
+ })
+ } else {
+ Text("pick a post").frame(maxWidth: .infinity)
+ }
+ }
+ }
+ }
+ .safeAreaInset(edge: .bottom) { statsBar }
+ .toolbar {
+ Button("Open…") { openPanel() }
+ if let apex = Apex.binaryPath() {
+ Text("apex: \(apex)")
+ }
+ }
+ .onAppear { load(arg: CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : nil) }
+ }
- private var statsBar: some View {
- HStack(spacing: 16) {
- Text(selected?.lastPathComponent ?? "—").lineLimit(1).truncationMode(.middle)
- Text(String(format: "apex %.0f ms", stats.apexMS))
- Text(String(format: "paint %.0f ms", stats.paintMS))
- Text(ByteCountFormatter.string(fromByteCount: Int64(stats.htmlBytes), countStyle: .file))
- if let t = topLine { Text("top src line \(t)") }
- if let c = clickedLine { Text("click → src line \(c)") }
- if let e = stats.error { Text(e).foregroundStyle(.red).lineLimit(1) }
- Spacer()
- }
- .font(.system(size: 11, design: .monospaced)).padding(6)
- .background(.bar)
- }
+ private var statsBar: some View {
+ HStack(spacing: 16) {
+ Text(selected?.lastPathComponent ?? "—").lineLimit(1).truncationMode(.middle)
+ Text(String(format: "apex %.0f ms", stats.apexMS))
+ Text(String(format: "paint %.0f ms", stats.paintMS))
+ Text(ByteCountFormatter.string(fromByteCount: Int64(stats.htmlBytes), countStyle: .file))
+ if let t = topLine {
+ Text("top src line \(t)")
+ }
+ if let c = clickedLine {
+ Text("click → src line \(c)")
+ }
+ if let e = stats.error {
+ Text(e).foregroundStyle(.red).lineLimit(1)
+ }
+ Spacer()
+ }
+ .font(.system(size: 11, design: .monospaced)).padding(6)
+ .background(.bar)
+ }
- private func load(arg: String?) {
- if let a = arg {
- let u = URL(fileURLWithPath: a).standardizedFileURL
- files = (try? FileManager.default.contentsOfDirectory(
- at: u.deletingLastPathComponent(), includingPropertiesForKeys: nil
- ).filter { $0.pathExtension == "md" }.sorted { $0.lastPathComponent < $1.lastPathComponent }) ?? [u]
- selected = files.first(where: { $0 == u }) ?? u
- } else if let dir = URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent("../prose") as URL?,
- let list = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil) {
- files = list.filter { $0.pathExtension == "md" }.sorted { $0.lastPathComponent < $1.lastPathComponent }
- selected = files.first
- }
- }
+ private func load(arg: String?) {
+ if let a = arg {
+ let u = URL(fileURLWithPath: a).standardizedFileURL
+ files = (try? FileManager.default.contentsOfDirectory(
+ at: u.deletingLastPathComponent(), includingPropertiesForKeys: nil,
+ ).filter { $0.pathExtension == "md" }.sorted { $0.lastPathComponent < $1.lastPathComponent }) ?? [u]
+ selected = files.first(where: { $0 == u }) ?? u
+ } else if let dir = URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent("../prose") as URL?,
+ let list = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)
+ {
+ files = list.filter { $0.pathExtension == "md" }.sorted { $0.lastPathComponent < $1.lastPathComponent }
+ selected = files.first
+ }
+ }
- private func openPanel() {
- let p = NSOpenPanel(); p.allowsMultipleSelection = false; p.canChooseDirectories = false
- p.allowedContentTypes = [.init(filenameExtension: "md")!]
- if p.runModal() == .OK, let u = p.url { files.append(u); selected = u }
- }
+ private func openPanel() {
+ let p = NSOpenPanel(); p.allowsMultipleSelection = false; p.canChooseDirectories = false
+ p.allowedContentTypes = [.init(filenameExtension: "md")!]
+ if p.runModal() == .OK, let u = p.url {
+ files.append(u); selected = u
+ }
+ }
}
diff --git a/spike/blocks/Package.swift b/spike/blocks/Package.swift
index 89431fb..518a8ba 100644
--- a/spike/blocks/Package.swift
+++ b/spike/blocks/Package.swift
@@ -2,7 +2,7 @@
import PackageDescription
let package = Package(
- name: "BlocksSpike",
- platforms: [.macOS(.v26)],
- targets: [.executableTarget(name: "BlocksSpike")]
+ name: "BlocksSpike",
+ platforms: [.macOS(.v26)],
+ targets: [.executableTarget(name: "BlocksSpike")],
)
diff --git a/spike/blocks/Sources/BlocksSpike/BlockModel.swift b/spike/blocks/Sources/BlocksSpike/BlockModel.swift
index f887b9e..86809f3 100644
--- a/spike/blocks/Sources/BlocksSpike/BlockModel.swift
+++ b/spike/blocks/Sources/BlocksSpike/BlockModel.swift
@@ -5,80 +5,88 @@
import Foundation
struct Block: Identifiable, Equatable {
- var id = UUID()
- var raw: String // markdown source incl. marker; kind is derived, never stored
+ var id = UUID()
+ var raw: String // markdown source incl. marker; kind is derived, never stored
}
nonisolated enum BlockModel {
- enum Kind { case heading1, heading2, paragraph, quote, hr }
+ enum Kind { case heading1, heading2, paragraph, quote, hr }
- /// Blank-line split — identical strategy to Spike B's readingBlocks, so the
- /// spikes differ by substrate, not by parse. ponytail: no AST, no lists/setext (corpus has none, #51).
- static func parse(_ md: String) -> [Block] {
- md.components(separatedBy: "\n\n")
- .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
- .filter { !$0.isEmpty }
- .map { Block(raw: $0) }
- }
+ /// Blank-line split — identical strategy to Spike B's readingBlocks, so the
+ /// spikes differ by substrate, not by parse. ponytail: no AST, no lists/setext (corpus has none, #51).
+ static func parse(_ md: String) -> [Block] {
+ md.components(separatedBy: "\n\n")
+ .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
+ .filter { !$0.isEmpty }
+ .map { Block(raw: $0) }
+ }
- static func kind(of raw: String) -> Kind {
- if raw.hasPrefix("## ") { return .heading2 }
- if raw.hasPrefix("# ") { return .heading1 }
- if raw.hasPrefix("> ") { return .quote }
- if raw.count <= 6, !raw.isEmpty, raw.allSatisfy({ $0 == "*" || $0 == "-" || $0 == "_" || $0.isWhitespace }) { return .hr }
- return .paragraph
- }
+ static func kind(of raw: String) -> Kind {
+ if raw.hasPrefix("## ") {
+ return .heading2
+ }
+ if raw.hasPrefix("# ") {
+ return .heading1
+ }
+ if raw.hasPrefix("> ") {
+ return .quote
+ }
+ if raw.count <= 6, !raw.isEmpty, raw.allSatisfy({ $0 == "*" || $0 == "-" || $0 == "_" || $0.isWhitespace }) {
+ return .hr
+ }
+ return .paragraph
+ }
- /// Rendered text: marker stripped, inline markdown parsed (inline-only — block
- /// structure is ours, exactly like Spike B's reading mode).
- static func rendered(_ raw: String) -> AttributedString {
- var p = raw
- let k = kind(of: raw)
- switch k {
- case .heading1: p = String(p.dropFirst(2))
- case .heading2: p = String(p.dropFirst(3))
- case .quote: p = String(p.dropFirst(2))
- case .hr: return AttributedString("⁂")
- case .paragraph: break
- }
- var opts = AttributedString.MarkdownParsingOptions()
- opts.interpretedSyntax = .inlineOnlyPreservingWhitespace
- return (try? AttributedString(markdown: p, options: opts)) ?? AttributedString(p)
- }
+ /// Rendered text: marker stripped, inline markdown parsed (inline-only — block
+ /// structure is ours, exactly like Spike B's reading mode).
+ static func rendered(_ raw: String) -> AttributedString {
+ var p = raw
+ let k = kind(of: raw)
+ switch k {
+ case .heading1: p = String(p.dropFirst(2))
+ case .heading2: p = String(p.dropFirst(3))
+ case .quote: p = String(p.dropFirst(2))
+ case .hr: return AttributedString("⁂")
+ case .paragraph: break
+ }
+ var opts = AttributedString.MarkdownParsingOptions()
+ opts.interpretedSyntax = .inlineOnlyPreservingWhitespace
+ return (try? AttributedString(markdown: p, options: opts)) ?? AttributedString(p)
+ }
- /// Marker-stripped plain text (anchor search runs over this).
- static func plainText(_ raw: String) -> String {
- switch kind(of: raw) {
- case .heading1: return String(raw.dropFirst(2))
- case .heading2: return String(raw.dropFirst(3))
- case .quote: return String(raw.dropFirst(2))
- case .hr: return ""
- case .paragraph: return raw
- }
- }
+ /// Marker-stripped plain text (anchor search runs over this).
+ static func plainText(_ raw: String) -> String {
+ switch kind(of: raw) {
+ case .heading1: String(raw.dropFirst(2))
+ case .heading2: String(raw.dropFirst(3))
+ case .quote: String(raw.dropFirst(2))
+ case .hr: ""
+ case .paragraph: raw
+ }
+ }
- /// Within-block UTF-16 range of `quote` (word-tokenized, whitespace-tolerant — same
- /// strategy as Spike B's anchorRange, scoped to one block). nil = stale.
- static func anchorRange(of quote: String, in raw: String) -> NSRange? {
- let text = plainText(raw)
- let textWords = words(text), 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
- return NSRange(location: text.utf16.distance(from: text.startIndex, to: from),
- length: text.utf16.distance(from: from, to: to))
- }
- }
- return nil
- }
+ /// Within-block UTF-16 range of `quote` (word-tokenized, whitespace-tolerant — same
+ /// strategy as Spike B's anchorRange, scoped to one block). nil = stale.
+ static func anchorRange(of quote: String, in raw: String) -> NSRange? {
+ let text = plainText(raw)
+ let textWords = words(text), 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
+ return NSRange(location: text.utf16.distance(from: text.startIndex, to: from),
+ length: text.utf16.distance(from: from, to: to))
+ }
+ }
+ return nil
+ }
- private struct Word { let norm: String; let range: Range }
- 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)
- }
- }
+ private struct Word { let norm: String; let range: Range }
+ 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/blocks/Sources/BlocksSpike/SpikeApp.swift b/spike/blocks/Sources/BlocksSpike/SpikeApp.swift
index ec24119..b8f1cab 100644
--- a/spike/blocks/Sources/BlocksSpike/SpikeApp.swift
+++ b/spike/blocks/Sources/BlocksSpike/SpikeApp.swift
@@ -6,345 +6,365 @@ import SwiftUI
@main
struct SpikeApp: App {
- @NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
- var body: some Scene {
- Window("Spike C — Blocks", id: "main") {
- ContentView()
- .frame(minWidth: 900, minHeight: 640)
- .onAppear { NSApp.activate(ignoringOtherApps: true) }
- }
- .windowStyle(.hiddenTitleBar)
- }
+ @NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
+ var body: some Scene {
+ Window("Spike C — Blocks", id: "main") {
+ ContentView()
+ .frame(minWidth: 900, minHeight: 640)
+ .onAppear { NSApp.activate(ignoringOtherApps: true) }
+ }
+ .windowStyle(.hiddenTitleBar)
+ }
- // ponytail: one runnable check — `swift run --package-path spike/blocks --check`
- init() {
- if CommandLine.arguments.contains("--check") { Self.selfCheck(); exit(0) }
- }
+ // ponytail: one runnable check — `swift run --package-path spike/blocks --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 blocks = BlockModel.parse(text)
- assert(blocks.count > 10, "FAIL: parse produced \(blocks.count) blocks")
- assert(BlockModel.kind(of: blocks[0].raw) == .heading2, "FAIL: first block not a heading (## in corpus)")
- let kinds = blocks.map { BlockModel.kind(of: $0.raw) }
- assert(kinds.contains(.heading2), "FAIL: no ## blocks")
- assert(kinds.contains(.hr), "FAIL: corpus hr (* * *) not detected")
- // rendered text must hide block markup
- let rendered = blocks.map { String(BlockModel.rendered($0.raw).characters) }
- assert(rendered.allSatisfy { !$0.hasPrefix("# ") && !$0.hasPrefix("## ") && !$0.hasPrefix("> ") },
- "FAIL: markup leaked into rendered view")
- assert(rendered.contains { $0.contains("expected value") }, "FAIL: body text missing")
- // anchor feasibility: block containing the DM quote
- let anchor = ContentView.findAnchorBlock(quote: "“I'm not too sure that many people will compete. So, the expected value of joining is actually pretty high.”", in: blocks)
- assert(anchor != nil, "FAIL: anchor block not found")
- // within-block range feasibility: same word search as Spike B, scoped to one block
- if let a = anchor {
- let r = BlockModel.anchorRange(of: "the expected value of joining", in: a.raw)
- assert(r != nil, "FAIL: within-block anchor range")
- }
- // paste-split: multi-paragraph raw splits into blocks
- assert(BlockModel.parse("one\n\ntwo\n\nthree").count == 3, "FAIL: paste-split")
- // perf: block-ify PERF-3k
- let perf = (try? String(contentsOfFile: "spike/prose/PERF-3k.md", encoding: .utf8)) ?? text
- var ms = 0.0
- for _ in 0..<3 {
- let t0 = DispatchTime.now()
- _ = BlockModel.parse(perf)
- ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6
- }
- print("PASS: \(blocks.count) blocks; anchor block found; PERF-3k block-ify \(String(format: "%.1f", ms)) ms")
- }
+ static func selfCheck() {
+ let text = try! String(contentsOfFile: "spike/prose/the-expected-value-of-showing.md", encoding: .utf8)
+ let blocks = BlockModel.parse(text)
+ assert(blocks.count > 10, "FAIL: parse produced \(blocks.count) blocks")
+ assert(BlockModel.kind(of: blocks[0].raw) == .heading2, "FAIL: first block not a heading (## in corpus)")
+ let kinds = blocks.map { BlockModel.kind(of: $0.raw) }
+ assert(kinds.contains(.heading2), "FAIL: no ## blocks")
+ assert(kinds.contains(.hr), "FAIL: corpus hr (* * *) not detected")
+ // rendered text must hide block markup
+ let rendered = blocks.map { String(BlockModel.rendered($0.raw).characters) }
+ assert(rendered.allSatisfy { !$0.hasPrefix("# ") && !$0.hasPrefix("## ") && !$0.hasPrefix("> ") },
+ "FAIL: markup leaked into rendered view")
+ assert(rendered.contains { $0.contains("expected value") }, "FAIL: body text missing")
+ // anchor feasibility: block containing the DM quote
+ let anchor = ContentView.findAnchorBlock(quote: "“I'm not too sure that many people will compete. So, the expected value of joining is actually pretty high.”", in: blocks)
+ assert(anchor != nil, "FAIL: anchor block not found")
+ // within-block range feasibility: same word search as Spike B, scoped to one block
+ if let a = anchor {
+ let r = BlockModel.anchorRange(of: "the expected value of joining", in: a.raw)
+ assert(r != nil, "FAIL: within-block anchor range")
+ }
+ // paste-split: multi-paragraph raw splits into blocks
+ assert(BlockModel.parse("one\n\ntwo\n\nthree").count == 3, "FAIL: paste-split")
+ // perf: block-ify PERF-3k
+ let perf = (try? String(contentsOfFile: "spike/prose/PERF-3k.md", encoding: .utf8)) ?? text
+ var ms = 0.0
+ for _ in 0 ..< 3 {
+ let t0 = DispatchTime.now()
+ _ = BlockModel.parse(perf)
+ ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6
+ }
+ print("PASS: \(blocks.count) blocks; anchor block found; PERF-3k block-ify \(String(format: "%.1f", ms)) ms")
+ }
}
// MARK: - Content
struct ContentView: View {
- @State private var blocks: [Block]
- @State private var focusedID: UUID?
- @State private var anchorID: UUID?
- @State private var staleShown = false
- @State private var loadMs: Double = 0
- @State private var hint = "Click a block to edit its source. Enter splits, ⌫ at start merges. IME probe: type ⌥U a in a block."
+ @State private var blocks: [Block]
+ @State private var focusedID: UUID?
+ @State private var anchorID: UUID?
+ @State private var staleShown = false
+ @State private var loadMs: Double = 0
+ @State private var hint = "Click a block to edit its source. Enter splits, ⌫ at start merges. IME probe: type ⌥U a in a block."
- init() {
- let args = CommandLine.arguments
- let arg = args.count > 1 && args[1] != "--check" ? args[1] : nil
- let t = Self.loadCorpus(arg)
- let t0 = DispatchTime.now()
- _blocks = State(initialValue: BlockModel.parse(t))
- _loadMs = State(initialValue: Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6)
- }
+ init() {
+ let args = CommandLine.arguments
+ let arg = args.count > 1 && args[1] != "--check" ? args[1] : nil
+ let t = Self.loadCorpus(arg)
+ let t0 = DispatchTime.now()
+ _blocks = State(initialValue: BlockModel.parse(t))
+ _loadMs = State(initialValue: Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6)
+ }
- /// Arg as given, then the default piece (run.sh passes absolute paths).
- static func loadCorpus(_ arg: String?) -> String {
- for c in [arg, "spike/prose/the-expected-value-of-showing.md"].compactMap({ $0 }) {
- if let s = try? String(contentsOfFile: c, encoding: .utf8) { return s }
- }
- return "# Spike C\n\n(No corpus file found — run from repo root.)"
- }
+ /// Arg as given, then the default piece (run.sh passes absolute paths).
+ static func loadCorpus(_ arg: String?) -> String {
+ for c in [arg, "spike/prose/the-expected-value-of-showing.md"].compactMap(\.self) {
+ if let s = try? String(contentsOfFile: c, encoding: .utf8) {
+ return s
+ }
+ }
+ return "# Spike C\n\n(No corpus file found — run from repo root.)"
+ }
- var body: some View {
- VStack(spacing: 0) {
- bar
- Divider()
- ScrollViewReader { proxy in
- ScrollView([.vertical]) {
- LazyVStack(alignment: .leading, spacing: 18) {
- ForEach(blocks) { block in
- BlockRow(
- block: block,
- isFocused: focusedID == block.id,
- isAnchored: anchorID == block.id,
- onEdit: { raw in edit(block.id, raw: raw) },
- onSplit: { at in split(block.id, at: at) },
- onMerge: { merge(block.id) },
- onFocus: {
- focusedID = block.id
- hint = "Focused block \(block.id.uuidString.prefix(4)) — type to edit."
- }
- )
- .id(block.id)
- }
- }
- .frame(maxWidth: 720, alignment: .leading)
- .padding(.horizontal, 40)
- .padding(.vertical, 24)
- .onChange(of: anchorID) { id in
- if let id { proxy.scrollTo(id, anchor: .center) }
- }
- }
- }
- Divider()
- Text(hint).font(.caption).foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading)
- .padding(.horizontal, 16).padding(.vertical, 6)
- }
- .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.")
- }
- }
+ var body: some View {
+ VStack(spacing: 0) {
+ bar
+ Divider()
+ ScrollViewReader { proxy in
+ ScrollView([.vertical]) {
+ LazyVStack(alignment: .leading, spacing: 18) {
+ ForEach(blocks) { block in
+ BlockRow(
+ block: block,
+ isFocused: focusedID == block.id,
+ isAnchored: anchorID == block.id,
+ onEdit: { raw in edit(block.id, raw: raw) },
+ onSplit: { at in split(block.id, at: at) },
+ onMerge: { merge(block.id) },
+ onFocus: {
+ focusedID = block.id
+ hint = "Focused block \(block.id.uuidString.prefix(4)) — type to edit."
+ },
+ )
+ .id(block.id)
+ }
+ }
+ .frame(maxWidth: 720, alignment: .leading)
+ .padding(.horizontal, 40)
+ .padding(.vertical, 24)
+ .onChange(of: anchorID) { id in
+ if let id {
+ proxy.scrollTo(id, anchor: .center)
+ }
+ }
+ }
+ }
+ Divider()
+ Text(hint).font(.caption).foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading)
+ .padding(.horizontal, 16).padding(.vertical, 6)
+ }
+ .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) {
- 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 anchorID != nil { Text("anchored").foregroundStyle(.secondary).font(.caption) }
- Spacer()
- Text("load \(String(format: "%.1f", loadMs)) ms · \(blocks.count) blocks").foregroundStyle(.secondary).font(.caption)
- }
- .padding(.horizontal, 16)
- .padding(.vertical, 8)
- }
+ private var bar: some View {
+ HStack(spacing: 12) {
+ 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 anchorID != nil {
+ Text("anchored").foregroundStyle(.secondary).font(.caption)
+ }
+ Spacer()
+ Text("load \(String(format: "%.1f", loadMs)) ms · \(blocks.count) blocks").foregroundStyle(.secondary).font(.caption)
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 8)
+ }
- // MARK: block ops
+ // MARK: block ops
- private func edit(_ id: UUID, raw: String) {
- guard let i = blocks.firstIndex(where: { $0.id == id }) else { return }
- // paste-split: multi-paragraph raw explodes into blocks at the same position
- if raw.contains("\n\n") {
- let parts = BlockModel.parse(raw)
- guard !parts.isEmpty else { return }
- blocks.replaceSubrange(i ... i, with: parts)
- focusedID = parts[parts.count - 1].id
- } else {
- blocks[i].raw = raw
- }
- }
+ private func edit(_ id: UUID, raw: String) {
+ guard let i = blocks.firstIndex(where: { $0.id == id }) else { return }
+ // paste-split: multi-paragraph raw explodes into blocks at the same position
+ if raw.contains("\n\n") {
+ let parts = BlockModel.parse(raw)
+ guard !parts.isEmpty else { return }
+ blocks.replaceSubrange(i ... i, with: parts)
+ focusedID = parts[parts.count - 1].id
+ } else {
+ blocks[i].raw = raw
+ }
+ }
- private func split(_ id: UUID, at location: Int) {
- guard let i = blocks.firstIndex(where: { $0.id == id }) else { return }
- let ns = blocks[i].raw as NSString
- let loc = max(0, min(location, ns.length))
- let before = ns.substring(to: loc).trimmingCharacters(in: .whitespacesAndNewlines)
- let after = ns.substring(from: loc).trimmingCharacters(in: .whitespacesAndNewlines)
- blocks[i].raw = before
- blocks.insert(Block(raw: after), at: i + 1)
- focusedID = blocks[i + 1].id
- }
+ private func split(_ id: UUID, at location: Int) {
+ guard let i = blocks.firstIndex(where: { $0.id == id }) else { return }
+ let ns = blocks[i].raw as NSString
+ let loc = max(0, min(location, ns.length))
+ let before = ns.substring(to: loc).trimmingCharacters(in: .whitespacesAndNewlines)
+ let after = ns.substring(from: loc).trimmingCharacters(in: .whitespacesAndNewlines)
+ blocks[i].raw = before
+ blocks.insert(Block(raw: after), at: i + 1)
+ focusedID = blocks[i + 1].id
+ }
- private func merge(_ id: UUID) {
- guard let i = blocks.firstIndex(where: { $0.id == id }), i > 0 else { return }
- blocks[i - 1].raw += " " + blocks[i].raw
- blocks.remove(at: i)
- focusedID = blocks[i - 1].id
- }
+ private func merge(_ id: UUID) {
+ guard let i = blocks.firstIndex(where: { $0.id == id }), i > 0 else { return }
+ blocks[i - 1].raw += " " + blocks[i].raw
+ blocks.remove(at: i)
+ focusedID = blocks[i - 1].id
+ }
- // MARK: anchor (block-granular Fix-Card feasibility)
+ // MARK: anchor (block-granular Fix-Card feasibility)
- static func findAnchorBlock(quote: String, in blocks: [Block]) -> Block? {
- let qw = normWords(quote)
- guard !qw.isEmpty else { return nil }
- for b in blocks {
- let bw = normWords(BlockModel.plainText(b.raw))
- guard bw.count >= qw.count else { continue }
- if (0 ... bw.count - qw.count).contains(where: { s in
- (s ..< s + qw.count).allSatisfy { bw[$0] == qw[$0 - s] }
- }) { return b }
- }
- return nil
- }
+ static func findAnchorBlock(quote: String, in blocks: [Block]) -> Block? {
+ let qw = normWords(quote)
+ guard !qw.isEmpty else { return nil }
+ for b in blocks {
+ let bw = normWords(BlockModel.plainText(b.raw))
+ guard bw.count >= qw.count else { continue }
+ if (0 ... bw.count - qw.count).contains(where: { s in
+ (s ..< s + qw.count).allSatisfy { bw[$0] == qw[$0 - s] }
+ }) {
+ return b
+ }
+ }
+ return nil
+ }
- static func normWords(_ s: String) -> [String] {
- s.split(whereSeparator: \.isWhitespace).map { $0.lowercased().trimmingCharacters(in: .punctuationCharacters) }
- }
+ static func normWords(_ s: String) -> [String] {
+ s.split(whereSeparator: \.isWhitespace).map { $0.lowercased().trimmingCharacters(in: .punctuationCharacters) }
+ }
- private func applyAnchor(_ quote: String) {
- let t0 = DispatchTime.now()
- let hit = ContentView.findAnchorBlock(quote: quote, in: blocks)
- loadMs = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6
- if let hit {
- anchorID = hit.id
- } else {
- anchorID = nil
- staleShown = true
- }
- }
+ private func applyAnchor(_ quote: String) {
+ let t0 = DispatchTime.now()
+ let hit = ContentView.findAnchorBlock(quote: quote, in: blocks)
+ loadMs = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6
+ if let hit {
+ anchorID = hit.id
+ } else {
+ anchorID = nil
+ staleShown = true
+ }
+ }
}
// MARK: - One block: rendered, or raw source when focused
private struct BlockRow: View {
- let block: Block
- let isFocused: Bool
- let isAnchored: Bool
- let onEdit: (String) -> Void
- let onSplit: (Int) -> Void
- let onMerge: () -> Void
- let onFocus: () -> Void
- @State private var raw: String
+ let block: Block
+ let isFocused: Bool
+ let isAnchored: Bool
+ let onEdit: (String) -> Void
+ let onSplit: (Int) -> Void
+ let onMerge: () -> Void
+ let onFocus: () -> Void
+ @State private var raw: String
- init(block: Block, isFocused: Bool, isAnchored: Bool,
- onEdit: @escaping (String) -> Void, onSplit: @escaping (Int) -> Void,
- onMerge: @escaping () -> Void, onFocus: @escaping () -> Void) {
- self.block = block
- self.isFocused = isFocused
- self.isAnchored = isAnchored
- self.onEdit = onEdit
- self.onSplit = onSplit
- self.onMerge = onMerge
- self.onFocus = onFocus
- _raw = State(initialValue: block.raw)
- }
+ init(block: Block, isFocused: Bool, isAnchored: Bool,
+ onEdit: @escaping (String) -> Void, onSplit: @escaping (Int) -> Void,
+ onMerge: @escaping () -> Void, onFocus: @escaping () -> Void)
+ {
+ self.block = block
+ self.isFocused = isFocused
+ self.isAnchored = isAnchored
+ self.onEdit = onEdit
+ self.onSplit = onSplit
+ self.onMerge = onMerge
+ self.onFocus = onFocus
+ _raw = State(initialValue: block.raw)
+ }
- var body: some View {
- Group {
- if isFocused {
- SingleBlockEditor(text: $raw, onEdit: onEdit, onSplit: onSplit, onMerge: onMerge)
- .frame(height: max(28, SingleBlockEditor.height(for: raw)))
- } else {
- rendered.padding(.vertical, 1)
- }
- }
- .frame(maxWidth: .infinity, alignment: .leading)
- .background(isAnchored ? Color(nsColor: NSColor(calibratedRed: 0.79, green: 0.39, blue: 0.26, alpha: 0.18)) : Color.clear)
- .contentShape(Rectangle())
- .onTapGesture { onFocus() }
- .onChange(of: block.raw) { raw = $0 } // external change (undo of split/merge)
- }
+ var body: some View {
+ Group {
+ if isFocused {
+ SingleBlockEditor(text: $raw, onEdit: onEdit, onSplit: onSplit, onMerge: onMerge)
+ .frame(height: max(28, SingleBlockEditor.height(for: raw)))
+ } else {
+ rendered.padding(.vertical, 1)
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+ .background(isAnchored ? Color(nsColor: NSColor(calibratedRed: 0.79, green: 0.39, blue: 0.26, alpha: 0.18)) : Color.clear)
+ .contentShape(Rectangle())
+ .onTapGesture { onFocus() }
+ .onChange(of: block.raw) { raw = $0 } // external change (undo of split/merge)
+ }
- @ViewBuilder private var rendered: some View {
- let k = BlockModel.kind(of: block.raw)
- switch k {
- case .heading1:
- Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 26).bold())
- case .heading2:
- Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 20).bold())
- case .quote:
- Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 17))
- .padding(.leading, 14).overlay(alignment: .leading) { Rectangle().fill(.quaternary).frame(width: 3) }
- case .hr:
- Text("⁂").font(.system(size: 17)).frame(maxWidth: .infinity, alignment: .center).foregroundStyle(.secondary)
- case .paragraph:
- Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 17))
- }
- }
+ @ViewBuilder private var rendered: some View {
+ let k = BlockModel.kind(of: block.raw)
+ switch k {
+ case .heading1:
+ Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 26).bold())
+ case .heading2:
+ Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 20).bold())
+ case .quote:
+ Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 17))
+ .padding(.leading, 14).overlay(alignment: .leading) { Rectangle().fill(.quaternary).frame(width: 3) }
+ case .hr:
+ Text("⁂").font(.system(size: 17)).frame(maxWidth: .infinity, alignment: .center).foregroundStyle(.secondary)
+ case .paragraph:
+ Text(BlockModel.rendered(block.raw)).font(.custom("Iowan Old Style", size: 17))
+ }
+ }
}
// MARK: - Focused block = one non-scrolling NSTextView (native IME/undo/select/cut-paste)
struct SingleBlockEditor: NSViewRepresentable {
- @Binding var text: String
- var onEdit: (String) -> Void
- var onSplit: (Int) -> Void
- var onMerge: () -> Void
+ @Binding var text: String
+ var onEdit: (String) -> Void
+ var onSplit: (Int) -> Void
+ var onMerge: () -> Void
- static func height(for raw: String) -> CGFloat {
- let s = NSAttributedString(string: raw, attributes: [.font: NSFontManager.shared
- .font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17) ?? .systemFont(ofSize: 17)])
- return ceil(s.boundingRect(with: CGSize(width: 640, height: CGFloat.greatestFiniteMagnitude),
- options: [.usesLineFragmentOrigin]).height) + 8
- }
+ static func height(for raw: String) -> CGFloat {
+ let s = NSAttributedString(string: raw, attributes: [.font: NSFontManager.shared
+ .font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17) ?? .systemFont(ofSize: 17)])
+ return ceil(s.boundingRect(with: CGSize(width: 640, height: CGFloat.greatestFiniteMagnitude),
+ options: [.usesLineFragmentOrigin]).height) + 8
+ }
- func makeNSView(context: Context) -> NSTextView {
- let tv = NSTextView()
- tv.isRichText = false
- tv.allowsUndo = true // per-block native undo — across-block undo is an honest spike finding
- tv.isAutomaticQuoteSubstitutionEnabled = false
- tv.isAutomaticDashSubstitutionEnabled = false
- tv.isAutomaticTextReplacementEnabled = false
- tv.isAutomaticSpellingCorrectionEnabled = false
- tv.drawsBackground = true
- tv.backgroundColor = NSColor(calibratedRed: 0.99, green: 0.965, blue: 0.88, alpha: 1) // "source mode" tint
- tv.typingAttributes = Self.typing
- tv.string = text
- tv.delegate = context.coordinator
- tv.isEditable = true
- tv.isSelectable = true
- tv.textContainer?.containerSize = NSSize(width: 640, height: CGFloat.greatestFiniteMagnitude)
- tv.textContainer?.widthTracksTextView = false
- tv.textContainer?.lineFragmentPadding = 4
- tv.isVerticallyResizable = false
- tv.isHorizontallyResizable = false
- context.coordinator.textView = tv
- DispatchQueue.main.async { tv.window?.makeFirstResponder(tv) }
- return tv
- }
+ func makeNSView(context: Context) -> NSTextView {
+ let tv = NSTextView()
+ tv.isRichText = false
+ tv.allowsUndo = true // per-block native undo — across-block undo is an honest spike finding
+ tv.isAutomaticQuoteSubstitutionEnabled = false
+ tv.isAutomaticDashSubstitutionEnabled = false
+ tv.isAutomaticTextReplacementEnabled = false
+ tv.isAutomaticSpellingCorrectionEnabled = false
+ tv.drawsBackground = true
+ tv.backgroundColor = NSColor(calibratedRed: 0.99, green: 0.965, blue: 0.88, alpha: 1) // "source mode" tint
+ tv.typingAttributes = Self.typing
+ tv.string = text
+ tv.delegate = context.coordinator
+ tv.isEditable = true
+ tv.isSelectable = true
+ tv.textContainer?.containerSize = NSSize(width: 640, height: CGFloat.greatestFiniteMagnitude)
+ tv.textContainer?.widthTracksTextView = false
+ tv.textContainer?.lineFragmentPadding = 4
+ tv.isVerticallyResizable = false
+ tv.isHorizontallyResizable = false
+ context.coordinator.textView = tv
+ DispatchQueue.main.async { tv.window?.makeFirstResponder(tv) }
+ return tv
+ }
- func updateNSView(_ tv: NSTextView, context: Context) {
- if tv.string != text { tv.string = text }
- }
+ func updateNSView(_ tv: NSTextView, context _: Context) {
+ if tv.string != text {
+ tv.string = text
+ }
+ }
- func makeCoordinator() -> Coordinator { Coordinator(self) }
+ func makeCoordinator() -> Coordinator {
+ Coordinator(self)
+ }
- static var typing: [NSAttributedString.Key: Any] { [
- .font: NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17) ?? .systemFont(ofSize: 17),
- ] }
+ static var typing: [NSAttributedString.Key: Any] {
+ [
+ .font: NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17) ?? .systemFont(ofSize: 17),
+ ]
+ }
- final class Coordinator: NSObject, NSTextViewDelegate {
- let parent: SingleBlockEditor
- weak var textView: NSTextView?
- init(_ parent: SingleBlockEditor) { self.parent = parent }
+ final class Coordinator: NSObject, NSTextViewDelegate {
+ let parent: SingleBlockEditor
+ weak var textView: NSTextView?
+ init(_ parent: SingleBlockEditor) {
+ self.parent = parent
+ }
- func textDidChange(_ notification: Notification) {
- guard let tv = notification.object as? NSTextView else { return }
- parent.text = tv.string
- parent.onEdit(tv.string)
- }
+ func textDidChange(_ notification: Notification) {
+ guard let tv = notification.object as? NSTextView else { return }
+ parent.text = tv.string
+ parent.onEdit(tv.string)
+ }
- // Enter = split at cursor, ⌫ at position 0 = merge up — the block-model lift meter.
- func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
- if commandSelector == #selector(NSResponder.insertNewline(_:)) {
- parent.onSplit(textView.selectedRange().location)
- return true
- }
- if commandSelector == #selector(NSResponder.deleteBackward(_:)) {
- if textView.selectedRange().location == 0, textView.selectedRange().length == 0 {
- parent.onMerge()
- return true
- }
- }
- return false
- }
- }
+ /// Enter = split at cursor, ⌫ at position 0 = merge up — the block-model lift meter.
+ func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
+ if commandSelector == #selector(NSResponder.insertNewline(_:)) {
+ parent.onSplit(textView.selectedRange().location)
+ return true
+ }
+ if commandSelector == #selector(NSResponder.deleteBackward(_:)) {
+ if textView.selectedRange().location == 0, textView.selectedRange().length == 0 {
+ parent.onMerge()
+ return true
+ }
+ }
+ return false
+ }
+ }
}
// 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)
- }
+ func applicationWillFinishLaunching(_: Notification) {
+ NSApp.setActivationPolicy(.regular)
+ }
+
+ func applicationDidFinishLaunching(_: Notification) {
+ NSApp.activate(ignoringOtherApps: true)
+ }
}
diff --git a/spike/codeedit/Package.swift b/spike/codeedit/Package.swift
index a834327..f8b5618 100644
--- a/spike/codeedit/Package.swift
+++ b/spike/codeedit/Package.swift
@@ -2,11 +2,11 @@
import PackageDescription
let package = Package(
- name: "CodeEditSpike",
- platforms: [.macOS(.v26)],
- dependencies: [
- // Fork fact from map #16: same fork + revision as Classis (0.15.8-helm = 3ce6007).
- .package(url: "https://github.com/AlexKucera/CodeEditSourceEditor.git", exact: "0.15.8-helm"),
- ],
- targets: [.executableTarget(name: "CodeEditSpike", dependencies: ["CodeEditSourceEditor"])]
+ name: "CodeEditSpike",
+ platforms: [.macOS(.v26)],
+ dependencies: [
+ // Fork fact from map #16: same fork + revision as Classis (0.15.8-helm = 3ce6007).
+ .package(url: "https://github.com/AlexKucera/CodeEditSourceEditor.git", exact: "0.15.8-helm"),
+ ],
+ targets: [.executableTarget(name: "CodeEditSpike", dependencies: ["CodeEditSourceEditor"])],
)
diff --git a/spike/codeedit/Sources/CodeEditSpike/SpikeApp.swift b/spike/codeedit/Sources/CodeEditSpike/SpikeApp.swift
index 1be4684..8161686 100644
--- a/spike/codeedit/Sources/CodeEditSpike/SpikeApp.swift
+++ b/spike/codeedit/Sources/CodeEditSpike/SpikeApp.swift
@@ -10,37 +10,37 @@ import SwiftUI
// MARK: - Prose theme (uniform-font compromise documented in the resolution)
enum ProseTheme {
- // Iowan Old Style like Spike B / the web proto; falls back to system serif.
- static var bodyFont: NSFont {
- NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17)
- ?? NSFont.systemFont(ofSize: 17, weight: .regular, width: .standard)
- }
+ /// Iowan Old Style like Spike B / the web proto; falls back to system serif.
+ static var bodyFont: NSFont {
+ NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17)
+ ?? NSFont.systemFont(ofSize: 17, weight: .regular, width: .standard)
+ }
- static let ink = NSColor(srgbRed: 0.10, green: 0.10, blue: 0.09, alpha: 1)
- static let dim = NSColor(srgbRed: 0.55, green: 0.55, blue: 0.55, alpha: 1)
- static let paper = NSColor(srgbRed: 0.98, green: 0.98, blue: 0.98, alpha: 1)
- static let accent = NSColor(srgbRed: 0.79, green: 0.39, blue: 0.26, alpha: 1)
+ static let ink = NSColor(srgbRed: 0.10, green: 0.10, blue: 0.09, alpha: 1)
+ static let dim = NSColor(srgbRed: 0.55, green: 0.55, blue: 0.55, alpha: 1)
+ static let paper = NSColor(srgbRed: 0.98, green: 0.98, blue: 0.98, alpha: 1)
+ static let accent = NSColor(srgbRed: 0.79, green: 0.39, blue: 0.26, alpha: 1)
- static var theme: EditorTheme {
- EditorTheme(
- text: .init(color: ink),
- insertionPoint: ink,
- invisibles: .init(color: dim),
- background: paper,
- lineHighlight: NSColor(srgbRed: 0.955, green: 0.955, blue: 0.955, alpha: 1),
- selection: NSColor(srgbRed: 0.79, green: 0.39, blue: 0.26, alpha: 0.18),
- keywords: .init(color: dim), // markdown markers route here via prosePass below
- commands: .init(color: ink),
- types: .init(color: ink, bold: true), // headings: bold, same size (substrate limit)
- attributes: .init(color: ink),
- variables: .init(color: ink),
- values: .init(color: ink),
- numbers: .init(color: ink),
- strings: .init(color: NSColor(srgbRed: 0.25, green: 0.42, blue: 0.31, alpha: 1)), // blockquote tint
- characters: .init(color: ink),
- comments: .init(color: dim)
- )
- }
+ static var theme: EditorTheme {
+ EditorTheme(
+ text: .init(color: ink),
+ insertionPoint: ink,
+ invisibles: .init(color: dim),
+ background: paper,
+ lineHighlight: NSColor(srgbRed: 0.955, green: 0.955, blue: 0.955, alpha: 1),
+ selection: NSColor(srgbRed: 0.79, green: 0.39, blue: 0.26, alpha: 0.18),
+ keywords: .init(color: dim), // markdown markers route here via prosePass below
+ commands: .init(color: ink),
+ types: .init(color: ink, bold: true), // headings: bold, same size (substrate limit)
+ attributes: .init(color: ink),
+ variables: .init(color: ink),
+ values: .init(color: ink),
+ numbers: .init(color: ink),
+ strings: .init(color: NSColor(srgbRed: 0.25, green: 0.42, blue: 0.31, alpha: 1)), // blockquote tint
+ characters: .init(color: ink),
+ comments: .init(color: dim),
+ )
+ }
}
// MARK: - Prose highlight pass (helm's MonokaiHighlighter pattern: wrap tree-sitter, add regex passes)
@@ -49,343 +49,352 @@ enum ProseTheme {
/// heading lines → bold capture, marker+inline-syntax runs → dim capture. Emphasis/anchor is NOT
/// done here — layer-backed Emphasis handles it.
final class ProseHighlighter: HighlightProviding {
- private let wrapped = TreeSitterClient()
+ private let wrapped = TreeSitterClient()
- func setUp(textView: TextView, codeLanguage: CodeLanguage) {
- wrapped.setUp(textView: textView, codeLanguage: codeLanguage)
- }
+ func setUp(textView: TextView, codeLanguage: CodeLanguage) {
+ wrapped.setUp(textView: textView, codeLanguage: codeLanguage)
+ }
- func applyEdit(
- textView: TextView,
- range: NSRange,
- delta: Int,
- completion: @escaping @MainActor (Result) -> Void
- ) {
- wrapped.applyEdit(textView: textView, range: range, delta: delta, completion: completion)
- }
+ func applyEdit(
+ textView: TextView,
+ range: NSRange,
+ delta: Int,
+ completion: @escaping @MainActor (Result) -> Void,
+ ) {
+ wrapped.applyEdit(textView: textView, range: range, delta: delta, completion: completion)
+ }
- func queryHighlightsFor(
- textView: TextView,
- range: NSRange,
- completion: @escaping @MainActor (Result<[HighlightRange], Error>) -> Void
- ) {
- wrapped.queryHighlightsFor(textView: textView, range: range) { result in
- switch result {
- case .failure(let error):
- completion(.failure(error))
- case .success(let tsRanges):
- var out = tsRanges
- let ns = textView.string as NSString
- let safe = range.intersection(NSRange(location: 0, length: ns.length)) ?? range
- out += Self.proseRanges(in: ns, range: safe)
- completion(.success(out))
- }
- }
- }
+ func queryHighlightsFor(
+ textView: TextView,
+ range: NSRange,
+ completion: @escaping @MainActor (Result<[HighlightRange], Error>) -> Void,
+ ) {
+ wrapped.queryHighlightsFor(textView: textView, range: range) { result in
+ switch result {
+ case let .failure(error):
+ completion(.failure(error))
+ case let .success(tsRanges):
+ var out = tsRanges
+ let ns = textView.string as NSString
+ let safe = range.intersection(NSRange(location: 0, length: ns.length)) ?? range
+ out += Self.proseRanges(in: ns, range: safe)
+ completion(.success(out))
+ }
+ }
+ }
- /// Pure: heading text → .type (bold via theme), heading marker + inline marks → .keyword (dim).
- /// ponytail: line-scan regex, not an AST — corpus is plain prose markdown; enough for the spike.
- static func proseRanges(in ns: NSString, range: NSRange) -> [HighlightRange] {
- var out: [HighlightRange] = []
- ns.enumerateSubstrings(in: range, options: [.byLines]) { line, lineRange, _, _ in
- guard let line, !line.isEmpty else { return }
- if let markerLen = Self.headingMarkerLen(line) {
- // heading text (after marker, same line) → bold capture
- let textLen = lineRange.length - markerLen
- if textLen > 0 {
- out.append(HighlightRange(
- range: NSRange(location: lineRange.location + markerLen, length: textLen),
- capture: .type
- ))
- }
- // marker → dim
- out.append(HighlightRange(
- range: NSRange(location: lineRange.location, length: markerLen),
- capture: .keyword
- ))
- } else if line.hasPrefix(">") {
- // quote line: text → tinted .string, markers dimmed
- let textLen = lineRange.length - 1
- if textLen > 0 {
- out.append(HighlightRange(range: NSRange(location: lineRange.location + 1, length: textLen), capture: .string))
- }
- out.append(HighlightRange(range: NSRange(location: lineRange.location, length: 1), capture: .keyword))
- } else {
- // inline syntax chars → dim, one run per char (runs merge at render)
- let marks: Set = [0x2A, 0x5F, 0x60, 0x5B, 0x5D, 0x28, 0x29, 0x21, 0x3C, 0x3E] // * _ ` [ ] ( ) ! < >
- for (off, ch) in line.utf16.enumerated() where marks.contains(ch) {
- out.append(HighlightRange(
- range: NSRange(location: lineRange.location + off, length: 1),
- capture: .keyword
- ))
- }
- }
- }
- return out
- }
+ /// Pure: heading text → .type (bold via theme), heading marker + inline marks → .keyword (dim).
+ /// ponytail: line-scan regex, not an AST — corpus is plain prose markdown; enough for the spike.
+ static func proseRanges(in ns: NSString, range: NSRange) -> [HighlightRange] {
+ var out: [HighlightRange] = []
+ ns.enumerateSubstrings(in: range, options: [.byLines]) { line, lineRange, _, _ in
+ guard let line, !line.isEmpty else { return }
+ if let markerLen = Self.headingMarkerLen(line) {
+ // heading text (after marker, same line) → bold capture
+ let textLen = lineRange.length - markerLen
+ if textLen > 0 {
+ out.append(HighlightRange(
+ range: NSRange(location: lineRange.location + markerLen, length: textLen),
+ capture: .type,
+ ))
+ }
+ // marker → dim
+ out.append(HighlightRange(
+ range: NSRange(location: lineRange.location, length: markerLen),
+ capture: .keyword,
+ ))
+ } else if line.hasPrefix(">") {
+ // quote line: text → tinted .string, markers dimmed
+ let textLen = lineRange.length - 1
+ if textLen > 0 {
+ out.append(HighlightRange(range: NSRange(location: lineRange.location + 1, length: textLen), capture: .string))
+ }
+ out.append(HighlightRange(range: NSRange(location: lineRange.location, length: 1), capture: .keyword))
+ } else {
+ // inline syntax chars → dim, one run per char (runs merge at render)
+ let marks: Set = [0x2A, 0x5F, 0x60, 0x5B, 0x5D, 0x28, 0x29, 0x21, 0x3C, 0x3E] // * _ ` [ ] ( ) ! < >
+ for (off, ch) in line.utf16.enumerated() where marks.contains(ch) {
+ out.append(HighlightRange(
+ range: NSRange(location: lineRange.location + off, length: 1),
+ capture: .keyword,
+ ))
+ }
+ }
+ }
+ return out
+ }
- private static func headingMarkerLen(_ line: String) -> Int? {
- guard line.hasPrefix("#") else { return nil }
- let hashes = line.prefix { $0 == "#" }.count
- guard hashes <= 6, line.dropFirst(hashes).hasPrefix(" ") else { return nil }
- return hashes + 1
- }
+ private static func headingMarkerLen(_ line: String) -> Int? {
+ guard line.hasPrefix("#") else { return nil }
+ let hashes = line.prefix { $0 == "#" }.count
+ guard hashes <= 6, line.dropFirst(hashes).hasPrefix(" ") else { return nil }
+ return hashes + 1
+ }
}
// MARK: - Quote anchor (identical algorithm to Spike B — same feasibility question)
nonisolated enum AnchorSearch {
- private struct Word { let norm: String; let range: Range }
- 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)
- }
- }
+ private struct Word { let norm: String; let range: Range }
+ 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)
+ }
+ }
- /// Word-tokenized whitespace/punctuation-tolerant search. nil = stale anchor.
- static func range(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.. 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
+ return NSRange(
+ location: text.utf16.distance(from: text.startIndex, to: from),
+ length: text.utf16.distance(from: from, to: to),
+ )
+ }
+ }
+ return nil
+ }
}
// MARK: - App shell
@main
struct SpikeApp: App {
- @NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
- var body: some Scene {
- Window("Spike A — CodeEdit fork", id: "main") {
- ContentView()
- .frame(minWidth: 900, minHeight: 640)
- .onAppear { NSApp.activate(ignoringOtherApps: true) }
- }
- .windowStyle(.hiddenTitleBar)
- }
+ @NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
+ var body: some Scene {
+ Window("Spike A — CodeEdit fork", id: "main") {
+ ContentView()
+ .frame(minWidth: 900, minHeight: 640)
+ .onAppear { NSApp.activate(ignoringOtherApps: true) }
+ }
+ .windowStyle(.hiddenTitleBar)
+ }
- // ponytail: one runnable check for the prose pass + anchor logic — `run.sh --check`
- init() {
- if CommandLine.arguments.contains("--check") { Self.selfCheck(); exit(0) }
- }
+ // ponytail: one runnable check for the prose pass + anchor logic — `run.sh --check`
+ init() {
+ if CommandLine.arguments.contains("--check") {
+ Self.selfCheck(); exit(0)
+ }
+ }
- static func selfCheck() {
- // Repo root from compile-time path (self-check must not depend on cwd).
- let root = URL(fileURLWithPath: #filePath)
- .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
- let text = (try? String(contentsOf: root.appendingPathComponent("spike/prose/the-expected-value-of-showing.md"), encoding: .utf8)) ?? ""
- assert(!text.isEmpty, "FAIL: corpus missing — run from repo root")
- let ns = text as NSString
- let full = NSRange(location: 0, length: ns.length)
- let ranges = ProseHighlighter.proseRanges(in: ns, range: full)
- // headings detected (calibration piece has H1 + H2s)
- let headingTexts = ranges.filter { $0.capture == .type }
- assert(headingTexts.count >= 3, "FAIL: expected headings, got \(headingTexts.count)")
- assert(headingTexts.allSatisfy { (ns.substring(with: $0.range) as NSString).range(of: "#").location == NSNotFound },
- "FAIL: marker leaked into heading text")
- // markers dimmed
- assert(ranges.contains { $0.capture == .keyword && ns.substring(with: $0.range).hasPrefix("#") },
- "FAIL: heading marker not dimmed")
- // anchor: live quote found; stale → nil; whitespace-tolerant
- 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 = AnchorSearch.range(of: quote, in: text) else { assert(false, "FAIL: live quote not found"); return }
- assert((ns.substring(with: r) as NSString).length > 50)
- let squished = quote.components(separatedBy: .newlines).joined(separator: " ")
- assert(AnchorSearch.range(of: squished, in: text) != nil, "FAIL: whitespace tolerance")
- assert(AnchorSearch.range(of: "this quote was deleted years ago", in: text) == nil, "FAIL: stale should be nil")
- // perf smoke: PERF-3k anchor timing
- let perfURL = root.appendingPathComponent("spike/prose/PERF-3k.md")
- if let perf = try? String(contentsOf: perfURL, encoding: .utf8) {
- let t0 = DispatchTime.now()
- _ = AnchorSearch.range(of: "The odds are better than they look", in: perf)
- let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6
- print("PASS: \(headingTexts.count) headings, anchor @ \(r.location) len \(r.length); PERF-3k anchor search \(String(format: "%.1f", ms)) ms")
- } else {
- print("PASS: \(headingTexts.count) headings, anchor @ \(r.location) len \(r.length); PERF-3k not found")
- }
- }
+ static func selfCheck() {
+ // Repo root from compile-time path (self-check must not depend on cwd).
+ let root = URL(fileURLWithPath: #filePath)
+ .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ let text = (try? String(contentsOf: root.appendingPathComponent("spike/prose/the-expected-value-of-showing.md"), encoding: .utf8)) ?? ""
+ assert(!text.isEmpty, "FAIL: corpus missing — run from repo root")
+ let ns = text as NSString
+ let full = NSRange(location: 0, length: ns.length)
+ let ranges = ProseHighlighter.proseRanges(in: ns, range: full)
+ // headings detected (calibration piece has H1 + H2s)
+ let headingTexts = ranges.filter { $0.capture == .type }
+ assert(headingTexts.count >= 3, "FAIL: expected headings, got \(headingTexts.count)")
+ assert(headingTexts.allSatisfy { (ns.substring(with: $0.range) as NSString).range(of: "#").location == NSNotFound },
+ "FAIL: marker leaked into heading text")
+ // markers dimmed
+ assert(ranges.contains { $0.capture == .keyword && ns.substring(with: $0.range).hasPrefix("#") },
+ "FAIL: heading marker not dimmed")
+ // anchor: live quote found; stale → nil; whitespace-tolerant
+ 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 = AnchorSearch.range(of: quote, in: text) else { assertionFailure("FAIL: live quote not found"); return }
+ assert((ns.substring(with: r) as NSString).length > 50)
+ let squished = quote.components(separatedBy: .newlines).joined(separator: " ")
+ assert(AnchorSearch.range(of: squished, in: text) != nil, "FAIL: whitespace tolerance")
+ assert(AnchorSearch.range(of: "this quote was deleted years ago", in: text) == nil, "FAIL: stale should be nil")
+ // perf smoke: PERF-3k anchor timing
+ let perfURL = root.appendingPathComponent("spike/prose/PERF-3k.md")
+ if let perf = try? String(contentsOf: perfURL, encoding: .utf8) {
+ let t0 = DispatchTime.now()
+ _ = AnchorSearch.range(of: "The odds are better than they look", in: perf)
+ let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6
+ print("PASS: \(headingTexts.count) headings, anchor @ \(r.location) len \(r.length); PERF-3k anchor search \(String(format: "%.1f", ms)) ms")
+ } else {
+ print("PASS: \(headingTexts.count) headings, anchor @ \(r.location) len \(r.length); PERF-3k not found")
+ }
+ }
}
struct ContentView: View {
- @State private var text: String
- @State private var editorState = SourceEditorState()
- @State private var reading = false
- @State private var staleShown = false
- @State private var loadMs: Double = 0
- @State private var anchorNote: String?
- /// Captured controller — the path to Emphasis/setCursorPositions (helm #160 pattern).
- /// Reference box, not @State: writes during makeNSViewController are dropped (see ControllerBox).
- private let box = ControllerBox()
+ @State private var text: String
+ @State private var editorState = SourceEditorState()
+ @State private var reading = false
+ @State private var staleShown = false
+ @State private var loadMs: Double = 0
+ @State private var anchorNote: String?
+ /// Captured controller — the path to Emphasis/setCursorPositions (helm #160 pattern).
+ /// Reference box, not @State: writes during makeNSViewController are dropped (see ControllerBox).
+ private let box = ControllerBox()
- init() {
- // Repo root from compile-time path — launchd cwd is "/", so relative paths never hit.
- let repoRoot = URL(fileURLWithPath: #filePath) // /spike/codeedit/Sources/CodeEditSpike/SpikeApp.swift
- .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
- let corpus = repoRoot.appendingPathComponent("spike/prose/the-expected-value-of-showing.md")
- let arg = CommandLine.arguments.first(where: { $0.hasSuffix(".md") })
- let url = arg.map { URL(fileURLWithPath: $0, relativeTo: repoRoot) } ?? corpus
- let t = (try? String(contentsOf: url, encoding: .utf8))
- ?? (try? String(contentsOf: corpus, encoding: .utf8))
- ?? "# Spike A\n\n(No corpus file found at \(corpus.path).)"
- _text = State(initialValue: t)
- }
+ init() {
+ // Repo root from compile-time path — launchd cwd is "/", so relative paths never hit.
+ let repoRoot = URL(fileURLWithPath: #filePath) // /spike/codeedit/Sources/CodeEditSpike/SpikeApp.swift
+ .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ let corpus = repoRoot.appendingPathComponent("spike/prose/the-expected-value-of-showing.md")
+ let arg = CommandLine.arguments.first(where: { $0.hasSuffix(".md") })
+ let url = arg.map { URL(fileURLWithPath: $0, relativeTo: repoRoot) } ?? corpus
+ let t = (try? String(contentsOf: url, encoding: .utf8))
+ ?? (try? String(contentsOf: corpus, encoding: .utf8))
+ ?? "# Spike A\n\n(No corpus file found at \(corpus.path).)"
+ _text = State(initialValue: t)
+ }
- var body: some View {
- VStack(spacing: 0) {
- bar
- Divider()
- if reading {
- // Reading toggle: same per-block renderer stance as Spike B (its resolution is the map's reference)
- 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 {
- editor
- }
- }
- .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.")
- }
- }
+ var body: some View {
+ VStack(spacing: 0) {
+ bar
+ Divider()
+ if reading {
+ // Reading toggle: same per-block renderer stance as Spike B (its resolution is the map's reference)
+ 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 {
+ editor
+ }
+ }
+ .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 editor: some View {
- // Centered measure via maxWidth (iA-Writer approach; no GeometryReader — it proposes
- // 0×0 to the AppKit leaf on first pass and the window never places in this shell).
- SourceEditor(
- $text,
- language: .markdown,
- configuration: config,
- state: $editorState,
- highlightProviders: [ProseHighlighter()],
- coordinators: [ControllerCapture(onCapture: { box.controller = $0 })]
- )
- .frame(maxWidth: 720)
- .frame(maxWidth: .infinity)
- .padding(.horizontal, 24)
- }
+ private var editor: some View {
+ // Centered measure via maxWidth (iA-Writer approach; no GeometryReader — it proposes
+ // 0×0 to the AppKit leaf on first pass and the window never places in this shell).
+ SourceEditor(
+ $text,
+ language: .markdown,
+ configuration: config,
+ state: $editorState,
+ highlightProviders: [ProseHighlighter()],
+ coordinators: [ControllerCapture(onCapture: { box.controller = $0 })],
+ )
+ .frame(maxWidth: 720)
+ .frame(maxWidth: .infinity)
+ .padding(.horizontal, 24)
+ }
- private var config: SourceEditorConfiguration {
- SourceEditorConfiguration(
- appearance: .init(
- theme: ProseTheme.theme,
- font: ProseTheme.bodyFont,
- lineHeightMultiple: 1.45, // paragraph rhythm via line-height (no per-paragraph spacing on substrate)
- wrapLines: true
- ),
- behavior: .init(reformatAtColumn: 10_000), // never hard-wrap prose
- peripherals: .init(
- showGutter: false, // no line numbers in a writing app
- showMinimap: false,
- showReformattingGuide: false,
- showFoldingRibbon: false,
- invisibleCharactersConfiguration: .init(showSpaces: false, showTabs: false, showLineEndings: false),
- warningCharacters: []
- )
- )
- }
+ private var config: SourceEditorConfiguration {
+ SourceEditorConfiguration(
+ appearance: .init(
+ theme: ProseTheme.theme,
+ font: ProseTheme.bodyFont,
+ lineHeightMultiple: 1.45, // paragraph rhythm via line-height (no per-paragraph spacing on substrate)
+ wrapLines: true,
+ ),
+ behavior: .init(reformatAtColumn: 10000), // never hard-wrap prose
+ peripherals: .init(
+ showGutter: false, // no line numbers in a writing app
+ showMinimap: false,
+ showReformattingGuide: false,
+ showFoldingRibbon: false,
+ invisibleCharactersConfiguration: .init(showSpaces: false, showTabs: false, showLineEndings: false),
+ warningCharacters: [],
+ ),
+ )
+ }
- 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 note = anchorNote { Text(note).foregroundStyle(.secondary).font(.caption) }
- Spacer()
- Text("load \(String(format: "%.1f", loadMs)) ms").foregroundStyle(.secondary).font(.caption)
- }
- .padding(.horizontal, 16)
- .padding(.vertical, 8)
- }
+ 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 note = anchorNote {
+ Text(note).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 controller = box.controller
- let t0 = DispatchTime.now()
- let r = AnchorSearch.range(of: quote, in: text)
- loadMs = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000
- guard let r else {
- anchorNote = nil
- staleShown = true
- return
- }
- anchorNote = "anchored @ \(r.location)–\(r.location + r.length)\(controller == nil ? " (no ctrl!)" : "")"
- guard let controller else { return }
- // Layer-backed emphasis highlight (survives re-highlighting) + scroll-to + selection.
- controller.textView.emphasisManager?.replaceEmphases(
- [Emphasis(range: r, style: .outline(color: ProseTheme.accent, fill: false))],
- for: "fix-card-anchor"
- )
- controller.setCursorPositions([CursorPosition(range: r)], scrollToVisible: true)
- }
+ private func applyAnchor(_ quote: String) {
+ let controller = box.controller
+ let t0 = DispatchTime.now()
+ let r = AnchorSearch.range(of: quote, in: text)
+ loadMs = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000
+ guard let r else {
+ anchorNote = nil
+ staleShown = true
+ return
+ }
+ anchorNote = "anchored @ \(r.location)–\(r.location + r.length)\(controller == nil ? " (no ctrl!)" : "")"
+ guard let controller else { return }
+ // Layer-backed emphasis highlight (survives re-highlighting) + scroll-to + selection.
+ controller.textView.emphasisManager?.replaceEmphases(
+ [Emphasis(range: r, style: .outline(color: ProseTheme.accent, fill: false))],
+ for: "fix-card-anchor",
+ )
+ controller.setCursorPositions([CursorPosition(range: r)], scrollToVisible: true)
+ }
}
/// Captures the live TextViewController at prepareCoordinator (helm #160's captured-controller pattern).
/// Reference box, NOT @State: prepareCoordinator fires inside makeNSViewController — during SwiftUI's
/// view update — and @State writes there are silently dropped (root cause of the "(no ctrl!)" case).
final class ControllerBox: @unchecked Sendable {
- var controller: TextViewController?
+ var controller: TextViewController?
}
+
final class ControllerCapture: TextViewCoordinator {
- let onCapture: (TextViewController) -> Void
- init(onCapture: @escaping (TextViewController) -> Void) { self.onCapture = onCapture }
- func prepareCoordinator(controller: TextViewController) {
- onCapture(controller)
- }
+ let onCapture: (TextViewController) -> Void
+ init(onCapture: @escaping (TextViewController) -> Void) {
+ self.onCapture = onCapture
+ }
+
+ func prepareCoordinator(controller: TextViewController) {
+ onCapture(controller)
+ }
}
// MARK: - Reading blocks (Spike B's proven per-block renderer; .full syntax)
extension SpikeApp {
- // 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
- var 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,
- options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace)
- )) ?? AttributedString(p)
- return (level, attr)
- }
- }
+ // 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
+ var 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,
+ options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace),
+ )) ?? AttributedString(p)
+ return (level, attr)
+ }
+ }
}
// 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)
- }
+ func applicationWillFinishLaunching(_: Notification) {
+ NSApp.setActivationPolicy(.regular)
+ }
+
+ func applicationDidFinishLaunching(_: Notification) {
+ NSApp.activate(ignoringOtherApps: true)
+ }
}
diff --git a/spike/textkit2/Package.swift b/spike/textkit2/Package.swift
index 2451633..7c65afa 100644
--- a/spike/textkit2/Package.swift
+++ b/spike/textkit2/Package.swift
@@ -2,7 +2,7 @@
import PackageDescription
let package = Package(
- name: "TextKit2Spike",
- platforms: [.macOS(.v26)],
- targets: [.executableTarget(name: "TextKit2Spike")]
+ 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
index 3e31798..2eb06bb 100644
--- a/spike/textkit2/Sources/TextKit2Spike/EditorPane.swift
+++ b/spike/textkit2/Sources/TextKit2Spike/EditorPane.swift
@@ -7,79 +7,83 @@ import SwiftUI
/// 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?
+ 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 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)
- }
+ 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)
- }
+ 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) }
+ func makeCoordinator() -> Coordinator {
+ Coordinator(onEdit: onEdit)
+ }
- final class Coordinator: NSObject, NSTextViewDelegate {
- let onEdit: ((String) -> Void)?
- weak var textView: NSTextView?
- var loadedHash: Int = 0
+ final class Coordinator: NSObject, NSTextViewDelegate {
+ let onEdit: ((String) -> Void)?
+ weak var textView: NSTextView?
+ var loadedHash: Int = 0
- init(onEdit: ((String) -> Void)?) { self.onEdit = onEdit }
+ 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)
- }
- }
+ 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
index 4eaf6a8..8fb7f6e 100644
--- a/spike/textkit2/Sources/TextKit2Spike/ProsePresenter.swift
+++ b/spike/textkit2/Sources/TextKit2Spike/ProsePresenter.swift
@@ -9,120 +9,136 @@ import AppKit
/// 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 }
+ 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 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 = ["*", "_", "`", "[", "]", "(", ")", "!", "<", ">"]
+ 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
- }
+ /// 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 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)
- }
+ /// 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) }
+ // 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 bodyAttributes: [NSAttributedString.Key: Any] { [
- .font: bodyFont, .paragraphStyle: paragraph(.body), .foregroundColor: NSColor(red: 0.10, green: 0.10, blue: 0.09, alpha: 1),
- ] }
+ static var bodyFont: NSFont {
+ NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17)
+ ?? NSFont.systemFont(ofSize: 17)
+ }
- 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
- }
- }
+ static var bodyAttributes: [NSAttributedString.Key: Any] {
+ [
+ .font: bodyFont, .paragraphStyle: paragraph(.body), .foregroundColor: NSColor(red: 0.10, green: 0.10, blue: 0.09, alpha: 1),
+ ]
+ }
- /// 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))
- }
- }
- }
- }
+ 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
+ }
+ }
- // MARK: Quote anchor (Fix-Card feasibility note for the ADR)
+ /// 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 = switch kind {
+ case .heading1: 2
+ case .heading2: 3
+ case .quote: 2
+ default: 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))
+ }
+ }
+ }
+ }
- /// 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)
- }
- }
+ /// 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 }
+ 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
index a67d093..9d5d59d 100644
--- a/spike/textkit2/Sources/TextKit2Spike/SpikeApp.swift
+++ b/spike/textkit2/Sources/TextKit2Spike/SpikeApp.swift
@@ -4,145 +4,150 @@ 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)
- }
+ @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) }
- }
+ // 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")
- }
+ 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)
- }
- }
+ // 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
+ @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))
- }
+ /// 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.")
- }
- }
+ 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 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
- }
- }
+ 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)
- }
+ func applicationWillFinishLaunching(_: Notification) {
+ NSApp.setActivationPolicy(.regular)
+ }
+
+ func applicationDidFinishLaunching(_: Notification) {
+ NSApp.activate(ignoringOtherApps: true)
+ }
}