chore: swiftformat drift + xcode 27 settings leftovers

Format-only pass over spikes, the gate prototype, and three app
files (brace style, wrapping — no semantic change), plus the 4-line
pbxproj alignment finishing the Xcode 27 settings pass (test-target
deployment target parity with 8e70f69).

[Generated by AI]
This commit is contained in:
AlexKucera committed 2026-10-16 14:49:26 +02:00
1 parent 8e70f69945
commit d722820fc8
16 files changed
+247 -128

No files matched your search

+4 -4
View File
@@ -331,7 +331,7 @@
GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES; GCC_WARN_UNUSED_VARIABLE = YES;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES; LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MACOSX_DEPLOYMENT_TARGET = 26.5; MACOSX_DEPLOYMENT_TARGET = 27.0;
MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
MTL_FAST_MATH = YES; MTL_FAST_MATH = YES;
ONLY_ACTIVE_ARCH = YES; ONLY_ACTIVE_ARCH = YES;
@@ -391,7 +391,7 @@
GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES; GCC_WARN_UNUSED_VARIABLE = YES;
LOCALIZATION_PREFERS_STRING_CATALOGS = YES; LOCALIZATION_PREFERS_STRING_CATALOGS = YES;
MACOSX_DEPLOYMENT_TARGET = 26.5; MACOSX_DEPLOYMENT_TARGET = 27.0;
MTL_ENABLE_DEBUG_INFO = NO; MTL_ENABLE_DEBUG_INFO = NO;
MTL_FAST_MATH = YES; MTL_FAST_MATH = YES;
SDKROOT = macosx; SDKROOT = macosx;
@@ -481,7 +481,7 @@
DEAD_CODE_STRIPPING = YES; DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 3M7APDAAC5; DEVELOPMENT_TEAM = 3M7APDAAC5;
GENERATE_INFOPLIST_FILE = YES; GENERATE_INFOPLIST_FILE = YES;
MACOSX_DEPLOYMENT_TARGET = 26.5; MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 1.0; MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests; PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
@@ -503,7 +503,7 @@
DEAD_CODE_STRIPPING = YES; DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = 3M7APDAAC5; DEVELOPMENT_TEAM = 3M7APDAAC5;
GENERATE_INFOPLIST_FILE = YES; GENERATE_INFOPLIST_FILE = YES;
MACOSX_DEPLOYMENT_TARGET = 26.5; MACOSX_DEPLOYMENT_TARGET = 27.0;
MARKETING_VERSION = 1.0; MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests; PRODUCT_BUNDLE_IDENTIFIER = com.babylondreams.MuseionTests;
PRODUCT_NAME = "$(TARGET_NAME)"; PRODUCT_NAME = "$(TARGET_NAME)";
+2 -1
View File
@@ -70,7 +70,8 @@ nonisolated enum ProfileBackup {
// Age check against the newest existing snapshot (#15: skips record no // Age check against the newest existing snapshot (#15: skips record no
// state; the normal age check governs retry). // state; the normal age check governs retry).
if let newest = sortedSnapshots(in: backupsRoot).first, if let newest = sortedSnapshots(in: backupsRoot).first,
now.timeIntervalSince(newest.timestamp) < snapshotInterval { now.timeIntervalSince(newest.timestamp) < snapshotInterval
{
return .skippedFresh return .skippedFresh
} }
-1
View File
@@ -162,7 +162,6 @@ struct ReadingSurface: NSViewRepresentable {
return blocks.first { $0.sourceRange.location >= caret }?.sourceLine return blocks.first { $0.sourceRange.location >= caret }?.sourceLine
} }
// MARK: WKNavigationDelegate // MARK: WKNavigationDelegate
func webView(_ wv: WKWebView, didFinish _: WKNavigation!) { func webView(_ wv: WKWebView, didFinish _: WKNavigation!) {
+2 -2
View File
@@ -29,13 +29,13 @@ func makeProfileFixture(at root: String) -> String {
for dir in ["skills/serif-writing", "logs", "cache", "sessions/xyz/cache"] { for dir in ["skills/serif-writing", "logs", "cache", "sessions/xyz/cache"] {
try? fileManager.createDirectory( try? fileManager.createDirectory(
atPath: (profile as NSString).appendingPathComponent(dir), atPath: (profile as NSString).appendingPathComponent(dir),
withIntermediateDirectories: true withIntermediateDirectories: true,
) )
} }
func write(_ text: String, _ rel: String) { func write(_ text: String, _ rel: String) {
try? text.write( try? text.write(
toFile: (profile as NSString).appendingPathComponent(rel), toFile: (profile as NSString).appendingPathComponent(rel),
atomically: true, encoding: .utf8 atomically: true, encoding: .utf8,
) )
} }
write("{\"token\": \"secret\"}", "auth.json") write("{\"token\": \"secret\"}", "auth.json")
+21 -9
View File
@@ -11,6 +11,7 @@
import SwiftUI import SwiftUI
// MARK: - Tokens (from ref/Web-Prototype/museion-workspace.html) // MARK: - Tokens (from ref/Web-Prototype/museion-workspace.html)
enum Tok { enum Tok {
static let bg = Color(hex: 0xFAFAF7) static let bg = Color(hex: 0xFAFAF7)
static let surface = Color(hex: 0xFFFFFF) static let surface = Color(hex: 0xFFFFFF)
@@ -24,6 +25,7 @@ enum Tok {
static func display(_ size: CGFloat, _ weight: Font.Weight = .regular) -> Font { static func display(_ size: CGFloat, _ weight: Font.Weight = .regular) -> Font {
.custom("Iowan Old Style", size: size).weight(weight) .custom("Iowan Old Style", size: size).weight(weight)
} }
static func mono(_ size: CGFloat) -> Font { static func mono(_ size: CGFloat) -> Font {
.system(size: size, design: .monospaced) .system(size: size, design: .monospaced)
} }
@@ -39,6 +41,7 @@ extension Color {
} }
// MARK: - Mock state // MARK: - Mock state
final class GateModel: ObservableObject { final class GateModel: ObservableObject {
enum Phase: Equatable { case checking, passed, failed } enum Phase: Equatable { case checking, passed, failed }
@Published var phase: Phase = .checking @Published var phase: Phase = .checking
@@ -52,13 +55,14 @@ final class GateModel: ObservableObject {
let myToken = token let myToken = token
phase = .checking phase = .checking
DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { [weak self] in DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { [weak self] in
guard let self, self.token == myToken else { return } guard let self, token == myToken else { return }
self.phase = self.nextPass ? .passed : .failed phase = nextPass ? .passed : .failed
} }
} }
} }
// MARK: - Shared pieces // MARK: - Shared pieces
struct EnginePill: View { struct EnginePill: View {
@EnvironmentObject var model: GateModel @EnvironmentObject var model: GateModel
@@ -82,7 +86,7 @@ struct EnginePill: View {
.background(Tok.surface, in: RoundedRectangle(cornerRadius: 10)) .background(Tok.surface, in: RoundedRectangle(cornerRadius: 10))
.overlay( .overlay(
RoundedRectangle(cornerRadius: 10) RoundedRectangle(cornerRadius: 10)
.strokeBorder(model.phase == .failed ? Tok.accent : Tok.border, lineWidth: 1) .strokeBorder(model.phase == .failed ? Tok.accent : Tok.border, lineWidth: 1),
) )
} }
@@ -101,7 +105,8 @@ struct Pulse: ViewModifier {
if active { if active {
content.opacity(0.35).animation( content.opacity(0.35).animation(
Animation.easeInOut(duration: 0.55).repeatForever(autoreverses: true), Animation.easeInOut(duration: 0.55).repeatForever(autoreverses: true),
value: active) value: active,
)
} else { } else {
content content
} }
@@ -163,14 +168,17 @@ struct RecheckButton: View {
} }
// MARK: - Mock workspace (context for the gate to sit over) // MARK: - Mock workspace (context for the gate to sit over)
struct MockWorkspace: View { struct MockWorkspace: View {
@EnvironmentObject var model: GateModel @EnvironmentObject var model: GateModel
var banner: AnyView? = nil var banner: AnyView?
var body: some View { var body: some View {
VStack(spacing: 0) { VStack(spacing: 0) {
toolbar toolbar
if let banner { banner } if let banner {
banner
}
HStack(spacing: 0) { HStack(spacing: 0) {
rail rail
editor editor
@@ -237,6 +245,7 @@ struct MockWorkspace: View {
} }
// MARK: - Variant A — blocking sheet, every launch // MARK: - Variant A — blocking sheet, every launch
struct VariantA: View { struct VariantA: View {
@EnvironmentObject var model: GateModel @EnvironmentObject var model: GateModel
@State private var showSteps = false @State private var showSteps = false
@@ -251,7 +260,7 @@ struct VariantA: View {
.background(Tok.surface, in: RoundedRectangle(cornerRadius: 14)) .background(Tok.surface, in: RoundedRectangle(cornerRadius: 14))
.overlay( .overlay(
RoundedRectangle(cornerRadius: 14) RoundedRectangle(cornerRadius: 14)
.strokeBorder(model.phase == .failed ? Tok.accent : Tok.border, lineWidth: 1) .strokeBorder(model.phase == .failed ? Tok.accent : Tok.border, lineWidth: 1),
) )
.shadow(radius: 24, y: 8) .shadow(radius: 24, y: 8)
} }
@@ -313,6 +322,7 @@ struct VariantA: View {
} }
// MARK: - Variant B — gate window (first run), pill (repeat runs) // MARK: - Variant B — gate window (first run), pill (repeat runs)
struct VariantB: View { struct VariantB: View {
@EnvironmentObject var model: GateModel @EnvironmentObject var model: GateModel
@@ -393,6 +403,7 @@ private struct GateWindow: View {
} }
// MARK: - Variant C — inline banner, never blocks // MARK: - Variant C — inline banner, never blocks
struct VariantC: View { struct VariantC: View {
@EnvironmentObject var model: GateModel @EnvironmentObject var model: GateModel
@@ -413,10 +424,10 @@ struct VariantC: View {
Image(systemName: "exclamationmark.triangle.fill") Image(systemName: "exclamationmark.triangle.fill")
.foregroundStyle(Tok.accent) .foregroundStyle(Tok.accent)
VStack(alignment: .leading, spacing: 8) { VStack(alignment: .leading, spacing: 8) {
(Text("Engine unavailable. ").font(.system(size: 12.5, weight: .semibold)) Text("Engine unavailable. ").font(.system(size: 12.5, weight: .semibold))
+ Text("Passes and Sessions need Hermes; the editor keeps working.") + Text("Passes and Sessions need Hermes; the editor keeps working.")
.font(.system(size: 12.5)) .font(.system(size: 12.5))
.foregroundStyle(Tok.muted)) .foregroundStyle(Tok.muted)
InstallSteps() InstallSteps()
} }
Spacer(minLength: 12) Spacer(minLength: 12)
@@ -441,6 +452,7 @@ struct VariantC: View {
} }
// MARK: - Root + switcher // MARK: - Root + switcher
struct GatePrototypeRoot: View { struct GatePrototypeRoot: View {
@StateObject private var model = GateModel() @StateObject private var model = GateModel()
@State private var variant = "A" @State private var variant = "A"
+1 -1
View File
@@ -4,5 +4,5 @@ import PackageDescription
let package = Package( let package = Package(
name: "ApexHTMLSpike", name: "ApexHTMLSpike",
platforms: [.macOS(.v26)], platforms: [.macOS(.v26)],
targets: [.executableTarget(name: "ApexHTMLSpike")] targets: [.executableTarget(name: "ApexHTMLSpike")],
) )
@@ -15,10 +15,16 @@ enum MarkdownChunker {
var out: [String] = [] var out: [String] = []
var i = 0 var i = 0
while i < lines.count { while i < lines.count {
if isBlank(lines[i]) { i += 1; continue } if isBlank(lines[i]) {
if !out.isEmpty { out.append("") } i += 1; continue
}
if !out.isEmpty {
out.append("")
}
out.append("<!--S:\(i + 1)-->") out.append("<!--S:\(i + 1)-->")
while i < lines.count && !isBlank(lines[i]) { out.append(String(lines[i])); i += 1 } while i < lines.count, !isBlank(lines[i]) {
out.append(String(lines[i])); i += 1
}
} }
return out.joined(separator: "\n") return out.joined(separator: "\n")
} }
@@ -38,8 +44,12 @@ enum HTMLStamper {
enum Apex { enum Apex {
nonisolated static func binaryPath() -> String? { nonisolated static func binaryPath() -> String? {
if let env = ProcessInfo.processInfo.environment["APEX_PATH"] { return env } if let env = ProcessInfo.processInfo.environment["APEX_PATH"] {
for p in ["/opt/homebrew/bin/apex", "/usr/local/bin/apex"] where FileManager.default.isExecutableFile(atPath: p) { return p } return env
}
for p in ["/opt/homebrew/bin/apex", "/usr/local/bin/apex"] where FileManager.default.isExecutableFile(atPath: p) {
return p
}
return nil return nil
} }
@@ -127,7 +137,7 @@ struct ReadingWebView: NSViewRepresentable {
} }
} }
// CSS custom properties fed from the ProseTypography slots (#70 defaults) + flow knobs (#71). /// CSS custom properties fed from the ProseTypography slots (#70 defaults) + flow knobs (#71).
static let css = """ static let css = """
:root { :root {
--body-face: "Concourse OT", "Iowan Old Style", serif; --body-face: "Concourse OT", "Iowan Old Style", serif;
@@ -177,7 +187,7 @@ struct ReadingWebView: NSViewRepresentable {
"<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\(css)</style></head><body>\(html)</body></html>" "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><style>\(css)</style></head><body>\(html)</body></html>"
} }
// Mapping probes: click → source line; ⌘-click → open; scroll → top visible source line. /// Mapping probes: click → source line; ⌘-click → open; scroll → top visible source line.
static let probeJS = """ static let probeJS = """
function stamped(el){ return el.closest('[data-source-line]'); } function stamped(el){ return el.closest('[data-source-line]'); }
document.addEventListener('click', function(e){ document.addEventListener('click', function(e){
@@ -218,32 +228,34 @@ struct ReadingWebView: NSViewRepresentable {
self.onSourceLine = onSourceLine self.onSourceLine = onSourceLine
} }
func webView(_ wv: WKWebView, didFinish: WKNavigation!) { func webView(_: WKWebView, didFinish _: WKNavigation!) {
if let t0 = paintStart { if let t0 = paintStart {
let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000 let ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1_000_000
onStats(Stats(paintMS: ms)) onStats(Stats(paintMS: ms))
} }
} }
// Spike diagnostics: surface the silent-load failure path. /// Spike diagnostics: surface the silent-load failure path.
func webView(_ wv: WKWebView, didFail na: WKNavigation!, withError error: Error) { func webView(_: WKWebView, didFail _: WKNavigation!, withError error: Error) {
FileHandle.standardError.write(Data("didFail: \(error)\n".utf8)) FileHandle.standardError.write(Data("didFail: \(error)\n".utf8))
} }
func webView(_ wv: WKWebView, didFailProvisionalNavigation na: WKNavigation!, withError error: Error) { func webView(_: WKWebView, didFailProvisionalNavigation _: WKNavigation!, withError error: Error) {
FileHandle.standardError.write(Data("didFailProvisional: \(error)\n".utf8)) FileHandle.standardError.write(Data("didFailProvisional: \(error)\n".utf8))
} }
nonisolated func webViewWebContentProcessDidTerminate(_ wv: WKWebView) { nonisolated func webViewWebContentProcessDidTerminate(_: WKWebView) {
FileHandle.standardError.write(Data("webContentProcessDidTerminate\n".utf8)) FileHandle.standardError.write(Data("webContentProcessDidTerminate\n".utf8))
} }
// Allow our own loadHTMLString (file:// baseURL / about:blank main frame); cancel the rest. /// 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. /// The initial load is a navigation too — a blanket .cancel kills the page before it paints.
func webView(_ wv: WKWebView, decidePolicyFor na: WKNavigationAction, func webView(_: WKWebView, decidePolicyFor na: WKNavigationAction,
decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void) { decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void)
{
if na.targetFrame?.isMainFrame == true, if na.targetFrame?.isMainFrame == true,
let u = na.request.url, u.scheme == "file" || u.absoluteString == "about:blank" { let u = na.request.url, u.scheme == "file" || u.absoluteString == "about:blank"
{
decisionHandler(.allow); return decisionHandler(.allow); return
} }
if na.modifierFlags.contains(.command), let url = na.request.url, url.scheme?.hasPrefix("http") == true { if na.modifierFlags.contains(.command), let url = na.request.url, url.scheme?.hasPrefix("http") == true {
@@ -252,18 +264,24 @@ struct ReadingWebView: NSViewRepresentable {
decisionHandler(.cancel) decisionHandler(.cancel)
} }
func userContentController(_ ucc: WKUserContentController, didReceive message: WKScriptMessage) { func userContentController(_: WKUserContentController, didReceive message: WKScriptMessage) {
switch message.name { switch message.name {
case "openLink": case "openLink":
if let s = message.body as? String, let url = URL(string: s) { NSWorkspace.shared.open(url) } if let s = message.body as? String, let url = URL(string: s) {
NSWorkspace.shared.open(url)
}
case "sourceClick", "sourceScroll": case "sourceClick", "sourceScroll":
if let s = message.body as? String, let n = Int(s) { onSourceLine(message.name == "sourceClick" ? "click" : "top", n) } if let s = message.body as? String, let n = Int(s) {
onSourceLine(message.name == "sourceClick" ? "click" : "top", n)
}
default: break default: break
} }
} }
} }
func makeCoordinator() -> Coordinator { Coordinator(onStats: onStats, onSourceLine: onSourceLine) } func makeCoordinator() -> Coordinator {
Coordinator(onStats: onStats, onSourceLine: onSourceLine)
}
} }
// MARK: - Shell // MARK: - Shell
@@ -282,8 +300,12 @@ struct SpikeApp: App {
// ponytail: one runnable check for the mapping logic — `swift run ApexHTMLSpike --check` // ponytail: one runnable check for the mapping logic — `swift run ApexHTMLSpike --check`
init() { init() {
let args = CommandLine.arguments let args = CommandLine.arguments
if args.contains("--check") { Self.selfCheck(); exit(0) } if args.contains("--check") {
if let i = args.firstIndex(of: "--pipeline"), args.count > i + 1 { Self.pipeline(path: args[i + 1]); exit(0) } 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. /// Headless end-to-end: chunk → apex → stamp → validate coverage. Prints per-file numbers.
@@ -302,7 +324,9 @@ struct SpikeApp: App {
let n = Int((stamped as NSString).substring(with: m.range(at: 1)))! let n = Int((stamped as NSString).substring(with: m.range(at: 1)))!
count += 1; lineSum += n count += 1; lineSum += n
let idx = n - 1 let idx = n - 1
if idx < 0 || idx >= lines.count || lines[idx].allSatisfy({ $0 == " " || $0 == "\t" || $0 == "\r" }) { bad += 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)") 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) exit(bad == 0 ? 0 : 2)
@@ -325,7 +349,7 @@ struct SpikeApp: App {
} }
final class AppDelegate: NSObject, NSApplicationDelegate { final class AppDelegate: NSObject, NSApplicationDelegate {
nonisolated func applicationDidFinishLaunching(_ n: Notification) {} nonisolated func applicationDidFinishLaunching(_: Notification) {}
} }
struct ContentView: View { struct ContentView: View {
@@ -353,18 +377,30 @@ struct ContentView: View {
// document re-spawns the web view (~hundreds of ms) and blanks the pane — // document re-spawns the web view (~hundreds of ms) and blanks the pane —
// the dominant switch cost, far bigger than apex itself. // the dominant switch cost, far bigger than apex itself.
ReadingWebView(fileURL: sel, onStats: { s in ReadingWebView(fileURL: sel, onStats: { s in
if s.apexMS > 0 || s.error != nil { stats = s } else { stats.paintMS = s.paintMS } if s.apexMS > 0 || s.error != nil {
stats = s
} else {
stats.paintMS = s.paintMS
}
}, onSourceLine: { kind, line in }, onSourceLine: { kind, line in
if kind == "click" { clickedLine = line } else { topLine = line } if kind == "click" {
clickedLine = line
} else {
topLine = line
}
}) })
} else { Text("pick a post").frame(maxWidth: .infinity) } } else {
Text("pick a post").frame(maxWidth: .infinity)
}
} }
} }
} }
.safeAreaInset(edge: .bottom) { statsBar } .safeAreaInset(edge: .bottom) { statsBar }
.toolbar { .toolbar {
Button("Open…") { openPanel() } Button("Open…") { openPanel() }
if let apex = Apex.binaryPath() { Text("apex: \(apex)") } if let apex = Apex.binaryPath() {
Text("apex: \(apex)")
}
} }
.onAppear { load(arg: CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : nil) } .onAppear { load(arg: CommandLine.arguments.count > 1 ? CommandLine.arguments[1] : nil) }
} }
@@ -375,9 +411,15 @@ struct ContentView: View {
Text(String(format: "apex %.0f ms", stats.apexMS)) Text(String(format: "apex %.0f ms", stats.apexMS))
Text(String(format: "paint %.0f ms", stats.paintMS)) Text(String(format: "paint %.0f ms", stats.paintMS))
Text(ByteCountFormatter.string(fromByteCount: Int64(stats.htmlBytes), countStyle: .file)) Text(ByteCountFormatter.string(fromByteCount: Int64(stats.htmlBytes), countStyle: .file))
if let t = topLine { Text("top src line \(t)") } if let t = topLine {
if let c = clickedLine { Text("click → src line \(c)") } Text("top src line \(t)")
if let e = stats.error { Text(e).foregroundStyle(.red).lineLimit(1) } }
if let c = clickedLine {
Text("click → src line \(c)")
}
if let e = stats.error {
Text(e).foregroundStyle(.red).lineLimit(1)
}
Spacer() Spacer()
} }
.font(.system(size: 11, design: .monospaced)).padding(6) .font(.system(size: 11, design: .monospaced)).padding(6)
@@ -388,11 +430,12 @@ struct ContentView: View {
if let a = arg { if let a = arg {
let u = URL(fileURLWithPath: a).standardizedFileURL let u = URL(fileURLWithPath: a).standardizedFileURL
files = (try? FileManager.default.contentsOfDirectory( files = (try? FileManager.default.contentsOfDirectory(
at: u.deletingLastPathComponent(), includingPropertiesForKeys: nil at: u.deletingLastPathComponent(), includingPropertiesForKeys: nil,
).filter { $0.pathExtension == "md" }.sorted { $0.lastPathComponent < $1.lastPathComponent }) ?? [u] ).filter { $0.pathExtension == "md" }.sorted { $0.lastPathComponent < $1.lastPathComponent }) ?? [u]
selected = files.first(where: { $0 == u }) ?? u selected = files.first(where: { $0 == u }) ?? u
} else if let dir = URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent("../prose") as URL?, } else if let dir = URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent("../prose") as URL?,
let list = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil) { let list = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)
{
files = list.filter { $0.pathExtension == "md" }.sorted { $0.lastPathComponent < $1.lastPathComponent } files = list.filter { $0.pathExtension == "md" }.sorted { $0.lastPathComponent < $1.lastPathComponent }
selected = files.first selected = files.first
} }
@@ -401,6 +444,8 @@ struct ContentView: View {
private func openPanel() { private func openPanel() {
let p = NSOpenPanel(); p.allowsMultipleSelection = false; p.canChooseDirectories = false let p = NSOpenPanel(); p.allowsMultipleSelection = false; p.canChooseDirectories = false
p.allowedContentTypes = [.init(filenameExtension: "md")!] p.allowedContentTypes = [.init(filenameExtension: "md")!]
if p.runModal() == .OK, let u = p.url { files.append(u); selected = u } if p.runModal() == .OK, let u = p.url {
files.append(u); selected = u
}
} }
} }
+1 -1
View File
@@ -4,5 +4,5 @@ import PackageDescription
let package = Package( let package = Package(
name: "BlocksSpike", name: "BlocksSpike",
platforms: [.macOS(.v26)], platforms: [.macOS(.v26)],
targets: [.executableTarget(name: "BlocksSpike")] targets: [.executableTarget(name: "BlocksSpike")],
) )
@@ -22,10 +22,18 @@ nonisolated enum BlockModel {
} }
static func kind(of raw: String) -> Kind { static func kind(of raw: String) -> Kind {
if raw.hasPrefix("## ") { return .heading2 } if raw.hasPrefix("## ") {
if raw.hasPrefix("# ") { return .heading1 } return .heading2
if raw.hasPrefix("> ") { return .quote } }
if raw.count <= 6, !raw.isEmpty, raw.allSatisfy({ $0 == "*" || $0 == "-" || $0 == "_" || $0.isWhitespace }) { return .hr } 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 return .paragraph
} }
@@ -49,11 +57,11 @@ nonisolated enum BlockModel {
/// Marker-stripped plain text (anchor search runs over this). /// Marker-stripped plain text (anchor search runs over this).
static func plainText(_ raw: String) -> String { static func plainText(_ raw: String) -> String {
switch kind(of: raw) { switch kind(of: raw) {
case .heading1: return String(raw.dropFirst(2)) case .heading1: String(raw.dropFirst(2))
case .heading2: return String(raw.dropFirst(3)) case .heading2: String(raw.dropFirst(3))
case .quote: return String(raw.dropFirst(2)) case .quote: String(raw.dropFirst(2))
case .hr: return "" case .hr: ""
case .paragraph: return raw case .paragraph: raw
} }
} }
+37 -17
View File
@@ -18,7 +18,9 @@ struct SpikeApp: App {
// ponytail: one runnable check — `swift run --package-path spike/blocks --check` // ponytail: one runnable check — `swift run --package-path spike/blocks --check`
init() { init() {
if CommandLine.arguments.contains("--check") { Self.selfCheck(); exit(0) } if CommandLine.arguments.contains("--check") {
Self.selfCheck(); exit(0)
}
} }
static func selfCheck() { static func selfCheck() {
@@ -77,8 +79,10 @@ struct ContentView: View {
/// Arg as given, then the default piece (run.sh passes absolute paths). /// Arg as given, then the default piece (run.sh passes absolute paths).
static func loadCorpus(_ arg: String?) -> String { static func loadCorpus(_ arg: String?) -> String {
for c in [arg, "spike/prose/the-expected-value-of-showing.md"].compactMap({ $0 }) { 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 } if let s = try? String(contentsOfFile: c, encoding: .utf8) {
return s
}
} }
return "# Spike C\n\n(No corpus file found — run from repo root.)" return "# Spike C\n\n(No corpus file found — run from repo root.)"
} }
@@ -101,7 +105,7 @@ struct ContentView: View {
onFocus: { onFocus: {
focusedID = block.id focusedID = block.id
hint = "Focused block \(block.id.uuidString.prefix(4)) — type to edit." hint = "Focused block \(block.id.uuidString.prefix(4)) — type to edit."
} },
) )
.id(block.id) .id(block.id)
} }
@@ -110,7 +114,9 @@ struct ContentView: View {
.padding(.horizontal, 40) .padding(.horizontal, 40)
.padding(.vertical, 24) .padding(.vertical, 24)
.onChange(of: anchorID) { id in .onChange(of: anchorID) { id in
if let id { proxy.scrollTo(id, anchor: .center) } if let id {
proxy.scrollTo(id, anchor: .center)
}
} }
} }
} }
@@ -129,7 +135,9 @@ struct ContentView: View {
HStack(spacing: 12) { 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("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") } Button("Stale anchor") { applyAnchor("this quote was deleted from the text") }
if anchorID != nil { Text("anchored").foregroundStyle(.secondary).font(.caption) } if anchorID != nil {
Text("anchored").foregroundStyle(.secondary).font(.caption)
}
Spacer() Spacer()
Text("load \(String(format: "%.1f", loadMs)) ms · \(blocks.count) blocks").foregroundStyle(.secondary).font(.caption) Text("load \(String(format: "%.1f", loadMs)) ms · \(blocks.count) blocks").foregroundStyle(.secondary).font(.caption)
} }
@@ -180,7 +188,9 @@ struct ContentView: View {
guard bw.count >= qw.count else { continue } guard bw.count >= qw.count else { continue }
if (0 ... bw.count - qw.count).contains(where: { s in if (0 ... bw.count - qw.count).contains(where: { s in
(s ..< s + qw.count).allSatisfy { bw[$0] == qw[$0 - s] } (s ..< s + qw.count).allSatisfy { bw[$0] == qw[$0 - s] }
}) { return b } }) {
return b
}
} }
return nil return nil
} }
@@ -216,7 +226,8 @@ private struct BlockRow: View {
init(block: Block, isFocused: Bool, isAnchored: Bool, init(block: Block, isFocused: Bool, isAnchored: Bool,
onEdit: @escaping (String) -> Void, onSplit: @escaping (Int) -> Void, onEdit: @escaping (String) -> Void, onSplit: @escaping (Int) -> Void,
onMerge: @escaping () -> Void, onFocus: @escaping () -> Void) { onMerge: @escaping () -> Void, onFocus: @escaping () -> Void)
{
self.block = block self.block = block
self.isFocused = isFocused self.isFocused = isFocused
self.isAnchored = isAnchored self.isAnchored = isAnchored
@@ -301,20 +312,28 @@ struct SingleBlockEditor: NSViewRepresentable {
return tv return tv
} }
func updateNSView(_ tv: NSTextView, context: Context) { func updateNSView(_ tv: NSTextView, context _: Context) {
if tv.string != text { tv.string = text } if tv.string != text {
tv.string = text
}
} }
func makeCoordinator() -> Coordinator { Coordinator(self) } func makeCoordinator() -> Coordinator {
Coordinator(self)
}
static var typing: [NSAttributedString.Key: Any] { [ static var typing: [NSAttributedString.Key: Any] {
[
.font: NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17) ?? .systemFont(ofSize: 17), .font: NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17) ?? .systemFont(ofSize: 17),
] } ]
}
final class Coordinator: NSObject, NSTextViewDelegate { final class Coordinator: NSObject, NSTextViewDelegate {
let parent: SingleBlockEditor let parent: SingleBlockEditor
weak var textView: NSTextView? weak var textView: NSTextView?
init(_ parent: SingleBlockEditor) { self.parent = parent } init(_ parent: SingleBlockEditor) {
self.parent = parent
}
func textDidChange(_ notification: Notification) { func textDidChange(_ notification: Notification) {
guard let tv = notification.object as? NSTextView else { return } guard let tv = notification.object as? NSTextView else { return }
@@ -322,7 +341,7 @@ struct SingleBlockEditor: NSViewRepresentable {
parent.onEdit(tv.string) parent.onEdit(tv.string)
} }
// Enter = split at cursor, ⌫ at position 0 = merge up — the block-model lift meter. /// Enter = split at cursor, ⌫ at position 0 = merge up — the block-model lift meter.
func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool { func textView(_ textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
if commandSelector == #selector(NSResponder.insertNewline(_:)) { if commandSelector == #selector(NSResponder.insertNewline(_:)) {
parent.onSplit(textView.selectedRange().location) parent.onSplit(textView.selectedRange().location)
@@ -341,10 +360,11 @@ struct SingleBlockEditor: NSViewRepresentable {
// ponytail: bare SPM executable gets .accessory activation — no window. Set policy BEFORE scenes build. // ponytail: bare SPM executable gets .accessory activation — no window. Set policy BEFORE scenes build.
final class AppDelegate: NSObject, NSApplicationDelegate { final class AppDelegate: NSObject, NSApplicationDelegate {
func applicationWillFinishLaunching(_ notification: Notification) { func applicationWillFinishLaunching(_: Notification) {
NSApp.setActivationPolicy(.regular) NSApp.setActivationPolicy(.regular)
} }
func applicationDidFinishLaunching(_ notification: Notification) {
func applicationDidFinishLaunching(_: Notification) {
NSApp.activate(ignoringOtherApps: true) NSApp.activate(ignoringOtherApps: true)
} }
} }
+1 -1
View File
@@ -8,5 +8,5 @@ let package = Package(
// Fork fact from map #16: same fork + revision as Classis (0.15.8-helm = 3ce6007). // 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"), .package(url: "https://github.com/AlexKucera/CodeEditSourceEditor.git", exact: "0.15.8-helm"),
], ],
targets: [.executableTarget(name: "CodeEditSpike", dependencies: ["CodeEditSourceEditor"])] targets: [.executableTarget(name: "CodeEditSpike", dependencies: ["CodeEditSourceEditor"])],
) )
@@ -10,7 +10,7 @@ import SwiftUI
// MARK: - Prose theme (uniform-font compromise documented in the resolution) // MARK: - Prose theme (uniform-font compromise documented in the resolution)
enum ProseTheme { enum ProseTheme {
// Iowan Old Style like Spike B / the web proto; falls back to system serif. /// Iowan Old Style like Spike B / the web proto; falls back to system serif.
static var bodyFont: NSFont { static var bodyFont: NSFont {
NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17) NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17)
?? NSFont.systemFont(ofSize: 17, weight: .regular, width: .standard) ?? NSFont.systemFont(ofSize: 17, weight: .regular, width: .standard)
@@ -38,7 +38,7 @@ enum ProseTheme {
numbers: .init(color: ink), numbers: .init(color: ink),
strings: .init(color: NSColor(srgbRed: 0.25, green: 0.42, blue: 0.31, alpha: 1)), // blockquote tint strings: .init(color: NSColor(srgbRed: 0.25, green: 0.42, blue: 0.31, alpha: 1)), // blockquote tint
characters: .init(color: ink), characters: .init(color: ink),
comments: .init(color: dim) comments: .init(color: dim),
) )
} }
} }
@@ -59,7 +59,7 @@ final class ProseHighlighter: HighlightProviding {
textView: TextView, textView: TextView,
range: NSRange, range: NSRange,
delta: Int, delta: Int,
completion: @escaping @MainActor (Result<IndexSet, Error>) -> Void completion: @escaping @MainActor (Result<IndexSet, Error>) -> Void,
) { ) {
wrapped.applyEdit(textView: textView, range: range, delta: delta, completion: completion) wrapped.applyEdit(textView: textView, range: range, delta: delta, completion: completion)
} }
@@ -67,13 +67,13 @@ final class ProseHighlighter: HighlightProviding {
func queryHighlightsFor( func queryHighlightsFor(
textView: TextView, textView: TextView,
range: NSRange, range: NSRange,
completion: @escaping @MainActor (Result<[HighlightRange], Error>) -> Void completion: @escaping @MainActor (Result<[HighlightRange], Error>) -> Void,
) { ) {
wrapped.queryHighlightsFor(textView: textView, range: range) { result in wrapped.queryHighlightsFor(textView: textView, range: range) { result in
switch result { switch result {
case .failure(let error): case let .failure(error):
completion(.failure(error)) completion(.failure(error))
case .success(let tsRanges): case let .success(tsRanges):
var out = tsRanges var out = tsRanges
let ns = textView.string as NSString let ns = textView.string as NSString
let safe = range.intersection(NSRange(location: 0, length: ns.length)) ?? range let safe = range.intersection(NSRange(location: 0, length: ns.length)) ?? range
@@ -95,13 +95,13 @@ final class ProseHighlighter: HighlightProviding {
if textLen > 0 { if textLen > 0 {
out.append(HighlightRange( out.append(HighlightRange(
range: NSRange(location: lineRange.location + markerLen, length: textLen), range: NSRange(location: lineRange.location + markerLen, length: textLen),
capture: .type capture: .type,
)) ))
} }
// marker → dim // marker → dim
out.append(HighlightRange( out.append(HighlightRange(
range: NSRange(location: lineRange.location, length: markerLen), range: NSRange(location: lineRange.location, length: markerLen),
capture: .keyword capture: .keyword,
)) ))
} else if line.hasPrefix(">") { } else if line.hasPrefix(">") {
// quote line: text → tinted .string, markers dimmed // quote line: text → tinted .string, markers dimmed
@@ -116,7 +116,7 @@ final class ProseHighlighter: HighlightProviding {
for (off, ch) in line.utf16.enumerated() where marks.contains(ch) { for (off, ch) in line.utf16.enumerated() where marks.contains(ch) {
out.append(HighlightRange( out.append(HighlightRange(
range: NSRange(location: lineRange.location + off, length: 1), range: NSRange(location: lineRange.location + off, length: 1),
capture: .keyword capture: .keyword,
)) ))
} }
} }
@@ -155,7 +155,7 @@ nonisolated enum AnchorSearch {
let to = textWords[start + quoteWords.count - 1].range.upperBound let to = textWords[start + quoteWords.count - 1].range.upperBound
return NSRange( return NSRange(
location: text.utf16.distance(from: text.startIndex, to: from), location: text.utf16.distance(from: text.startIndex, to: from),
length: text.utf16.distance(from: from, to: to) length: text.utf16.distance(from: from, to: to),
) )
} }
} }
@@ -179,7 +179,9 @@ struct SpikeApp: App {
// ponytail: one runnable check for the prose pass + anchor logic — `run.sh --check` // ponytail: one runnable check for the prose pass + anchor logic — `run.sh --check`
init() { init() {
if CommandLine.arguments.contains("--check") { Self.selfCheck(); exit(0) } if CommandLine.arguments.contains("--check") {
Self.selfCheck(); exit(0)
}
} }
static func selfCheck() { static func selfCheck() {
@@ -201,7 +203,7 @@ struct SpikeApp: App {
"FAIL: heading marker not dimmed") "FAIL: heading marker not dimmed")
// anchor: live quote found; stale → nil; whitespace-tolerant // 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.\"" 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 } 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) assert((ns.substring(with: r) as NSString).length > 50)
let squished = quote.components(separatedBy: .newlines).joined(separator: " ") let squished = quote.components(separatedBy: .newlines).joined(separator: " ")
assert(AnchorSearch.range(of: squished, in: text) != nil, "FAIL: whitespace tolerance") assert(AnchorSearch.range(of: squished, in: text) != nil, "FAIL: whitespace tolerance")
@@ -282,7 +284,7 @@ struct ContentView: View {
configuration: config, configuration: config,
state: $editorState, state: $editorState,
highlightProviders: [ProseHighlighter()], highlightProviders: [ProseHighlighter()],
coordinators: [ControllerCapture(onCapture: { box.controller = $0 })] coordinators: [ControllerCapture(onCapture: { box.controller = $0 })],
) )
.frame(maxWidth: 720) .frame(maxWidth: 720)
.frame(maxWidth: .infinity) .frame(maxWidth: .infinity)
@@ -295,17 +297,17 @@ struct ContentView: View {
theme: ProseTheme.theme, theme: ProseTheme.theme,
font: ProseTheme.bodyFont, font: ProseTheme.bodyFont,
lineHeightMultiple: 1.45, // paragraph rhythm via line-height (no per-paragraph spacing on substrate) lineHeightMultiple: 1.45, // paragraph rhythm via line-height (no per-paragraph spacing on substrate)
wrapLines: true wrapLines: true,
), ),
behavior: .init(reformatAtColumn: 10_000), // never hard-wrap prose behavior: .init(reformatAtColumn: 10000), // never hard-wrap prose
peripherals: .init( peripherals: .init(
showGutter: false, // no line numbers in a writing app showGutter: false, // no line numbers in a writing app
showMinimap: false, showMinimap: false,
showReformattingGuide: false, showReformattingGuide: false,
showFoldingRibbon: false, showFoldingRibbon: false,
invisibleCharactersConfiguration: .init(showSpaces: false, showTabs: false, showLineEndings: false), invisibleCharactersConfiguration: .init(showSpaces: false, showTabs: false, showLineEndings: false),
warningCharacters: [] warningCharacters: [],
) ),
) )
} }
@@ -315,7 +317,9 @@ struct ContentView: View {
Divider().frame(height: 14) 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("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") } Button("Stale anchor") { applyAnchor("this quote was deleted from the text") }
if let note = anchorNote { Text(note).foregroundStyle(.secondary).font(.caption) } if let note = anchorNote {
Text(note).foregroundStyle(.secondary).font(.caption)
}
Spacer() Spacer()
Text("load \(String(format: "%.1f", loadMs)) ms").foregroundStyle(.secondary).font(.caption) Text("load \(String(format: "%.1f", loadMs)) ms").foregroundStyle(.secondary).font(.caption)
} }
@@ -338,7 +342,7 @@ struct ContentView: View {
// Layer-backed emphasis highlight (survives re-highlighting) + scroll-to + selection. // Layer-backed emphasis highlight (survives re-highlighting) + scroll-to + selection.
controller.textView.emphasisManager?.replaceEmphases( controller.textView.emphasisManager?.replaceEmphases(
[Emphasis(range: r, style: .outline(color: ProseTheme.accent, fill: false))], [Emphasis(range: r, style: .outline(color: ProseTheme.accent, fill: false))],
for: "fix-card-anchor" for: "fix-card-anchor",
) )
controller.setCursorPositions([CursorPosition(range: r)], scrollToVisible: true) controller.setCursorPositions([CursorPosition(range: r)], scrollToVisible: true)
} }
@@ -350,9 +354,13 @@ struct ContentView: View {
final class ControllerBox: @unchecked Sendable { final class ControllerBox: @unchecked Sendable {
var controller: TextViewController? var controller: TextViewController?
} }
final class ControllerCapture: TextViewCoordinator { final class ControllerCapture: TextViewCoordinator {
let onCapture: (TextViewController) -> Void let onCapture: (TextViewController) -> Void
init(onCapture: @escaping (TextViewController) -> Void) { self.onCapture = onCapture } init(onCapture: @escaping (TextViewController) -> Void) {
self.onCapture = onCapture
}
func prepareCoordinator(controller: TextViewController) { func prepareCoordinator(controller: TextViewController) {
onCapture(controller) onCapture(controller)
} }
@@ -373,7 +381,7 @@ extension SpikeApp {
} }
let attr = (try? AttributedString( let attr = (try? AttributedString(
markdown: p, markdown: p,
options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace) options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace),
)) ?? AttributedString(p) )) ?? AttributedString(p)
return (level, attr) return (level, attr)
} }
@@ -382,10 +390,11 @@ extension SpikeApp {
// ponytail: bare SPM executable gets .accessory activation — no window. Set policy BEFORE scenes build. // ponytail: bare SPM executable gets .accessory activation — no window. Set policy BEFORE scenes build.
final class AppDelegate: NSObject, NSApplicationDelegate { final class AppDelegate: NSObject, NSApplicationDelegate {
func applicationWillFinishLaunching(_ notification: Notification) { func applicationWillFinishLaunching(_: Notification) {
NSApp.setActivationPolicy(.regular) NSApp.setActivationPolicy(.regular)
} }
func applicationDidFinishLaunching(_ notification: Notification) {
func applicationDidFinishLaunching(_: Notification) {
NSApp.activate(ignoringOtherApps: true) NSApp.activate(ignoringOtherApps: true)
} }
} }
+1 -1
View File
@@ -4,5 +4,5 @@ import PackageDescription
let package = Package( let package = Package(
name: "TextKit2Spike", name: "TextKit2Spike",
platforms: [.macOS(.v26)], platforms: [.macOS(.v26)],
targets: [.executableTarget(name: "TextKit2Spike")] targets: [.executableTarget(name: "TextKit2Spike")],
) )
@@ -62,14 +62,18 @@ struct EditorPane: NSViewRepresentable {
tv.scrollRangeToVisible(anchorHighlight) tv.scrollRangeToVisible(anchorHighlight)
} }
func makeCoordinator() -> Coordinator { Coordinator(onEdit: onEdit) } func makeCoordinator() -> Coordinator {
Coordinator(onEdit: onEdit)
}
final class Coordinator: NSObject, NSTextViewDelegate { final class Coordinator: NSObject, NSTextViewDelegate {
let onEdit: ((String) -> Void)? let onEdit: ((String) -> Void)?
weak var textView: NSTextView? weak var textView: NSTextView?
var loadedHash: Int = 0 var loadedHash: Int = 0
init(onEdit: ((String) -> Void)?) { self.onEdit = onEdit } init(onEdit: ((String) -> Void)?) {
self.onEdit = onEdit
}
func textDidChange(_ notification: Notification) { func textDidChange(_ notification: Notification) {
guard let tv = notification.object as? NSTextView, let storage = tv.textStorage else { return } guard let tv = notification.object as? NSTextView, let storage = tv.textStorage else { return }
@@ -13,10 +13,18 @@ nonisolated enum ProsePresenter {
static func lineKind(_ line: String) -> LineKind { static func lineKind(_ line: String) -> LineKind {
let t = line.drop(while: { $0 == " " }) let t = line.drop(while: { $0 == " " })
if t.hasPrefix("## ") { return .heading2 } if t.hasPrefix("## ") {
if t.hasPrefix("# ") { return .heading1 } return .heading2
if t.hasPrefix("> ") { return .quote } }
if !t.isEmpty && t.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) { return .syntaxOnly } if t.hasPrefix("# ") {
return .heading1
}
if t.hasPrefix("> ") {
return .quote
}
if !t.isEmpty, t.allSatisfy({ $0 == "*" || $0 == " " || $0 == "-" || $0 == "_" }) {
return .syntaxOnly
}
return .body return .body
} }
@@ -56,13 +64,20 @@ nonisolated enum ProsePresenter {
} }
// Typography: system serif for prose (New York), 17pt body, scaled headings — the web proto's Iowan/Charter stance. // 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 serif: NSFont {
static var bodyFont: NSFont { NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17) NSFont.systemFont(ofSize: 17, weight: .regular, width: .compressed)
?? NSFont.systemFont(ofSize: 17) } }
static var bodyAttributes: [NSAttributedString.Key: Any] { [ static var bodyFont: NSFont {
NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17)
?? NSFont.systemFont(ofSize: 17)
}
static var bodyAttributes: [NSAttributedString.Key: Any] {
[
.font: bodyFont, .paragraphStyle: paragraph(.body), .foregroundColor: NSColor(red: 0.10, green: 0.10, blue: 0.09, alpha: 1), .font: bodyFont, .paragraphStyle: paragraph(.body), .foregroundColor: NSColor(red: 0.10, green: 0.10, blue: 0.09, alpha: 1),
] } ]
}
static func attributes(for kind: LineKind) -> [NSAttributedString.Key: Any] { static func attributes(for kind: LineKind) -> [NSAttributedString.Key: Any] {
switch kind { switch kind {
@@ -80,15 +95,16 @@ nonisolated enum ProsePresenter {
let line = ns.substring(with: range) let line = ns.substring(with: range)
let kind = lineKind(line) let kind = lineKind(line)
// prefix markers // prefix markers
let markerLen: Int let markerLen = switch kind {
switch kind { case .heading1: 2
case .heading1: markerLen = 2 case .heading2: 3
case .heading2: markerLen = 3 case .quote: 2
case .quote: markerLen = 2 default: 0
default: markerLen = 0
} }
let dim: [NSAttributedString.Key: Any] = [.foregroundColor: NSColor(white: 0.55, alpha: 1), .font: NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)] 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))) } if markerLen > 0 {
out.addAttributes(dim, range: NSRange(location: range.location, length: min(markerLen, range.length)))
}
// inline marks in body/quote // inline marks in body/quote
if kind == .body || kind == .quote { if kind == .body || kind == .quote {
for (offset, ch) in line.utf16.enumerated() { for (offset, ch) in line.utf16.enumerated() {
@@ -16,7 +16,9 @@ struct SpikeApp: App {
// ponytail: one runnable check for the anchor logic — `swift run TextKit2Spike --check` // ponytail: one runnable check for the anchor logic — `swift run TextKit2Spike --check`
init() { init() {
if CommandLine.arguments.contains("--check") { Self.selfCheck(); exit(0) } if CommandLine.arguments.contains("--check") {
Self.selfCheck(); exit(0)
}
} }
static func selfCheck() { static func selfCheck() {
@@ -67,7 +69,7 @@ struct ContentView: View {
@State private var loadMs: Double = 0 @State private var loadMs: Double = 0
@State private var doc: NSAttributedString @State private var doc: NSAttributedString
// calibration piece default; PERF-3k via arg /// calibration piece default; PERF-3k via arg
init() { init() {
let args = CommandLine.arguments let args = CommandLine.arguments
let path = args.count > 1 ? args[1] : "spike/prose/the-expected-value-of-showing.md" let path = args.count > 1 ? args[1] : "spike/prose/the-expected-value-of-showing.md"
@@ -115,7 +117,9 @@ struct ContentView: View {
Divider().frame(height: 14) 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("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") } 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) } if let a = anchor {
Text("anchored @ \(a.location)–\(a.location + a.length)").foregroundStyle(.secondary).font(.caption)
}
Spacer() Spacer()
Text("load \(String(format: "%.1f", loadMs)) ms").foregroundStyle(.secondary).font(.caption) Text("load \(String(format: "%.1f", loadMs)) ms").foregroundStyle(.secondary).font(.caption)
} }
@@ -139,10 +143,11 @@ struct ContentView: View {
// ponytail: bare SPM executable gets .accessory activation — no window. Set policy BEFORE scenes build. // ponytail: bare SPM executable gets .accessory activation — no window. Set policy BEFORE scenes build.
final class AppDelegate: NSObject, NSApplicationDelegate { final class AppDelegate: NSObject, NSApplicationDelegate {
func applicationWillFinishLaunching(_ notification: Notification) { func applicationWillFinishLaunching(_: Notification) {
NSApp.setActivationPolicy(.regular) NSApp.setActivationPolicy(.regular)
} }
func applicationDidFinishLaunching(_ notification: Notification) {
func applicationDidFinishLaunching(_: Notification) {
NSApp.activate(ignoringOtherApps: true) NSApp.activate(ignoringOtherApps: true)
} }
} }