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

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

452 lines
17 KiB
Swift

// Spike (#74) — THROWAWAY. apex → HTML → WKWebView reading surface.
// Proves: data-source-line mapping, CSS-var typography, ⌘-click links, in-app apex latency, first paint.
import AppKit
import SwiftUI
import WebKit
// MARK: - Mapping (pure, self-checked)
/// ponytail: sentinel pre-pass — apex passes HTML comments through verbatim, we stamp after.
enum MarkdownChunker {
/// Prepend `<!--S:N-->` (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("<!--S:\(i + 1)-->")
while i < lines.count, !isBlank(lines[i]) {
out.append(String(lines[i])); i += 1
}
}
return out.joined(separator: "\n")
}
}
/// Rewrites `<!--S:N-->` 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:(\d+)-->\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
}
/// 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 <ul> — 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)
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 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)
}
}
/// 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 {
"<!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.
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
init(onStats: @escaping (Stats) -> Void, onSourceLine: @escaping (String, Int) -> Void) {
self.onStats = onStats
self.onSourceLine = onSourceLine
}
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(_: WKWebView, didFail _: WKNavigation!, withError error: Error) {
FileHandle.standardError.write(Data("didFail: \(error)\n".utf8))
}
func webView(_: WKWebView, didFailProvisionalNavigation _: WKNavigation!, withError error: Error) {
FileHandle.standardError.write(Data("didFailProvisional: \(error)\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(_: 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(_: 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)
}
}
// 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) }
}
}
// 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)
}
}
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 == "<!--S:1-->\n# T\n\n<!--S:3-->\nA\n\n<!--S:5-->\nB\n1. x\n\n<!--S:9-->\nC", stamped)
// stamper: sentinel → attribute on following element; multi-digit lines
let html = "<h1>T</h1>\n<!--S:1-->\n<p>A</p>\n<!--S:12-->\n<ul>\n<li>B</li>\n</ul>"
let out = HTMLStamper.stamp(html)
assert(out == "<h1>T</h1>\n<p data-source-line=\"1\">A</p>\n<ul data-source-line=\"12\">\n<li>B</li>\n</ul>", out)
print("self-check OK")
}
}
final class AppDelegate: NSObject, NSApplicationDelegate {
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?
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 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
}
}
}