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
+252 -133

No files matched your search

+4 -4
View File
@@ -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)";
+2 -1
View File
@@ -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
}
-1
View File
@@ -162,7 +162,6 @@ struct ReadingSurface: NSViewRepresentable {
return blocks.first { $0.sourceRange.location >= caret }?.sourceLine
}
// MARK: WKNavigationDelegate
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"] {
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")
+21 -9
View File
@@ -11,6 +11,7 @@
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)
@@ -24,6 +25,7 @@ enum Tok {
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)
}
@@ -39,6 +41,7 @@ extension Color {
}
// MARK: - Mock state
final class GateModel: ObservableObject {
enum Phase: Equatable { case checking, passed, failed }
@Published var phase: Phase = .checking
@@ -52,13 +55,14 @@ final class GateModel: ObservableObject {
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
guard let self, token == myToken else { return }
phase = nextPass ? .passed : .failed
}
}
}
// MARK: - Shared pieces
struct EnginePill: View {
@EnvironmentObject var model: GateModel
@@ -82,7 +86,7 @@ struct EnginePill: View {
.background(Tok.surface, in: RoundedRectangle(cornerRadius: 10))
.overlay(
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 {
content.opacity(0.35).animation(
Animation.easeInOut(duration: 0.55).repeatForever(autoreverses: true),
value: active)
value: active,
)
} else {
content
}
@@ -163,14 +168,17 @@ struct RecheckButton: View {
}
// MARK: - Mock workspace (context for the gate to sit over)
struct MockWorkspace: View {
@EnvironmentObject var model: GateModel
var banner: AnyView? = nil
var banner: AnyView?
var body: some View {
VStack(spacing: 0) {
toolbar
if let banner { banner }
if let banner {
banner
}
HStack(spacing: 0) {
rail
editor
@@ -237,6 +245,7 @@ struct MockWorkspace: View {
}
// MARK: - Variant A — blocking sheet, every launch
struct VariantA: View {
@EnvironmentObject var model: GateModel
@State private var showSteps = false
@@ -251,7 +260,7 @@ struct VariantA: View {
.background(Tok.surface, in: RoundedRectangle(cornerRadius: 14))
.overlay(
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)
}
@@ -313,6 +322,7 @@ struct VariantA: View {
}
// MARK: - Variant B — gate window (first run), pill (repeat runs)
struct VariantB: View {
@EnvironmentObject var model: GateModel
@@ -393,6 +403,7 @@ private struct GateWindow: View {
}
// MARK: - Variant C — inline banner, never blocks
struct VariantC: View {
@EnvironmentObject var model: GateModel
@@ -413,10 +424,10 @@ struct VariantC: View {
Image(systemName: "exclamationmark.triangle.fill")
.foregroundStyle(Tok.accent)
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.")
.font(.system(size: 12.5))
.foregroundStyle(Tok.muted))
.foregroundStyle(Tok.muted)
InstallSteps()
}
Spacer(minLength: 12)
@@ -441,6 +452,7 @@ struct VariantC: View {
}
// MARK: - Root + switcher
struct GatePrototypeRoot: View {
@StateObject private var model = GateModel()
@State private var variant = "A"
+1 -1
View File
@@ -4,5 +4,5 @@ import PackageDescription
let package = Package(
name: "ApexHTMLSpike",
platforms: [.macOS(.v26)],
targets: [.executableTarget(name: "ApexHTMLSpike")]
targets: [.executableTarget(name: "ApexHTMLSpike")],
)
@@ -15,10 +15,16 @@ enum MarkdownChunker {
var out: [String] = []
var i = 0
while i < lines.count {
if isBlank(lines[i]) { i += 1; continue }
if !out.isEmpty { out.append("") }
if isBlank(lines[i]) {
i += 1; continue
}
if !out.isEmpty {
out.append("")
}
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")
}
@@ -38,8 +44,12 @@ enum HTMLStamper {
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 }
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
}
@@ -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 = """
:root {
--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>"
}
// 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 = """
function stamped(el){ return el.closest('[data-source-line]'); }
document.addEventListener('click', function(e){
@@ -218,32 +228,34 @@ struct ReadingWebView: NSViewRepresentable {
self.onSourceLine = onSourceLine
}
func webView(_ wv: WKWebView, didFinish: WKNavigation!) {
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) {
/// 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) {
func webView(_: WKWebView, didFailProvisionalNavigation _: WKNavigation!, withError error: Error) {
FileHandle.standardError.write(Data("didFailProvisional: \(error)\n".utf8))
}
nonisolated func webViewWebContentProcessDidTerminate(_ wv: WKWebView) {
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) {
/// 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" {
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 {
@@ -252,18 +264,24 @@ struct ReadingWebView: NSViewRepresentable {
decisionHandler(.cancel)
}
func userContentController(_ ucc: WKUserContentController, didReceive message: WKScriptMessage) {
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) }
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) }
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
@@ -282,8 +300,12 @@ struct SpikeApp: App {
// 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) }
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.
@@ -302,7 +324,9 @@ struct SpikeApp: App {
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 }
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)
@@ -325,7 +349,7 @@ struct SpikeApp: App {
}
final class AppDelegate: NSObject, NSApplicationDelegate {
nonisolated func applicationDidFinishLaunching(_ n: Notification) {}
nonisolated func applicationDidFinishLaunching(_: Notification) {}
}
struct ContentView: View {
@@ -353,18 +377,30 @@ struct ContentView: View {
// 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 }
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 }
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 }
.toolbar {
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) }
}
@@ -375,9 +411,15 @@ struct ContentView: View {
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) }
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)
@@ -388,11 +430,12 @@ struct ContentView: View {
if let a = arg {
let u = URL(fileURLWithPath: a).standardizedFileURL
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]
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) {
let list = try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)
{
files = list.filter { $0.pathExtension == "md" }.sorted { $0.lastPathComponent < $1.lastPathComponent }
selected = files.first
}
@@ -401,6 +444,8 @@ struct ContentView: View {
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 }
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(
name: "BlocksSpike",
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 {
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 }
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
}
@@ -49,11 +57,11 @@ nonisolated enum BlockModel {
/// 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
case .heading1: String(raw.dropFirst(2))
case .heading2: String(raw.dropFirst(3))
case .quote: String(raw.dropFirst(2))
case .hr: ""
case .paragraph: raw
}
}
+38 -18
View File
@@ -18,7 +18,9 @@ struct SpikeApp: App {
// ponytail: one runnable check — `swift run --package-path spike/blocks --check`
init() {
if CommandLine.arguments.contains("--check") { Self.selfCheck(); exit(0) }
if CommandLine.arguments.contains("--check") {
Self.selfCheck(); exit(0)
}
}
static func selfCheck() {
@@ -47,7 +49,7 @@ struct SpikeApp: App {
// 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 {
for _ in 0 ..< 3 {
let t0 = DispatchTime.now()
_ = BlockModel.parse(perf)
ms = Double(DispatchTime.now().uptimeNanoseconds - t0.uptimeNanoseconds) / 1e6
@@ -77,8 +79,10 @@ struct ContentView: View {
/// 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 }
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.)"
}
@@ -101,7 +105,7 @@ struct ContentView: View {
onFocus: {
focusedID = block.id
hint = "Focused block \(block.id.uuidString.prefix(4)) — type to edit."
}
},
)
.id(block.id)
}
@@ -110,7 +114,9 @@ struct ContentView: View {
.padding(.horizontal, 40)
.padding(.vertical, 24)
.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) {
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) }
if anchorID != nil {
Text("anchored").foregroundStyle(.secondary).font(.caption)
}
Spacer()
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 }
if (0 ... bw.count - qw.count).contains(where: { s in
(s ..< s + qw.count).allSatisfy { bw[$0] == qw[$0 - s] }
}) { return b }
}) {
return b
}
}
return nil
}
@@ -216,7 +226,8 @@ private struct BlockRow: View {
init(block: Block, isFocused: Bool, isAnchored: Bool,
onEdit: @escaping (String) -> Void, onSplit: @escaping (Int) -> Void,
onMerge: @escaping () -> Void, onFocus: @escaping () -> Void) {
onMerge: @escaping () -> Void, onFocus: @escaping () -> Void)
{
self.block = block
self.isFocused = isFocused
self.isAnchored = isAnchored
@@ -301,20 +312,28 @@ struct SingleBlockEditor: NSViewRepresentable {
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] { [
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 }
init(_ parent: SingleBlockEditor) {
self.parent = parent
}
func textDidChange(_ notification: Notification) {
guard let tv = notification.object as? NSTextView else { return }
@@ -322,7 +341,7 @@ struct SingleBlockEditor: NSViewRepresentable {
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 {
if commandSelector == #selector(NSResponder.insertNewline(_:)) {
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.
final class AppDelegate: NSObject, NSApplicationDelegate {
func applicationWillFinishLaunching(_ notification: Notification) {
func applicationWillFinishLaunching(_: Notification) {
NSApp.setActivationPolicy(.regular)
}
func applicationDidFinishLaunching(_ notification: Notification) {
func applicationDidFinishLaunching(_: Notification) {
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).
.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)
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 {
NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17)
?? NSFont.systemFont(ofSize: 17, weight: .regular, width: .standard)
@@ -38,7 +38,7 @@ enum ProseTheme {
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)
comments: .init(color: dim),
)
}
}
@@ -59,7 +59,7 @@ final class ProseHighlighter: HighlightProviding {
textView: TextView,
range: NSRange,
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)
}
@@ -67,13 +67,13 @@ final class ProseHighlighter: HighlightProviding {
func queryHighlightsFor(
textView: TextView,
range: NSRange,
completion: @escaping @MainActor (Result<[HighlightRange], Error>) -> Void
completion: @escaping @MainActor (Result<[HighlightRange], Error>) -> Void,
) {
wrapped.queryHighlightsFor(textView: textView, range: range) { result in
switch result {
case .failure(let error):
case let .failure(error):
completion(.failure(error))
case .success(let tsRanges):
case let .success(tsRanges):
var out = tsRanges
let ns = textView.string as NSString
let safe = range.intersection(NSRange(location: 0, length: ns.length)) ?? range
@@ -95,13 +95,13 @@ final class ProseHighlighter: HighlightProviding {
if textLen > 0 {
out.append(HighlightRange(
range: NSRange(location: lineRange.location + markerLen, length: textLen),
capture: .type
capture: .type,
))
}
// marker → dim
out.append(HighlightRange(
range: NSRange(location: lineRange.location, length: markerLen),
capture: .keyword
capture: .keyword,
))
} else if line.hasPrefix(">") {
// 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) {
out.append(HighlightRange(
range: NSRange(location: lineRange.location + off, length: 1),
capture: .keyword
capture: .keyword,
))
}
}
@@ -147,15 +147,15 @@ nonisolated enum AnchorSearch {
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({
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)
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`
init() {
if CommandLine.arguments.contains("--check") { Self.selfCheck(); exit(0) }
if CommandLine.arguments.contains("--check") {
Self.selfCheck(); exit(0)
}
}
static func selfCheck() {
@@ -201,7 +203,7 @@ struct SpikeApp: App {
"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 }
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")
@@ -282,7 +284,7 @@ struct ContentView: View {
configuration: config,
state: $editorState,
highlightProviders: [ProseHighlighter()],
coordinators: [ControllerCapture(onCapture: { box.controller = $0 })]
coordinators: [ControllerCapture(onCapture: { box.controller = $0 })],
)
.frame(maxWidth: 720)
.frame(maxWidth: .infinity)
@@ -295,17 +297,17 @@ struct ContentView: View {
theme: ProseTheme.theme,
font: ProseTheme.bodyFont,
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(
showGutter: false, // no line numbers in a writing app
showMinimap: false,
showReformattingGuide: false,
showFoldingRibbon: false,
invisibleCharactersConfiguration: .init(showSpaces: false, showTabs: false, showLineEndings: false),
warningCharacters: []
)
warningCharacters: [],
),
)
}
@@ -315,7 +317,9 @@ struct ContentView: View {
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) }
if let note = anchorNote {
Text(note).foregroundStyle(.secondary).font(.caption)
}
Spacer()
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.
controller.textView.emphasisManager?.replaceEmphases(
[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)
}
@@ -350,9 +354,13 @@ struct ContentView: View {
final class ControllerBox: @unchecked Sendable {
var controller: TextViewController?
}
final class ControllerCapture: TextViewCoordinator {
let onCapture: (TextViewController) -> Void
init(onCapture: @escaping (TextViewController) -> Void) { self.onCapture = onCapture }
init(onCapture: @escaping (TextViewController) -> Void) {
self.onCapture = onCapture
}
func prepareCoordinator(controller: TextViewController) {
onCapture(controller)
}
@@ -373,7 +381,7 @@ extension SpikeApp {
}
let attr = (try? AttributedString(
markdown: p,
options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace)
options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace),
)) ?? AttributedString(p)
return (level, attr)
}
@@ -382,10 +390,11 @@ extension SpikeApp {
// ponytail: bare SPM executable gets .accessory activation — no window. Set policy BEFORE scenes build.
final class AppDelegate: NSObject, NSApplicationDelegate {
func applicationWillFinishLaunching(_ notification: Notification) {
func applicationWillFinishLaunching(_: Notification) {
NSApp.setActivationPolicy(.regular)
}
func applicationDidFinishLaunching(_ notification: Notification) {
func applicationDidFinishLaunching(_: Notification) {
NSApp.activate(ignoringOtherApps: true)
}
}
+1 -1
View File
@@ -4,5 +4,5 @@ import PackageDescription
let package = Package(
name: "TextKit2Spike",
platforms: [.macOS(.v26)],
targets: [.executableTarget(name: "TextKit2Spike")]
targets: [.executableTarget(name: "TextKit2Spike")],
)
@@ -62,14 +62,18 @@ struct EditorPane: NSViewRepresentable {
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
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 }
@@ -13,10 +13,18 @@ nonisolated enum ProsePresenter {
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 }
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
}
@@ -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.
static var serif: NSFont { NSFont.systemFont(ofSize: 17, weight: .regular, width: .compressed) }
static var bodyFont: NSFont { NSFontManager.shared.font(withFamily: "Iowan Old Style", traits: [], weight: 5, size: 17)
?? NSFont.systemFont(ofSize: 17) }
static var serif: NSFont {
NSFont.systemFont(ofSize: 17, weight: .regular, width: .compressed)
}
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),
] }
]
}
static func attributes(for kind: LineKind) -> [NSAttributedString.Key: Any] {
switch kind {
@@ -80,15 +95,16 @@ nonisolated enum ProsePresenter {
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 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))) }
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() {
@@ -107,8 +123,8 @@ nonisolated enum ProsePresenter {
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 }) {
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)
@@ -16,7 +16,9 @@ struct SpikeApp: App {
// ponytail: one runnable check for the anchor logic — `swift run TextKit2Spike --check`
init() {
if CommandLine.arguments.contains("--check") { Self.selfCheck(); exit(0) }
if CommandLine.arguments.contains("--check") {
Self.selfCheck(); exit(0)
}
}
static func selfCheck() {
@@ -67,7 +69,7 @@ struct ContentView: View {
@State private var loadMs: Double = 0
@State private var doc: NSAttributedString
// calibration piece default; PERF-3k via arg
/// 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"
@@ -115,7 +117,9 @@ struct ContentView: View {
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) }
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)
}
@@ -139,10 +143,11 @@ struct ContentView: View {
// ponytail: bare SPM executable gets .accessory activation — no window. Set policy BEFORE scenes build.
final class AppDelegate: NSObject, NSApplicationDelegate {
func applicationWillFinishLaunching(_ notification: Notification) {
func applicationWillFinishLaunching(_: Notification) {
NSApp.setActivationPolicy(.regular)
}
func applicationDidFinishLaunching(_ notification: Notification) {
func applicationDidFinishLaunching(_: Notification) {
NSApp.activate(ignoringOtherApps: true)
}
}